obi-sdk 0.19.45-beta.2 → 0.19.45-beta.3
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 +2 -2
- package/dist/obi-sdk.standalone.iife.js +2 -2
- package/package.json +1 -1
|
@@ -39,7 +39,7 @@ 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 Ws(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 qs(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 TS=Object.freeze({__proto__:null,removeExtmapAllowMixed:Go,shimAddIceCandidateNullOrEmpty:Ws,shimConnectionState:Vo,shimMaxMessageSize:zs,shimParameterlessSetLocalDescription:qs,shimRTCIceCandidate:Gs,shimRTCIceCandidateRelayProtocol:jo,shimSendThrowTypeError:Hs});function kS(){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=bh,i=gS(n),r={browserDetails:i,commonShim:TS,extractVersion:Vs,disableLog:pS,disableWarnings:mS,sdp:yS};switch(i.browser){case"chrome":if(!Oh||!Uo||!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=Oh,Ws(n,i),qs(n),Ch(n,i),xh(n),Uo(n,i),wh(n),Ph(n,i),_h(n),Eh(n),Ih(n,i),Gs(n),jo(n),Vo(n),zs(n,i),Hs(n),Go(n,i);break;case"firefox":if(!Gh||!Bo||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=Gh,Ws(n,i),qs(n),Ah(n,i),Bo(n,i),Nh(n),Dh(n),Mh(n),Lh(n),Uh(n),Bh(n),Fh(n),jh(n),Vh(n),Gs(n),Vo(n),zs(n,i),Hs(n);break;case"safari":if(!Qh||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=Qh,Ws(n,i),qs(n),$h(n),Xh(n),Wh(n),zh(n),Hh(n),Yh(n),qh(n),Jh(n),Gs(n),jo(n),zs(n,i),Hs(n),Go(n,i);break;default:t("Unsupported browser!");break}return r}kS({window:typeof window>"u"?void 0:window});const SS=10,Ks="lk_e2ee",CS={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:SS,keyringSize:16};var On;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(On||(On={}));var tf;(function(n){n.KeyRatcheted="keyRatcheted"})(tf||(tf={}));var An;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(An||(An={}));var nf;(function(n){n.Error="cryptorError"})(nf||(nf={}));function xS(){return wS()||zo()}function zo(){return typeof window.RTCRtpScriptTransform<"u"}function wS(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class k_ extends Xt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,r)=>{ie.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},CS),e),this.on(On.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(On.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(On.RatchetRequest,e,t)}}class Nn extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var se;(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"})(se||(se={}));class pe extends Nn{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=se[t]}}class Ho extends Nn{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class an extends Nn{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class _S extends Nn{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Ge extends Nn{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Wo extends Nn{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class qo extends Nn{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class rf extends Nn{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:No[t]}}var $s;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})($s||($s={})),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}($s||($s={}));var sf;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(sf||(sf={}));var L;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(L||(L={}));var j;(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"})(j||(j={}));var U;(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"})(U||(U={}));var D;(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"})(D||(D={}));function ES(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const RS=/version\/(\d+(\.?_?\d+)+)/i;let Ko;function Lt(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(Ko===void 0||e){const i=PS.find(r=>{let{test:s}=r;return s.test(t)});Ko=i==null?void 0:i.describe(t)}return Ko}const PS=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Ys(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:$o(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Ys(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:$o(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Ys(RS,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:$o(n)}}}];function Ys(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 $o(n){return n.includes("mac os")?Ys(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var IS="2.13.0";const OS=IS,AS=16;class Xe{}Xe.setTimeout=function(){return setTimeout(...arguments)},Xe.setInterval=function(){return setInterval(...arguments)},Xe.clearTimeout=function(){return clearTimeout(...arguments)},Xe.clearInterval=function(){return clearInterval(...arguments)};const NS=5e3,lr=[];var wt;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(wt||(wt={}));class I extends Xt.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=ie,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),NS):this.handleAppVisibilityChanged()},this.log=sn((r=i.loggerName)!==null&&r!==void 0?r:Mt.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)),ue(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"&&(lr.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&lr.splice(lr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),_i(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?D.AudioPlaybackStarted:D.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?D.AudioPlaybackFailed:D.VideoPlaybackFailed,s):s.name==="AbortError"?ie.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):ie.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(D.ElementAttached,e),e}detach(e){try{if(e){Ei(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(D.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Ei(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(D.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=sn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),lr.forEach(i=>{i.parentElement||(t=!1)}),t&&lr.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(){mt()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){mt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function _i(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)),(!Mn()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Mn()||Ri())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ei(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(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function r(l){switch(l){case e.Audio:return It.AUDIO;case e.Video:return It.VIDEO;default:return It.DATA}}n.kindToProto=r;function s(l){switch(l){case It.AUDIO:return e.Audio;case It.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(l){switch(l){case t.Camera:return je.CAMERA;case t.Microphone:return je.MICROPHONE;case t.ScreenShare:return je.SCREEN_SHARE;case t.ScreenShareAudio:return je.SCREEN_SHARE_AUDIO;default:return je.UNKNOWN}}n.sourceToProto=a;function o(l){switch(l){case je.CAMERA:return t.Camera;case je.MICROPHONE:return t.Microphone;case je.SCREEN_SHARE:return t.ScreenShare;case je.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(l){switch(l){case _o.ACTIVE:return i.Active;case _o.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(I||(I={}));class fe{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 MS=["vp8","h264"],LS=["vp8","h264","vp9","av1"];function DS(n){return!!MS.find(e=>e===n)}var af;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(af||(af={}));var Yo;(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}})(Yo||(Yo={}));const ur={h90:new fe(160,90,9e4,20),h180:new fe(320,180,16e4,20),h216:new fe(384,216,18e4,20),h360:new fe(640,360,45e4,20),h540:new fe(960,540,8e5,25),h720:new fe(1280,720,17e5,30),h1080:new fe(1920,1080,3e6,30),h1440:new fe(2560,1440,5e6,30),h2160:new fe(3840,2160,8e6,30)},Xo={h120:new fe(160,120,7e4,20),h180:new fe(240,180,125e3,20),h240:new fe(320,240,14e4,20),h360:new fe(480,360,33e4,20),h480:new fe(640,480,5e5,20),h540:new fe(720,540,6e5,25),h720:new fe(960,720,13e5,30),h1080:new fe(1440,1080,23e5,30),h1440:new fe(1920,1440,38e5,30)},Jo={h360fps3:new fe(640,360,2e5,3,"medium"),h360fps15:new fe(640,360,4e5,15,"medium"),h720fps5:new fe(1280,720,8e5,5,"medium"),h720fps15:new fe(1280,720,15e5,15,"medium"),h720fps30:new fe(1280,720,2e6,30,"medium"),h1080fps15:new fe(1920,1080,25e5,15,"medium"),h1080fps30:new fe(1920,1080,5e6,30,"medium"),original:new fe(0,0,7e6,30,"medium")},US="|",of="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function BS(n){const e=n.split(US);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function pt(n){return y(this,void 0,void 0,function*(){return new Promise(e=>Xe.setTimeout(e,n))})}function Qo(){return"addTransceiver"in RTCPeerConnection.prototype}function Zo(){return"addTrack"in RTCPeerConnection.prototype}function FS(){if(!("getCapabilities"in RTCRtpSender)||Mn())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 jS(){if(!("getCapabilities"in RTCRtpSender)||Ri())return!1;if(Mn()){const t=Lt();if(t!=null&&t.version&&Jn(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 dr(n){return n==="av1"||n==="vp9"}function ec(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function VS(){return typeof RTCPeerConnection>"u"?!1:Qo()||Zo()}function Ri(){var n;return((n=Lt())===null||n===void 0?void 0:n.name)==="Firefox"}function Mn(){var n;return((n=Lt())===null||n===void 0?void 0:n.name)==="Safari"}function GS(){const n=Lt();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function cf(){var n,e;return mt()?(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 zS(){const n=Lt(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Jn(e,n.osVersion)>=0?!0:n.name==="Safari"&&Jn(e,n.version)>=0}function mt(){return typeof document<"u"}function Jt(){return navigator.product=="ReactNative"}function tc(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function lf(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function uf(){if(!Jt())return;let n=lf();if(n)return n.platform}function df(){if(mt())return window.devicePixelRatio;if(Jt()){let n=lf();if(n)return n.devicePixelRatio}return 1}function Jn(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 HS(n){for(const e of n)e.target.handleResize(e)}function WS(n){for(const e of n)e.target.handleVisibilityChanged(e)}let nc=null;const hf=()=>(nc||(nc=new ResizeObserver(HS)),nc);let ic=null;const ff=()=>(ic||(ic=new IntersectionObserver(WS,{root:null,rootMargin:"0px"})),ic);function qS(){var n;const e=new Lk({sdk:Xd.JS,protocol:AS,version:OS});return Jt()&&(e.os=(n=uf())!==null&&n!==void 0?n:""),e}function pf(){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 hr;function rc(){if(!hr){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(),[hr]=i.stream.getAudioTracks(),!hr)throw Error("Could not get empty media stream audio track");hr.enabled=!1}return hr.clone()}class sc{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 KS(n){return LS.includes(n)}function Ln(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 $S(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function ac(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function YS(n,e){return n.segments.map(t=>{let{id:i,text:r,language:s,startTime:a,endTime:o,final:c}=t;var l;const u=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),d=Date.now();return c?e.delete(i):e.set(i,u),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:s,firstReceivedTime:u,lastReceivedTime:d}})}function XS(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 mf(n){switch(n.reason){case se.LeaveRequest:return n.context;case se.Cancelled:return Ot.CLIENT_INITIATED;case se.NotAllowed:return Ot.USER_REJECTED;case se.ServerUnreachable:return Ot.JOIN_FAILURE;default:return Ot.UNKNOWN_REASON}}function Xs(n){return n!==void 0?Number(n):void 0}function Qn(n){return n!==void 0?BigInt(n):void 0}function Pi(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function on(n){return!!n&&n.kind==I.Kind.Audio}function Ii(n){return!!n&&n.kind==I.Kind.Video}function Dn(n){return Pi(n)&&Ii(n)}function Zn(n){return Pi(n)&&on(n)}function oc(n){return!!n&&!n.isLocal}function JS(n){return!!n&&!n.isLocal}function cc(n){return oc(n)&&Ii(n)}function QS(n){return n.isLocal}function ZS(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 gf(n,e,t){var i,r,s,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=Tf(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&&(lc(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(h.audio.processor=c??u)),h.video&&(lc(h.video,t),(r=(a=h.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||d)&&(h.video.processor=l??d)),h}function lc(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function uc(n){var e,t,i,r;const s={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":lc(o,c.resolution);break;default:o[l]=c[l]}}),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 vf(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=bf();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 pt(t),r.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return i.close(),!c}return!1}()})}function bf(){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 eC(n){return n==="audioinput"?I.Source.Microphone:n==="videoinput"?I.Source.Camera:I.Source.Unknown}function yf(n){return n===I.Source.Microphone?"audioinput":n===I.Source.Camera?"videoinput":void 0}function tC(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,Mn()?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 Js(n){return n.split("/")[1].toLowerCase()}function nC(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Oo({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ue(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?ue(n.track):{})}}function iC(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function rC(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 Tf(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:ES(e)}}function sC(n){switch(n){case je.CAMERA:return I.Source.Camera;case je.MICROPHONE:return I.Source.Microphone;case je.SCREEN_SHARE:return I.Source.ScreenShare;case je.SCREEN_SHARE_AUDIO:return I.Source.ScreenShareAudio;default:return I.Source.Unknown}}class aC extends Xt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,r;const{kind:s,data:a}=t.data;switch(s){case"error":ie.error(a.error.message),this.emit(An.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(An.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(An.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(On.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{ie.error("e2ee worker encountered an error:",{error:t.error}),this.emit(An.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!xS())throw new Ho("tried to setup end-to-end encryption on an unsupported browser");if(ie.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:lS.getLevel()}};this.worker&&(ie.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ie.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ie.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(U.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(L.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==bt.NONE,r.identity)),e.on(L.ConnectionStateChanged,i=>{i===ce.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==bt.NONE,r.identity)})})}).on(L.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(L.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(L.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(j.LocalTrackPublished,i=>y(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(On.SetKey,i=>this.postKey(i)).on(On.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"?Js(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Pi(e)||!t){t||ie.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(zo()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ks in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,a=e.readableStream;if(!s||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:r,participantIdentity:i}};this.worker.postMessage(o,[a,s])}e[Ks]=!0}})}handleSender(e,t,i){var r;if(!(Ks 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(zo()){ie.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{ie.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[Ks]=!0}}}const dc="default";class We{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new We),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=We.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){ie.debug("awaiting getUserMedia promise");try{t?yield We.userMediaPromiseMap.get(t):yield Promise.all(We.userMediaPromiseMap.values())}catch{ie.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Mn()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const l=c.label==="",u=t?c.kind===t:!0;return l&&u}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),l.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!==dc)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===dc);if(!s){ie.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==dc&&o.groupId===(i??s.groupId));if(!a){ie.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?We.userMediaPromiseMap.has(e):We.userMediaPromiseMap.size>0}}We.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],We.userMediaPromiseMap=new Map;var fr;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(fr||(fr={}));class oC{constructor(){this.pendingTasks=new Map,this.taskMutex=new dt,this.nextTaskIndex=0}run(e){return y(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:fr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=fr.RUNNING,yield e()}finally{t.status=fr.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 cC(n,e){const t=new URL($S(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),kf(t,"rtc")}function lC(n){const e=new URL(ac(n));return kf(e,"validate")}function uC(n){return n.endsWith("/")?n:"".concat(n,"/")}function kf(n,e){return n.pathname="".concat(uC(n.pathname)).concat(e),n.toString()}const dC=["syncState","trickle","offer","answer","simulate","leave"];function hC(n){const e=dC.indexOf(n.case)>=0;return ie.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ye;(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"})(ye||(ye={}));class hc{get currentState(){return this.state}get isDisconnected(){return this.state===ye.DISCONNECTING||this.state===ye.DISCONNECTED}get isEstablishingConnection(){return this.state===ye.CONNECTING||this.state===ye.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=ye.DISCONNECTED,this.log=ie,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=sn((i=t.loggerName)!==null&&i!==void 0?i:Mt.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new oC,this.queuedRequests=[],this.closingLock=new dt,this.connectionLock=new dt,this.state=ye.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=ye.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=ye.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=qS(),a=fC(t,s,i),o=cC(e,a),c=lC(o);return new Promise((l,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 pe("room connection has been cancelled (signal)",se.Cancelled))}),f=setTimeout(()=>{this.close(),u(new pe("room connection has timed out (signal)",se.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const m=new URL(o);m.searchParams.has("access_token")&&m.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(m),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=p=>y(this,void 0,void 0,function*(){if(this.state!==ye.CONNECTED){this.state=ye.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(c);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();u(new pe(b,se.NotAllowed,v.status))}else u(new pe("Encountered unknown websocket error during connection: ".concat(p.toString()),se.InternalError,v.status))}catch(v){u(new pe(v instanceof Error?v.message:"server was not reachable",se.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>y(this,void 0,void 0,function*(){var v,b,C;let w;if(typeof p.data=="string"){const T=JSON.parse(p.data);w=nh.fromJson(T,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)w=nh.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==ye.CONNECTED){let T=!1;if(((v=w.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=ye.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=w.message.value.pingTimeout,this.pingIntervalDuration=w.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(w.message.value)):this.state===ye.RECONNECTING&&w.message.case!=="leave"?(this.state=ye.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=w.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(w.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),T=!0)):this.isEstablishingConnection&&w.message.case==="leave"?u(new pe("Received leave request while trying to (re)connect",se.LeaveRequest,void 0,w.message.value.reason)):i.reconnect||u(new pe("did not receive join response, got ".concat((C=w.message)===null||C===void 0?void 0:C.case," instead"),se.InternalError)),!T)return}this.signalLatency&&(yield pt(this.signalLatency)),this.handleSignalResponse(w)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new pe("Websocket got closed during a (re)connection attempt",se.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{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=ye.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,pt(250)])),e.ws=void 0}}finally{t&&(e.state=ye.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Qs(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Qs(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 Po({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Io({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 ah({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 sh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new lh({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Se.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new hh({timestamp:Se.parse(Date.now()),rtt:Se.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new rh({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Us({reason:Ot.CLIENT_INITIATED,action:xi.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&&!hC(t)&&i.state===ye.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 pt(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 Bk({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=Sf(r.value);this.onAnswer&&this.onAnswer(a)}else if(r.case==="offer"){const a=Sf(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===ye.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=Xe.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&&Xe.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=Xe.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Xe.clearInterval(this.pingInterval)}}function Sf(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 Qs(n){return new Yn({sdp:n.sdp,type:n.type})}function fC(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",Jt()?"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 Dt={},fc={},pc={exports:{}},Cf;function mc(){if(Cf)return pc.exports;Cf=1;var n=pc.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")})}),pc.exports}var xf;function pC(){return xf||(xf=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,l,u){if(u&&!l)c[u]=e(o[1]);else for(var d=0;d<l.length;d+=1)o[d+1]!=null&&(c[l[d]]=e(o[d+1]))},i=function(o,c,l){var u=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:u&&!c[o.name]&&(c[o.name]={});var d=o.push?{}:u?c[o.name]:c;t(l.match(o.reg),d,o.names,o.name),o.push&&c[o.push].push(d)},r=mc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},l=[],u=c;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var m=0;m<(r[h]||[]).length;m+=1){var p=r[h][m];if(p.reg.test(f))return i(p,u,f)}}),c.media=l,c};var a=function(o,c){var l=c.split(/=(.+)/,2);return l.length===2?o[l[0]]=e(l[1]):l.length===1&&c.length>1&&(o[l[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 c=[],l=o.split(" ").map(e),u=0;u<l.length;u+=3)c.push({component:l[u],ip:l[u+1],port:l[u+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(l){var u,d=!1;return l[0]!=="~"?u=e(l):(u=e(l.substring(1,l.length)),d=!0),{scid:u,paused:d}})})}}(fc)),fc}var gc,wf;function mC(){if(wf)return gc;wf=1;var n=mc(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,l=c.length;return a.replace(e,function(u){if(o>=l)return u;var d=c[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(a,o,c){var l=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,u=[a+"="+l];if(o.names)for(var d=0;d<o.names.length;d+=1){var h=o.names[d];o.name?u.push(c[o.name][h]):u.push(c[o.names[d]])}else u.push(c[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 gc=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 c=o.outerOrder||r,l=o.innerOrder||s,u=[];return c.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)),l.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(m){u.push(i(h,f,m))})})})}),u.join(`\r
|
|
41
41
|
`)+`\r
|
|
42
|
-
`},gc}var _f;function gC(){if(_f)return Dt;_f=1;var n=pC(),e=mC(),t=mc();return Dt.grammar=t,Dt.write=e,Dt.parse=n.parse,Dt.parseParams=n.parseParams,Dt.parseFmtpConfig=n.parseFmtpConfig,Dt.parsePayloads=n.parsePayloads,Dt.parseRemoteCandidates=n.parseRemoteCandidates,Dt.parseImageAttributes=n.parseImageAttributes,Dt.parseSimulcastStreamList=n.parseSimulcastStreamList,Dt}var Un=gC();function vc(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,c=t.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),m=this;return new Promise(function(p,v){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!a){var w=n.apply(m,f);o&&o(w),u.forEach(function(T){return(0,T.resolve)(w)}),u=[]}},d()),b){var C=n.apply(m,f);return o&&o(C),p(C)}u.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(m){return(0,m.reject)(f)}),u=[]},h}const vC=.7,bC=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Ef extends Xt.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=ie,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=vc(r=>y(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),bC),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=sn((i=t.loggerName)!==null&&i!==void 0?i:Mt.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}=yC(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=Un.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(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0)return!0;let c=!1;for(const l of s.fmtp)if(l.payload===o){l.config=l.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(l.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Un.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(Oi.NegotiationComplete),e.sdp&&Un.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Oi.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=Un.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{Pf(s),s.type==="audio"?Rf(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(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0||(dr(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*vC);for(const l of s.fmtp)if(l.payload===o){l.config.includes("x-google-start-bitrate")||(l.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,Un.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Un.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Pf(r),r.type==="audio"&&Rf(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Un.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 Ge("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 Ge("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 Wo(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===of))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:of})}}}function Rf(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 yC(n){var e;const t=[],i=[],r=Un.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(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function Pf(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 bc="vp8",TC={audioPreset:Yo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Jo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:bc,backupCodec:!0},If={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Of={deviceId:{ideal:"default"},resolution:ur.h720.resolution},kC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new dS,disconnectOnPageLeave:!0,webAudioMix:!1},yc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Re;(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"})(Re||(Re={}));class SC{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=yc.peerConnectionTimeout,this.log=ie,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Re.CONNECTED:o.some(c=>c==="failed")?this.state=Re.FAILED:o.some(c=>c==="connecting")?this.state=Re.CONNECTING:o.every(c=>c==="closed")?this.state=Re.CLOSED:o.some(c=>c==="closed")?this.state=Re.CLOSING:o.every(c=>c==="new")&&(this.state=Re.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Re[a]," to ").concat(Re[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=sn((r=i.loggerName)!==null&&r!==void 0?r:Mt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Ef(e,i),this.subscriber=new Ef(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,Nt.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Nt.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=Re.NEW,this.connectionLock=new dt,this.remoteOfferLock=new dt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return 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===Nt.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(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.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===Nt.PUBLISHER?this.publisher.getConnectedAddress():e===Nt.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((c,l)=>y(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Xe.clearTimeout(d),l(new pe("room connection has been cancelled",se.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Xe.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(new pe("could not establish pc connection",se.InternalError))},a);for(;this.state!==Re.CONNECTED;)if(yield pt(50),r!=null&&r.signal.aborted){l(new pe("room connection has been cancelled",se.Cancelled));return}Xe.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class Pe extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Nf(t,Pe.MAX_MESSAGE_BYTES),this.data=i?Nf(i,Pe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Pe(e.code,e.message,e.data)}toProto(){return new Kd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Pe(Pe.ErrorCode[e],Pe.ErrorMessage[e],t)}}Pe.MAX_MESSAGE_BYTES=256,Pe.MAX_DATA_BYTES=15360,Pe.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},Pe.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 Af=15360;function Tc(n){return new TextEncoder().encode(n).length}function Nf(n,e){if(Tc(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 kc=2e3;function Zs(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 CC=1e3;class Mf 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=vc(()=>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(D.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new dt,this.pauseUpstreamLock=new dt,this.processorLock=new dt,this.restartLock=new dt,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=>{Ei(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&&(_i(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=>{_i(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]:CC;return function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Lt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield pt(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield pt(50)}throw new an("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===Ln(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ln(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?We.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 an("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=hS(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(l=>{Ei(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(D.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?D.Muted:D.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),cf()&&(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(D.UpstreamPaused,this);const i=Lt();if((i==null?void 0:i.name)==="Safari"&&Jn(i.version,"12.0")<0)throw new Ho("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(D.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),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),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(_i(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Ei(i._mediaStreamTrack,l),_i(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(D.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(D.TrackProcessorUpdate))}()})}}class ea extends Mf{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=Zs(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.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!==Ln(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=uc({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(){mt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},kc)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Jt()&&!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(D.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 vf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(D.AudioSilenceDetected)),e})}}function xC(n,e,t){switch(n.kind){case"audio":return new ea(n,e,!1,void 0,t);case"video":return new na(n,e,!1,t);default:throw new an("unsupported track type: ".concat(n.kind))}}const wC=Object.values(ur),_C=Object.values(Xo),EC=Object.values(Jo),RC=[ur.h180,ur.h360],PC=[Xo.h180,Xo.h360],IC=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new fe(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)}),Sc=["q","h","f"];function Cc(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,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=AC(n,e,t,l),ie.debug("using video encoding",a));const u=a.maxFramerate,d=new fe(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&dr(l)){const m=new ta(c),p=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Lt();if(Mn()||Jt()||(v==null?void 0:v.name)==="Chrome"&&Jn(v==null?void 0:v.version,"113")<0){const b=m.suffix=="h"?2:3;for(let C=0;C<m.spatial;C+=1)p.push({rid:Sc[2-C],maxBitrate:a.maxBitrate/Math.pow(b,C),maxFramerate:d.encoding.maxFramerate});p[0].scalabilityMode=c}else p.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),ie.debug("using svc encoding",{encodings:p}),p}if(!o)return[a];let h=[];n?h=(r=Df(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Lf(n,d):h=(s=Df(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Lf(n,d);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const p=Math.max(e,t);if(p>=960&&f)return xc(e,t,[m,f,d],u);if(p>=480)return xc(e,t,[m,d],u)}return xc(e,t,[d])}function OC(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ie.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(),c=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,l=(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),Cc(n.source===I.Source.ScreenShare,c,l,t)}function AC(n,e,t,i){const r=NC(n,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.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 NC(n,e,t){if(n)return EC;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?wC:_C}function Lf(n,e){if(n)return IC(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)?RC:PC}function xc(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=Sc.length)return;const o=Math.min(n,e),l={rid:Sc[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&&(l.maxFramerate=u);const d=Ri()||a===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),Jt()&&uf()==="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 c;o.maxFramerate!=s&&(a&&(a=!1,ie.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ie.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Df(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 ta{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 MC(n){return n.source===I.Source.ScreenShare||n.constraints.height&&Ln(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const LC=5e3;class na extends Mf{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((c,l)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);o+=Zs(c,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new dt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!mt())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()},kc))}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,c=In(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)s=l.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=c.return)&&(yield r.call(c))}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,c=In(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){s=l.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=c.return)&&(yield r.call(c))}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=wt.LOW;i<=wt.HIGH;i+=1)t.push(new Ao({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=uc({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var c=!0,l=In(this.simulcastCodecs.values()),u;u=yield l.next(),t=u.done,!t;c=!0){s=u.value,c=!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{!c&&!t&&(r=l.return)&&(yield r.call(l))}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,c,l,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=In(r.simulcastCodecs.values()),m;m=yield f.next(),a=m.done,!a;h=!0)l=m.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(p){o={error:p}}finally{try{!h&&!a&&(c=f.return)&&(yield c.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)},LC))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,i=In(e);r=yield i.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const u=c;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){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Uf(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 l})}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 Uf(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),cf()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Uf(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:c}=o;if(!c)return;if(c.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:c,senderEncodings:e}));return}let l=!1;const u=Lt();if((u==null?void 0:u.name)==="Chrome"&&Jn(u==null?void 0:u.version,"133")>0&&c[0].scalabilityMode){const h=c[0],f=new ta(h.scalabilityMode);let m=Ti.OFF;if(t.forEach(p=>{p.enabled&&(m===Ti.OFF||p.quality>m)&&(m=p.quality)}),m===Ti.OFF)h.active&&(h.active=!1,l=!0);else if(!h.active||f.spatial!==m+1){l=!0,h.active=!0;const p=new ta(e[0].scalabilityMode);f.spatial=m+1,f.suffix=p.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-m),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,f)=>{var m;let p=(m=h.rid)!==null&&m!==void 0?m:"";p===""&&(p="q");const v=Bf(p),b=t.find(C=>C.quality===v);b&&h.active!==b.enabled&&(l=!0,h.active=b.enabled,r.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),s),Ri()&&(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)))});l&&(o.encodings=c,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Bf(n){switch(n){case"f":return wt.HIGH;case"h":return wt.MEDIUM;case"q":return wt.LOW;default:return wt.HIGH}}function Ff(n,e,t,i){if(!t)return[new $n({quality:wt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new ta(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)a.push(new $n({quality:Math.min(wt.HIGH,s.spatial-1)-l,width:Math.ceil(n/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Bf((a=r.rid)!==null&&a!==void 0?a:"");return new $n({quality:l,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const jf="_lossy",Vf="_reliable",DC=2*1e3,wc="leave-reconnect";var Ut;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ut||(Ut={}));class UC extends Xt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=yc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ut.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ie,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===Vf)s.reliableDCSub=a;else if(a.label===jf)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 c=ft.fromBinary(new Uint8Array(o));((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(U.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&FC(c,c.value.value),this.emit(U.DataPacketReceived,c))}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?ae.LOSSY:ae.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(U.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===wc&&(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=Xe.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ut.Connected&&i();const s=()=>{this.off(U.Disconnected,a),i()},a=()=>{this.off(U.Restarted,s),r()};this.once(U.Restarted,s),this.once(U.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(U.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ye.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=sn((t=e.loggerName)!==null&&t!==void 0?t:Mt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new hc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new dt,this.dataProcessLock=new dt,this.dcBufferStatus=new Map([[ae.LOSSY,!0],[ae.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(U.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(U.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(U.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(U.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(U.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(U.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(U.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(U.SignalRequestResponse,i)}get logContext(){var e,t,i,r,s,a,o,c;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:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.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(U.SignalConnected)},10),s}catch(s){if(s instanceof pe&&s.reason===se.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(U.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 an("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 pe("publication of local track timed out, no response from server",se.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!==Re.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new SC(r,e.subscriberPrimary,this.loggerOptions),this.emit(U.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===Re.CONNECTED){const u=this.pcState===Ut.New;this.pcState=Ut.Connected,u&&this.emit(U.Connected,e)}else s===Re.FAILED&&this.pcState===Ut.Connected&&(this.pcState=Ut.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ye.RECONNECTING,l=[Re.FAILED,Re.CLOSING,Re.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(U.Offline)}),this.pcManager.onTrack=s=>{this.emit(U.MediaTrackAdded,s.track,s.streams[0],s.receiver)},BC((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(U.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(U.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(U.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(U.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(U.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ki.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 xi.DISCONNECT:this.emit(U.Disconnected,e==null?void 0:e.reason),this.close();break;case xi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case xi.RESUME:this.handleDisconnect(wc)}}}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===or.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(jf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Vf,{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(Qo())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Zo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(Qo())return this.createSimulcastTransceiverSender(e,t,i,r);if(Zo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ii(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 Ge("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 Ge("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){ie.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===or.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Re.NEW)===Re.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 Ge?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof Ai||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ki.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(U.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 Ge("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(U.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 Ai;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof pe&&a.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):new Ai}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(U.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ye.CONNECTED)throw new Ai("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(U.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 Ge("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ge("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(U.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 pe&&r.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):r instanceof pe&&r.reason===se.LeaveRequest?r:new Ai(s)}if(this.emit(U.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!==ye.CONNECTED)throw new Ai("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(U.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=Ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield pt(DC),!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ut.Connected}catch(e){throw this.pcState=Ut.Disconnected,new pe("could not establish PC connection, ".concat(e.message),se.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new ft({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcResponse",value:new qd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,ae.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new ft({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcAck",value:new Wd({requestId:t})}});yield this.sendDataPacket(i,ae.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(U.Closing,r);!this.dcBufferStatus.get(e);)yield pt(10);this.off(U.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 Ge("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new pe("".concat(o," connection not set"),se.InternalError);let c=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(t,r);if((l==null?void 0:l.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 pt(50)}throw new pe("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),se.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!==Re.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 Wo("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(U.Closing,r),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();KS(c)&&a.set(o.payload,c)}),this.emit(U.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Wo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(s)}finally{this.off(U.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===ae.LOSSY)return this.lossyDCSub;if(e===ae.RELIABLE)return this.reliableDCSub}else{if(e===ae.LOSSY)return this.lossyDC;if(e===ae.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,c=new Array,l=new Array;e.forEach(u=>{u.isDesired!==o&&c.push(u.trackSid),u.isEnabled||l.push(u.trackSid)}),this.client.sendSyncState(new uh({answer:s?Qs({sdp:s.sdp,type:s.type}):void 0,offer:a?Qs({sdp:a.sdp,type:a.type}):void 0,subscription:new Ds({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:nC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new dh({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(ae.LOSSY),Nt.PUBLISHER),t(this.dataChannelForKind(ae.RELIABLE),Nt.PUBLISHER),t(this.dataChannelForKind(ae.LOSSY,!0),Nt.SUBSCRIBER),t(this.dataChannelForKind(ae.RELIABLE,!0),Nt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Xe.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){mt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){mt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Ai extends Error{}function BC(n){return n!==void 0&&n>13}function FC(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 _c{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 tc(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),ie.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(jC(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 pe("Could not fetch region settings: ".concat(t.statusText),t.status===401?se.NotAllowed:se.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function jC(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Gf{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class VC extends Gf{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=In(this),c;c=yield o.next(),e=c.done,!e;a=!0){r=c.value,a=!1;const l=r;s.add(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class GC extends Gf{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Xs(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=In(this),c;c=yield o.next(),e=c.done,!e;a=!0)r=c.value,a=!1,s+=r}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return s})}}class zf{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 zC extends zf{}class HC extends zf{}class Hf 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?D.Muted:D.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(D.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(),kc)),iC()&&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(D.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class WC extends Hf{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=Zs(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;Jt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Jt())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(ec(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&ec(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(D.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(D.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 Ec=100;class qC extends Hf{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=Zs(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=vc(()=>{this.updateDimensions()},Ec),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?Ei(this._mediaStreamTrack,t):_i(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 KC(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,c)=>Math.max(o,c.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<Ec){Xe.setTimeout(()=>{this.updateVisibility()},Ec);return}this.lastVisible=a,this.emit(D.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,c=a.height()*s;o+c>i+r&&(i=o,r=c)}((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(D.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?df():t||(df()>2?2:1)}}class KC{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=pr(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=pr(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=pr(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Rc(e),this.isPiP=mt()&&pr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Rc(this.element),this.isPiP=pr(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ff().observe(this.element),hf().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=ff())===null||e===void 0||e.unobserve(this.element),(t=hf())===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 pr(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Rc(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Rc(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=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&&c!=="none"}class cn extends Xt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=bt.NONE,this.log=ie,this.handleMuted=()=>{this.emit(D.Muted)},this.handleUnmuted=()=>{this.emit(D.Unmuted)},this.log=sn((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Mt.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(D.Muted,this.handleMuted),this.track.off(D.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(D.Muted,this.handleMuted),e.on(D.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ue(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==bt.NONE}get audioTrack(){if(on(this.track))return this.track}get videoTrack(){if(Ii(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={}))})(cn||(cn={}));class Pc extends cn{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(D.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(D.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(D.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(on(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(At.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(At.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(At.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(At.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(At.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(At.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ia(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=Tf(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 c=gf(s,If,Of),l=uc(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(We.userMediaPromiseMap.set("audioinput",u),u.catch(()=>We.userMediaPromiseMap.delete("audioinput"))),s.video&&(We.userMediaPromiseMap.set("videoinput",u),u.catch(()=>We.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 m=f?c.audio:c.video;(typeof m=="boolean"||!m)&&(m={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&Ln(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const C=xC(h,p,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,on(C)&&i?yield C.setProcessor(i):Ii(C)&&r&&(yield C.setProcessor(r)),C})))}catch(d){if(!t)throw d;return ia(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function $C(n){return y(this,void 0,void 0,function*(){return(yield ia({audio:!1,video:n??!0}))[0]})}function YC(n){return y(this,void 0,void 0,function*(){return(yield ia({audio:n??!0,video:!1}))[0]})}var Bn;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Bn||(Bn={}));function XC(n){switch(n){case ar.EXCELLENT:return Bn.Excellent;case ar.GOOD:return Bn.Good;case ar.POOR:return Bn.Poor;case ar.LOST:return Bn.Lost;default:return Bn.Unknown}}class Wf extends Xt.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===Ls.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Si.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]:Ls.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Bn.Unknown,this.log=ie,this.log=sn((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Mt.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 sc,this.once(j.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===Si.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Si.ACTIVE&&this.emit(j.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(j.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(j.ParticipantNameChanged,e)}_setAttributes(e){const t=rC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(j.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const c=this.permissions,l=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,l&&this.emit(j.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(j.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=XC(e),t!==this._connectionQuality&&this.emit(j.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=>on(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(D.Muted,()=>{this.emit(j.TrackMuted,e)}),e.on(D.Unmuted,()=>{this.emit(j.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 JC(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 ch({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 qf=15e3;class QC extends Wf{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=bt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sc)},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(c=>this.log.warn(c.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:c,message:l}=a,u=this.pendingSignalRequests.get(o);u&&(c!==No.OK&&u.reject(new rf(l,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,l=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(l=Pe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,l);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=>JC(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),ue(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ue(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ue(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,c,l,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 m=!0,p=In(b),v;v=yield p.next(),o=v.done,!o;m=!0){u=v.value,m=!1;const C=u;DS(C)&&(this.log.debug("publish ".concat(C," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ue(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,C,f.options))}}catch(C){c={error:C}}finally{try{!m&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(c)throw c.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),ue(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Zn(a)||Dn(a))try{if(mt())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),ue(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),ue(a))),Zn(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),ue(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!==bt.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(U.RemoteMute,(t,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(U.Connected,this.handleReconnected).on(U.SignalRestarted,this.handleReconnected).on(U.SignalResumed,this.handleReconnected).on(U.Restarting,this.handleReconnecting).on(U.Resuming,this.handleReconnecting).on(U.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(U.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(U.Disconnected,this.handleDisconnected).on(U.SignalRequestResponse,this.handleSignalRequestResponse).on(U.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,c)=>y(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:m=>{c(m),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(m=>{let[p,v]=m;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),o();return}yield pt(50)}c(new rf("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&c(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(j.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?bt.GCM:bt.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 c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case I.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case I.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case I.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new an(e)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(j.MediaDevicesError,l),this.pendingPublishing.delete(e),l}try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ue(d))),l.push(this.publishTrack(d,r));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}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 c=this.getTrackPublication(I.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.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=gf(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 ia(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(on(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=I.Source.Microphone,this.emit(j.AudioStreamAcquired)),Ii(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 Ho("getDisplayMedia not supported");e.resolution===void 0&&!GS()&&(e.resolution=Jo.h1080fps30.resolution);const t=tC(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new an("no video track found");const s=new na(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(j.AudioStreamAcquired);const o=new ea(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,c,l,u;Zn(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 ea(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new na(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new an("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),ue(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;m&&(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),ue(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!zS()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,C)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ye.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ue(i)}));const w=()=>y(this,void 0,void 0,function*(){try{const T=yield this.publish(i,p,m);b(T)}catch(T){C(T)}});setTimeout(()=>{this.engine.off(U.SignalConnected,w),C(new qo("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(U.SignalConnected,w),this.engine.on(U.Closing,()=>{this.engine.off(U.SignalConnected,w),C(new qo("publishing rejected as engine closed",499))})}else try{const w=yield this.publish(i,p,m);b(w)}catch(w){C(w)}}catch(w){C(w)}}));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),ue(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>sC(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ue(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var r,s,a,o,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new qo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(k=>Pi(e)&&k.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),ue(e))),t.stopMicTrackOnMute&&on(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&Ri()&&(t.simulcast=!1),t.videoCodec==="av1"&&!FS()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!jS()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=bc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(k=>t.videoCodec===Js(k.mime))||(t.videoCodec=Js(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(D.Muted,this.onTrackMuted),e.on(D.Unmuted,this.onTrackUnmuted),e.on(D.Ended,this.handleTrackEnded),e.on(D.UpstreamPaused,this.onTrackUpstreamPaused),e.on(D.UpstreamResumed,this.onTrackUpstreamResumed),e.on(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new Ro({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 k={width:0,height:0};try{k=yield e.waitForDimensions()}catch{const _=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:ur.h720.resolution;k={width:_.width,height:_.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{dims:k}))}v.width=k.width,v.height=k.height,Dn(e)&&(dr(p)&&(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),ue(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),v.simulcastCodecs=[new Eo({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:bc}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===bt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Eo({codec:t.backupCodec.codec,cid:""})))),b=Cc(e.source===I.Source.ScreenShare,v.width,v.height,t),v.layers=Ff(v.width,v.height,b,dr(t.videoCodec))}else e.kind===I.Kind.Audio&&(b=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.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 Ge("cannot publish track when not connected");const C=()=>y(this,void 0,void 0,function*(){var k,x,_;if(!this.engine.pcManager)throw new Ge("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Dn(e)&&((k=t.degradationPreference)!==null&&k!==void 0||(t.degradationPreference=MC(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Ri()&&e.kind===I.Kind.Audio){let R;for(const O of this.engine.pcManager.publisher.getTransceivers())if(O.sender===e.sender){R=O;break}R&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:R,codec:"opus",maxbr:!((x=b[0])===null||x===void 0)&&x.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&dr(e.codec)&&(!((_=b[0])===null||_===void 0)&&_.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let w;if(this.enabledPublishVideoCodecs.length>0)w=(yield Promise.all([this.engine.addTrack(v),C()]))[0];else{w=yield this.engine.addTrack(v);let k;if(w.codecs.forEach(x=>{k===void 0&&(k=x.mimeType)}),k&&e.kind===I.Kind.Video){const x=Js(k);x!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{codec:x})),t.videoCodec=x,b=Cc(e.source===I.Source.ScreenShare,v.width,v.height,t))}yield C()}const T=new Pc(e.kind,w,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return T.options=t,e.sid=w.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:w})),Dn(e)?e.startMonitor(this.engine.client):Zn(e)&&e.startMonitor(),this.addTrackPublication(T),this.emit(j.LocalTrackPublished,T),T})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==bt.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new an("track is not published");if(!Dn(e))throw new an("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=OC(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),ue(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=new Ro({cid:c.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Ff(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Ge("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),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 l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ue(e))),yield l)}const s=this.getPublicationForTrack(e),a=s?ue(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(D.Muted,this.onTrackMuted),e.off(D.Unmuted,this.onTrackUnmuted),e.off(D.Ended,this.handleTrackEnded),e.off(D.UpstreamPaused,this.onTrackUpstreamPaused),e.off(D.UpstreamResumed,this.onTrackUpstreamResumed),e.off(D.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 c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Re.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Dn(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}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(j.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(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>y(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==I.Source.ScreenShare&&l.source!==I.Source.ScreenShareAudio&&(Zn(l)||Dn(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(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?ae.RELIABLE:ae.LOSSY,a=r.destinationIdentities,o=r.topic,c=new ft({kind:s,value:{case:"user",value:new Gd({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new ft({kind:ae.RELIABLE,value:{case:"sipDtmf",value:new zd({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ae.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 ft({value:{case:"chatMessage",value:new ko(Object.assign(Object.assign({},i),{timestamp:Se.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.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 ft({value:{case:"chatMessage",value:new ko(Object.assign(Object.assign({},i),{timestamp:Se.parse(i.timestamp),editTimestamp:Se.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.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()),c=new Array(o?o.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const m=c.reduce((p,v)=>p+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,m)},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),l(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=>{l(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:Qn(s.timestamp),totalLength:Qn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new eh({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"?So.UPDATE:So.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new ft({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,ae.RELIABLE);let l=0;const u=this,d=new WritableStream({write(m){return y(this,void 0,void 0,function*(){for(const p of ZS(m,qf)){yield u.engine.waitForBufferStatusLow(ae.RELIABLE);const v=new xo({content:p,streamId:r,chunkIndex:Qn(l)}),b=new ft({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,ae.RELIABLE),l+=1}})},close(){return y(this,void 0,void 0,function*(){const m=new wo({streamId:r}),p=new ft({destinationIdentities:o,value:{case:"streamTrailer",value:m}});yield u.engine.sendDataPacket(p,ae.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(U.Closing,h);const f=new zC(d,s,()=>this.engine.off(U.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:c}=yield a.read();if(o)break;yield s.write(c)}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(),c=e==null?void 0:e.destinationIdentities,l={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:Qn((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:Qn(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new th({name:l.name})}}),d=new ft({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,ae.RELIABLE);let h=0;const f=new dt,m=this.engine,p=this.log,v=new WritableStream({write(C){return y(this,void 0,void 0,function*(){const w=yield f.lock();let T=0;try{for(;T<C.byteLength;){const k=C.slice(T,T+qf);yield m.waitForBufferStatusLow(ae.RELIABLE);const x=new ft({destinationIdentities:c,value:{case:"streamChunk",value:new xo({content:k,streamId:o,chunkIndex:Qn(h)})}});yield m.sendDataPacket(x,ae.RELIABLE),h+=1,T+=k.byteLength}}finally{w()}})},close(){return y(this,void 0,void 0,function*(){const C=new wo({streamId:o}),w=new ft({destinationIdentities:c,value:{case:"streamTrailer",value:C}});yield m.sendDataPacket(w,ae.RELIABLE)})},abort(C){p.error("Sink error:",C)}});return new HC(v,l)})}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((l,u)=>y(i,void 0,void 0,function*(){var d,h,f,m;if(Tc(a)>Af){u(Pe.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&&Jn((m=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){u(Pe.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),u(Pe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),u(Pe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(C,w)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),w?u(w):l(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 ft({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcRequest",value:new Hd({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,ae.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,Pe.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),ue(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?(Zn(r)||Dn(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 pt(20)}})}}class ZC extends cn{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=wt.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(D.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 Ds({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $d({participantSid:"",trackSids:[this.trackSid]})]});this.emit(D.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?cn.SubscriptionStatus.Unsubscribed:super.isSubscribed?cn.SubscriptionStatus.Subscribed:cn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?cn.PermissionStatus.Allowed:cn.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||(cc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&cc(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(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(D.VisibilityChanged,this.handleVisibilityChange),r.off(D.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(D.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(D.VisibilityChanged,this.handleVisibilityChange),e.on(D.Ended,this.handleEnded),this.emit(D.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(D.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?D.Muted:D.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(D.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(D.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 cc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ih({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=wt.HIGH,this.emit(D.UpdateSettings,e)}}class ra extends Wf{static fromParticipantInfo(e,t,i){return new ra(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 c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ls.STANDARD;super(t,i||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(D.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ue(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(D.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(D.SubscriptionPermissionChanged,t=>{this.emit(j.TrackSubscriptionPermissionChanged,e,t)}),e.on(D.SubscriptionStatusChanged,t=>{this.emit(j.TrackSubscriptionStatusChanged,e,t)}),e.on(D.Subscribed,t=>{this.emit(j.TrackSubscribed,t,e)}),e.on(D.Unsubscribed,t=>{this.emit(j.TrackUnsubscribed,t,e)}),e.on(D.SubscriptionFailed,t=>{this.emit(j.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(j.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),ue(o))),this.emit(j.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new qC(e,t,r,s):l=new WC(e,t,r,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(i),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&oc(l)&&on(l)&&l.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 c=I.kindFromProto(r.type);if(!c)return;o=new ZC(c,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 l=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));l&&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:ue(l),newTrack:ue(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),ue(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(j.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(j.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;on(i.track)&&oc(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 ce;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ce||(ce={}));const e1=4*1e3;class Ni extends Xt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=ce.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ie,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,c)=>y(this,void 0,void 0,function*(){var l;if(!VS())throw Jt()?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===ce.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(ce.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),tc(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new _c(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,m,p)=>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(p??a,o,c,C),this.abortController=void 0,f()}catch(w){if(this.regionUrlProvider&&w instanceof pe&&w.reason!==se.Cancelled&&w.reason!==se.NotAllowed){let T=null;try{T=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(k){if(k instanceof pe&&(k.status===401||k.reason===se.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(k);return}}T&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(T),this.logContext),this.recreateEngine(),yield d(f,m,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,mf(w)),m(w))}else{let T=Ot.UNKNOWN_REASON;w instanceof pe&&(T=mf(w)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),m(w)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sc((f,m)=>{d(f,m,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,l,u,d)=>y(this,void 0,void 0,function*(){var h,f,m;const p=yield c.join(a,o,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},d.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[C,w]=b;return"".concat(C,": ").concat(w)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(m=p.participant)===null||m===void 0?void 0:m.identity}),!v.version)throw new _S("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),p}),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(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,l)=>y(this,void 0,void 0,function*(){var u,d;this.state===ce.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({},yc),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new pe("could not establish signal connection",se.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof pe&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new pe("Connection attempt aborted",se.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}mt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),mt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ce.Connected),this.emit(L.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return y(t,[...o],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,m;const p=yield l.disconnectLock.lock();try{if(l.state===ce.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ce.Connecting||l.state===ce.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(d=l.abortController)===null||d===void 0||d.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new pe("Client initiated disconnect",se.Cancelled)),l.connectFuture=void 0),!((m=l.engine)===null||m===void 0)&&m.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(u,Ot.CLIENT_INITIATED),l.engine=void 0}finally{p()}}()})},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=Lt();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const u=rc();u.enabled=!0;const d=new MediaStream([u]);l.srcObject=d,document.addEventListener("visibilitychange",()=>{l&&(l.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(l),this.once(L.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.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(ce.Reconnecting)&&this.emit(L.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(ce.Connected),this.emit(L.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(o.identity);o.state===Si.DISCONNECTED?this.handleParticipantDisconnected(o.identity,l):l=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),o.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(L.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||o.set(l.sid,l)}),a.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?o.set(l.sid,u):o.delete(l.sid))});const c=Array.from(o.values());c.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(L.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);if(!l||!l.track)return;const u=I.streamStateFromProto(o.state);u!==l.track.streamState&&(l.track.streamState=u,c.emit(j.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(L.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.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 c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(L.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(j.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(L.SipDTMFReceived,o,a),a==null||a.emit(j.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(o.trackId),u=YS(o,this.transcriptionReceivedTimes);l==null||l.emit(D.TranscriptionReceived,u),c==null||c.emit(j.TranscriptionReceived,u,l),this.emit(L.TranscriptionReceived,u,c,l)},this.handleChatMessage=(a,o)=>{const c=XS(o);this.emit(L.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(L.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(L.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(L.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(L.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(L.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,c;const l=We.getInstance().previousDevices,u=yield We.getInstance().getDevices(void 0,!1),d=Lt();if((d==null?void 0:d.name)==="Chrome"&&d.os!=="iOS")for(let f of u){const m=l.find(p=>p.deviceId===f.deviceId);m&&m.label!==""&&m.kind===f.kind&&m.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(L.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const m=eC(f),p=this.localParticipant.getTrackPublication(m);if(p&&(!((a=p.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(C=>C.kind===f),b=this.getActiveDevice(f);if(b===((o=l.filter(C=>C.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((c=v[0])===null||c===void 0?void 0:c.deviceId)!==b){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Mn()||f==="videoinput"||v.length>0&&!v.find(C=>C.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(L.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(L.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(L.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(L.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(L.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(L.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(L.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(L.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,c,l,u,d,h;(o=a.track)===null||o===void 0||o.on(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(D.Restarted,this.onLocalTrackRestarted),(d=(u=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(L.LocalTrackPublished,a,this.localParticipant),Zn(a.track)&&(yield a.track.checkForSilence())&&this.emit(L.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),m=yf(a.source);m&&f&&f!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,f),this.emit(L.ActiveDeviceChanged,m,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(D.Restarted,this.onLocalTrackRestarted),this.emit(L.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=yf(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(L.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(L.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(L.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(L.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(L.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},kC),e),this.log=sn((i=this.options.loggerName)!==null&&i!==void 0?i:Mt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},If),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Of),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},TC),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new dt,this.localParticipant=new QC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ln(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ln(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Ln(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),mt()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Ni.cleanupRegistry&&Ni.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,Pe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,Pe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});Tc(u)>Af?(c=Pe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof Pe?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=Pe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}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 aC(this.options.e2ee),this.e2eeManager.on(An.ParticipantEncryptionStatusChanged,(t,i)=>{QS(i)&&(this.isE2EEEnabled=t),this.emit(L.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(An.EncryptionError,t=>this.emit(L.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return y(this,void 0,void 0,function*(){return this.state===ce.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(U.RoomUpdate,i),e(r.sid))};this.engine.on(U.RoomUpdate,i),this.once(L.Disconnected,()=>{this.engine.off(U.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 UC(this.options),this.engine.on(U.ParticipantUpdate,this.handleParticipantUpdates).on(U.RoomUpdate,this.handleRoomUpdate).on(U.SpeakersChanged,this.handleSpeakersChanged).on(U.StreamStateChanged,this.handleStreamStateUpdate).on(U.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(U.SubscriptionError,this.handleSubscriptionError).on(U.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(U.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(U.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(U.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(U.DataPacketReceived,this.handleDataPacket).on(U.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ce.SignalReconnecting)&&this.emit(L.SignalReconnecting)}).on(U.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ce.Connected)&&this.emit(L.Reconnected)}).on(U.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ce.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(U.Restarting,this.handleRestarting).on(U.SignalRestarted,this.handleSignalRestarted).on(U.Offline,()=>{this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(L.Reconnecting)}).on(U.DCBufferStatusChanged,(e,t)=>{this.emit(L.DCBufferStatusChanged,e,t)}).on(U.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(j.LocalTrackSubscribed,t),this.emitWhenConnected(L.LocalTrackSubscribed,t,this.localParticipant)}).on(U.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(L.Moved,e.room.name,e.token),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return We.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ce.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(tc(new URL(e))&&t){this.regionUrlProvider=new _c(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ce.Disconnected&&(this.regionUrl=i,yield fetch(ac(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(ac(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 Yt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Yt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Yt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Yt({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 Yt({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 Yt({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 Yt({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 Us({reason:Ot.CLIENT_INITIATED,action:xi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Yt({scenario:{case:"subscriberBandwidth",value:Qn(t)}});break;case"leave-full-reconnect":r=new Yt({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,c,l,u,d,h,f,m;let p=!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 w=Array.from(s.localParticipant.audioTrackPublications.values()).filter(T=>T.source===I.Source.Microphone);try{p=(yield Promise.all(w.map(T=>{var k;return(k=T.audioTrack)===null||k===void 0?void 0:k.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=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const w=Array.from(s.localParticipant.videoTrackPublications.values()).filter(T=>T.source===I.Source.Camera);try{p=(yield Promise.all(w.map(T=>{var k;return(k=T.videoTrack)===null||k===void 0?void 0:k.setDeviceId(b)}))).every(T=>T===!0)}catch(T){throw s.options.videoCaptureDefaults.deviceId=C,T}}else if(i==="audiooutput"){if(!ec()&&!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=(l=yield We.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(m=s.options).audioOutput)!==null&&u!==void 0||(m.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(w=>w.setAudioOutput({deviceId:r})))}catch(w){throw s.options.audioOutput.deviceId=C,w}}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(L.ActiveDeviceChanged,i,r)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(j.AttributesChanged,this.onLocalAttributesChanged).on(j.TrackMuted,this.onLocalTrackMuted).on(j.TrackUnmuted,this.onLocalTrackUnmuted).on(j.LocalTrackPublished,this.onLocalTrackPublished).on(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(j.MediaDevicesError,this.onMediaDevicesError).on(j.AudioStreamAcquired,this.startAudio).on(j.ChatMessage,this.onLocalChatMessageSent).on(j.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===ce.Connecting||this.state===ce.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(L.Reconnected,u),this.off(L.Connected,u),this.off(L.Disconnected,d)};this.once(L.Reconnected,u),this.once(L.Connected,u),this.once(L.Disconnected,d);return}if(this.state===ce.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=BS(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 c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,o,t,i,l)}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!==ce.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(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(j.AttributesChanged,this.onLocalAttributesChanged).off(j.TrackMuted,this.onLocalTrackMuted).off(j.TrackUnmuted,this.onLocalTrackUnmuted).off(j.LocalTrackPublished,this.onLocalTrackPublished).off(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(j.MediaDevicesError,this.onMediaDevicesError).off(j.AudioStreamAcquired,this.startAudio).off(j.ChatMessage,this.onLocalChatMessageSent).off(j.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),mt()&&(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(ce.Disconnected),this.emit(L.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(L.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:Xs(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new VC(a,o,Xs(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:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new GC(a,o,Xs(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=bf())!==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(),pt(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(L.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=ra.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new ra(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(L.ParticipantConnected,i),i.on(j.TrackPublished,r=>{this.emitWhenConnected(L.TrackPublished,r,i)}).on(j.TrackSubscribed,(r,s)=>{r.kind===I.Kind.Audio?(r.on(D.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(D.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===I.Kind.Video&&(r.on(D.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(D.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(L.TrackSubscribed,r,s,i)}).on(j.TrackUnpublished,r=>{this.emit(L.TrackUnpublished,r,i)}).on(j.TrackUnsubscribed,(r,s)=>{this.emit(L.TrackUnsubscribed,r,s,i)}).on(j.TrackMuted,r=>{this.emitWhenConnected(L.TrackMuted,r,i)}).on(j.TrackUnmuted,r=>{this.emitWhenConnected(L.TrackUnmuted,r,i)}).on(j.ParticipantMetadataChanged,r=>{this.emitWhenConnected(L.ParticipantMetadataChanged,r,i)}).on(j.ParticipantNameChanged,r=>{this.emitWhenConnected(L.ParticipantNameChanged,r,i)}).on(j.AttributesChanged,r=>{this.emitWhenConnected(L.ParticipantAttributesChanged,r,i)}).on(j.ConnectionQualityChanged,r=>{this.emitWhenConnected(L.ConnectionQualityChanged,r,i)}).on(j.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(L.ParticipantPermissionsChanged,r,i)}).on(j.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(L.TrackSubscriptionStatusChanged,r,s,i)}).on(j.TrackSubscriptionFailed,(r,s)=>{this.emit(L.TrackSubscriptionFailed,r,i,s)}).on(j.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(L.TrackSubscriptionPermissionChanged,r,s,i)}).on(j.Active,()=>{this.emitWhenConnected(L.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&&JS(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=Xe.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,Ot.STATE_MISMATCH))):e=0},e1)}clearConnectionReconcile(){this.connectionReconcileInterval&&Xe.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(L.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,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===ce.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ce.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 Ns({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Se.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected),this.emit(L.Connected),this.setAndEmitConnectionState(ce.Connected),r.video){const a=new Pc(I.Kind.Video,new Ci({source:je.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO,name:"video-dummy"}),new na(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:pf(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(j.LocalTrackPublished,a)}if(r.audio){const a=new Pc(I.Kind.Audio,new Ci({source:je.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO}),new ea(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rc(),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(j.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Kn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Si.ACTIVE,tracks:[],joinedAt:Se.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(s.video){const l=pf(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Ci({source:je.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const l=rc(),u=new Ci({source:je.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}c.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!==L.ActiveSpeakersChanged&&e!==L.TranscriptionReceived){const s=Kf(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)}}Ni.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Kf(n){return n.map(e=>{if(e)return Array.isArray(e)?Kf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Bt;(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"})(Bt||(Bt={}));class Fn extends Xt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Bt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ni(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==Bt.IDLE)throw Error("check is running already");this.setStatus(Bt.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!==Bt.SKIPPED&&this.setStatus(this.isSuccess()?Bt.SUCCESS:Bt.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===ce.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!==ce.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Bt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(L.Reconnecting,()=>{t=!0}),this.room.once(L.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 pt(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 t1 extends Fn{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new _c(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,c=1e6/a,l="A".repeat(a),u=Date.now();for(let m=0;m<c;m++)yield s.write(l);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(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Ic=1e4;class n1 extends Fn{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/(Ic/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Ic/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],l=(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 l.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,Ic)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class i1 extends Fn{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield YC();if(yield vf(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 r1 extends Fn{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield $C();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,c;const l=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=(c=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),i.remove()})}}class s1 extends Fn{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(l=>{setTimeout(l,5e3),s=l}),o=()=>{i=!0};t.on(L.SignalReconnecting,o).on(L.Reconnecting,o).on(L.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!r||t.state!==ce.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 a1 extends Fn{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new hc,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 c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(a=!0,o=!0):l.startsWith("turns:")&&(a=!0,o=!0,s=!0),l.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(c=>setTimeout(c,0)))})}}class o1 extends Fn{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(L.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&&(c1(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(),ie.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 c1(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 l1 extends Fn{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 hc;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)===Yd.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 S_ extends Xt.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:Bt.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!==Bt.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(l1)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(o1)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(a1)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(s1)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(i1)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(r1)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(n1);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(t1)})}}const u1=/\{[^{}]+\}/g;function d1(){return Math.random().toString(36).slice(2,11)}function h1(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=Jf(e);const c=[];async function l(u,d){const{baseUrl:h,fetch:f=i,Request:m=t,headers:p,params:v={},parseAs:b="json",querySerializer:C,bodySerializer:w=s??p1,body:T,...k}=d||{};h&&(e=Jf(h));let x=typeof r=="function"?r:Xf(r);C&&(x=typeof C=="function"?C:Xf({...typeof r=="object"?r:{},...C}));const _=T===void 0?void 0:w(T),R=_===void 0||_ instanceof FormData?{}:{"Content-Type":"application/json"},O={redirect:"follow",...o,...k,body:_,headers:g1(R,a,p,v.header)};let B,N,W=new t(m1(u,{baseUrl:e,params:v,querySerializer:x}),O);for(const Q in k)Q in W||(W[Q]=k[Q]);if(c.length){B=d1(),N=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:x,bodySerializer:w});for(const Q of c)if(Q&&typeof Q=="object"&&typeof Q.onRequest=="function"){const X=await Q.onRequest({request:W,schemaPath:u,params:v,options:N,id:B});if(X){if(!(X instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");W=X}}}let K=await f(W);if(c.length)for(let Q=c.length-1;Q>=0;Q--){const X=c[Q];if(X&&typeof X=="object"&&typeof X.onResponse=="function"){const Te=await X.onResponse({request:W,response:K,schemaPath:u,params:v,options:N,id:B});if(Te){if(!(Te instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");K=Te}}}if(K.status===204||K.headers.get("Content-Length")==="0")return K.ok?{data:{},response:K}:{error:{},response:K};if(K.ok)return b==="stream"?{data:K.body,response:K}:{data:await K[b](),response:K};let M=await K.text();try{M=JSON.parse(M)}catch{}return{error:M,response:K}}return{GET(u,d){return l(u,{...d,method:"GET"})},PUT(u,d){return l(u,{...d,method:"PUT"})},POST(u,d){return l(u,{...d,method:"POST"})},DELETE(u,d){return l(u,{...d,method:"DELETE"})},OPTIONS(u,d){return l(u,{...d,method:"OPTIONS"})},HEAD(u,d){return l(u,{...d,method:"HEAD"})},PATCH(u,d){return l(u,{...d,method:"PATCH"})},TRACE(u,d){return l(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()`");c.push(d)}},eject(...u){for(const d of u){const h=c.indexOf(d);h!==-1&&c.splice(h,1)}}}}function sa(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 $f(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(sa(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Yf(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(sa(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Xf(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(Yf(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($f(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(sa(r,s,n))}}return i.join("&")}}function f1(n,e){let t=n;for(const i of n.match(u1)??[]){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,Yf(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,$f(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${sa(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function p1(n){return n instanceof FormData?n:JSON.stringify(n)}function m1(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=f1(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function g1(...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 Jf(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Qf="Onboardee-Session-Token",Zf="OnboardeeSessionToken";class ep{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=h1({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest:({request:t})=>{if(this.trackOnboardeeToken&&window.localStorage){const i=window.localStorage.getItem(Zf);i&&t.headers.set(Qf,i)}return t},onResponse:({response:t})=>{if(this.trackOnboardeeToken){const i=t.headers.get(Qf);i&&window.localStorage&&window.localStorage.setItem(Zf,i)}return t}})}setTrackOnboardeeToken(e){this.trackOnboardeeToken=e}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 tp="https://app.coragents.ai";class aa extends Ia{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 ep({baseUrl:tp}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new Ni(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}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(L.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(L.TrackSubscribed,i=>{if(console.info("[obi] track subscribed kind=",i.kind,"source=",i.source),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(L.LocalTrackPublished,i=>{if(console.info("[obi] local track published kind=",i.kind,"source=",i.source),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(L.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(L.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),e&&(this.isPaused,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isPaused,this.isPaused&&this.muteMicrophone()),t){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?this.speakingStateChanged("speaking"):this.speakingStateChanged("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 l=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",l),!1}console.log("[obi] requesting audio track via getUserMedia"),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});const t=this.publishedAudioStream.getAudioTracks().map(l=>{var u,d;return{id:l.id,label:l.label,enabled:l.enabled,muted:l.muted,readyState:l.readyState,constraints:(u=l.getConstraints)==null?void 0:u.call(l),settings:(d=l.getSettings)==null?void 0:d.call(l)}});console.log("[obi] getUserMedia resolved",t);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const l=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",l),!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:c}=this.createFFT(this.publishedAudioStream);this.userAnalyser=o,this.userAudioContext=c,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,c=Math.pow(a/s,1/o);for(let l=0;l<o;l++){const u=s*Math.pow(c,l),d=s*Math.pow(c,l+1),h=Math.floor(u/i),f=Math.floor(d/i),m=Math.min(f,this.frequencyDataBuffer.length),p=Math.min(h,m);if(p<m){let v=0;for(let C=p;C<m;C++)v+=this.frequencyDataBuffer[C];const b=v/(m-p)/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 aa(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 oa extends Ia{constructor(e,t,i={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.engagement=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 ep({baseUrl:i.apiBaseUrl||tp}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new aa(r,s,a,o)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var t,i,r,s,a,o,c;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const l=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});this.identity=e.identity||null,this.product=((t=l.data)==null?void 0:t.product)||null,this.plans=((i=l.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=l.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((s=l.data)==null?void 0:s.plan_is_completed)||[],this.showWidget=((a=l.data)==null?void 0:a.show_widget)||!1,this.engagement=((o=l.data)==null?void 0:o.engagement)||null;const u=((c=this.product)==null?void 0:c.track_onboardee_token)??!0;if(this.api.setTrackOnboardeeToken(u),e.planUuid){let d=null;try{const h=await this.api.getPlanSDK(e.planUuid);if(h.error)throw new Error(`Plan not found: ${h.error}`);h.data&&(d=h.data)}catch(h){try{const f=await this.api.getSessionPlan(e.planUuid);if(f.error)throw new Error(`Session plan not found: ${f.error}`);f.data&&(d=f.data)}catch(f){console.error("[obi] error getting plan via both endpoints",{planErr:h,sessionErr:f})}}d?(this.selectedPlan=d,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(l){throw this.error=l instanceof Error?l:new Error(String(l)),this.setState("error"),l}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 c;return o.uuid===((c=this.selectedPlan)==null?void 0:c.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,engagement:this.engagement,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 oa(t,i,r);return a.state=s.state,a.identity=s.identity||null,a.product=s.product||null,a.engagement=s.engagement||null,a.plans=s.plans||[],a.selectedPlan=s.selectedPlan||null,a.selectedPlanUuid=s.selectedPlanUuid||null,a.showWidget=s.showWidget||!1,s.session&&(a.session=aa.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 ca,Z,np,ei,ip,rp,sp,ap,Oc,Ac,Nc,op,mr={},cp=[],v1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,gr=Array.isArray;function ln(n,e){for(var t in e)n[t]=e[t];return n}function Mc(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Lc(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?ca.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return la(n,a,i,r,null)}function la(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??++np,__i:-1,__u:0};return r==null&&Z.vnode!=null&&Z.vnode(s),s}function nt(n){return n.children}function un(n,e){this.props=n,this.context=e}function Mi(n,e){if(e==null)return n.__?Mi(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"?Mi(n):null}function lp(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 lp(n)}}function Dc(n){(!n.__d&&(n.__d=!0)&&ei.push(n)&&!ua.__r++||ip!=Z.debounceRendering)&&((ip=Z.debounceRendering)||rp)(ua)}function ua(){for(var n,e,t,i,r,s,a,o=1;ei.length;)ei.length>o&&ei.sort(sp),n=ei.shift(),o=ei.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=ln({},i)).__v=i.__v+1,Z.vnode&&Z.vnode(t),Uc(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??Mi(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,pp(s,t,a),t.__e!=r&&lp(t)));ua.__r=0}function up(n,e,t,i,r,s,a,o,c,l,u){var d,h,f,m,p,v,b=i&&i.__k||cp,C=e.length;for(c=b1(t,e,b,c,C),d=0;d<C;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?mr:b[f.__i]||mr,f.__i=d,v=Uc(n,f,h,r,s,a,o,c,l,u),m=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Bc(h.ref,null,f),u.push(f.ref,f.__c||m,f)),p==null&&m!=null&&(p=m),4&f.__u||h.__k===f.__k?c=dp(f,c,n):typeof f.type=="function"&&v!==void 0?c=v:m&&(c=m.nextSibling),f.__u&=-7);return t.__e=p,c}function b1(n,e,t,i,r){var s,a,o,c,l,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"?(c=s+h,(a=n.__k[s]=typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?la(null,a,null,null,null):gr(a)?la(nt,{children:a},null,null,null):a.constructor==null&&a.__b>0?la(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=n,a.__b=n.__b+1,o=null,(l=a.__i=y1(a,t,c,d))!=-1&&(d--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(r>u?h--:r<u&&h++),typeof a.type!="function"&&(a.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?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=Mi(o)),gp(o,o));return i}function dp(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=dp(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Mi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function da(n,e){return e=e||[],n==null||typeof n=="boolean"||(gr(n)?n.some(function(t){da(t,e)}):e.push(n)),e}function y1(n,e,t,i){var r,s,a=n.key,o=n.type,c=e[t];if(c===null&&n.key==null||c&&a==c.key&&o==c.type&&!(2&c.__u))return t;if(i>(c!=null&&!(2&c.__u)?1:0))for(r=t-1,s=t+1;r>=0||s<e.length;){if(r>=0){if((c=e[r])&&!(2&c.__u)&&a==c.key&&o==c.type)return r;r--}if(s<e.length){if((c=e[s])&&!(2&c.__u)&&a==c.key&&o==c.type)return s;s++}}return-1}function hp(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||v1.test(e)?t:t+"px"}function ha(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||hp(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||hp(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(ap,"$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=Oc,n.addEventListener(e,s?Nc:Ac,s)):n.removeEventListener(e,s?Nc:Ac,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 fp(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=Oc++;else if(e.t<t.u)return;return t(Z.event?Z.event(e):e)}}}function Uc(n,e,t,i,r,s,a,o,c,l){var u,d,h,f,m,p,v,b,C,w,T,k,x,_,R,O,B,N=e.type;if(e.constructor!=null)return null;128&t.__u&&(c=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=Z.__b)&&u(e);e:if(typeof N=="function")try{if(b=e.props,C="prototype"in N&&N.prototype.render,w=(u=N.contextType)&&i[u.__c],T=u?w?w.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 un(b,T),d.constructor=N,d.render=k1),w&&w.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=ln({},d.__s)),ln(d.__s,N.getDerivedStateFromProps(b,d.__s))),f=d.props,m=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(W){W&&(W.__=e)}),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);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,m,p)})}if(d.context=T,d.props=b,d.__P=n,d.__e=!1,x=Z.__r,_=0,C){for(d.state=d.__s,d.__d=!1,x&&x(e),u=d.render(d.props,d.state,d.context),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[]}else do d.__d=!1,x&&x(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++_<25);d.state=d.__s,d.getChildContext!=null&&(i=ln(ln({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(p=d.getSnapshotBeforeUpdate(f,m)),O=u,u!=null&&u.type===nt&&u.key==null&&(O=mp(u.props.children)),o=up(n,gr(O)?O:[O],e,t,i,r,s,a,o,c,l),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),v&&(d.__E=d.__=null)}catch(W){if(e.__v=null,c||s!=null)if(W.then){for(e.__u|=c?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--;)Mc(s[B]);else e.__e=t.__e,e.__k=t.__k;Z.__e(W,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=T1(t.__e,e,t,i,r,s,a,c,l);return(u=Z.diffed)&&u(e),128&e.__u?void 0:o}function pp(n,e,t){for(var i=0;i<t.length;i++)Bc(t[i],t[++i],t[++i]);Z.__c&&Z.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){Z.__e(s,r.__v)}})}function mp(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:gr(n)?n.map(mp):ln({},n)}function T1(n,e,t,i,r,s,a,o,c){var l,u,d,h,f,m,p,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(l=0;l<s.length;l++)if((f=s[l])&&"setAttribute"in f==!!C&&(C?f.localName==C:f.nodeType==3)){n=f,s[l]=null;break}}if(n==null){if(C==null)return document.createTextNode(b);n=document.createElementNS(r,C,b.is&&b),o&&(Z.__m&&Z.__m(e,s),o=!1),s=null}if(C==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&ca.call(n.childNodes),v=t.props||mr,!o&&s!=null)for(v={},l=0;l<n.attributes.length;l++)v[(f=n.attributes[l]).name]=f.value;for(l in v)if(f=v[l],l!="children"){if(l=="dangerouslySetInnerHTML")d=f;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;ha(n,l,null,f,r)}}for(l in b)f=b[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?u=f:l=="value"?m=f:l=="checked"?p=f:o&&typeof f!="function"||v[l]===f||ha(n,l,f,v[l],r);if(u)o||d&&(u.__html==d.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(d&&(n.innerHTML=""),up(e.type=="template"?n.content:n,gr(h)?h:[h],e,t,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&Mi(t,0),o,c),s!=null)for(l=s.length;l--;)Mc(s[l]);o||(l="value",C=="progress"&&m==null?n.removeAttribute("value"):m!=null&&(m!==n[l]||C=="progress"&&!m||C=="option"&&m!=v[l])&&ha(n,l,m,v[l],r),l="checked",p!=null&&p!=n[l]&&ha(n,l,p,v[l],r))}return n}function Bc(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){Z.__e(r,t)}}function gp(n,e,t){var i,r;if(Z.unmount&&Z.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||Bc(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){Z.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&gp(i[r],e,t||typeof n.type!="function");t||Mc(n.__e),n.__c=n.__=n.__e=void 0}function k1(n,e,t){return this.constructor(n,t)}function S1(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),Z.__&&Z.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Uc(e,n=(!i&&t||e).__k=Lc(nt,null,[n]),r||mr,mr,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?ca.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),pp(s,n,a)}function C1(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,Dc(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"+op++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}ca=cp.slice,Z={__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}},np=0,un.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ln({},this.state),typeof n=="function"&&(n=n(ln({},t),this.props)),n&&ln(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Dc(this))},un.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Dc(this))},un.prototype.render=nt,ei=[],rp=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,sp=function(n,e){return n.__v.__b-e.__v.__b},ua.__r=0,ap=/(PointerCapture)$|Capture$/i,Oc=0,Ac=fp(!1),Nc=fp(!0),op=0;var x1=0;function g(n,e,t,i,r,s){e||(e={});var a,o,c=e;if("ref"in c)for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var l={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--x1,__i:-1,__u:0,__source:r,__self:s};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)c[o]===void 0&&(c[o]=a[o]);return Z.vnode&&Z.vnode(l),l}var ti,Ce,Fc,vp,vr=0,bp=[],Le=Z,yp=Le.__b,Tp=Le.__r,kp=Le.diffed,Sp=Le.__c,Cp=Le.unmount,xp=Le.__;function br(n,e){Le.__h&&Le.__h(Ce,n,vr||e),vr=0;var t=Ce.__H||(Ce.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function Y(n){return vr=1,w1(Ep,n)}function w1(n,e,t){var i=br(ti++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):Ep(void 0,e),function(o){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,o);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=Ce,!Ce.__f)){var r=function(o,c,l){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,c,l);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,c,l)||d};Ce.__f=!0;var s=Ce.shouldComponentUpdate,a=Ce.componentWillUpdate;Ce.componentWillUpdate=function(o,c,l){if(this.__e){var u=s;s=void 0,r(o,c,l),s=u}a&&a.call(this,o,c,l)},Ce.shouldComponentUpdate=r}return i.__N||i.__}function Je(n,e){var t=br(ti++,3);!Le.__s&&Vc(t.__H,e)&&(t.__=n,t.u=e,Ce.__H.__h.push(t))}function yr(n,e){var t=br(ti++,4);!Le.__s&&Vc(t.__H,e)&&(t.__=n,t.u=e,Ce.__h.push(t))}function Ie(n){return vr=5,fa(function(){return{current:n}},[])}function fa(n,e){var t=br(ti++,7);return Vc(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function _1(n,e){return vr=8,fa(function(){return n},e)}function wp(n){var e=Ce.context[n.__c],t=br(ti++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ce)),e.props.value):n.__}function E1(){for(var n;n=bp.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(pa),n.__H.__h.forEach(jc),n.__H.__h=[]}catch(e){n.__H.__h=[],Le.__e(e,n.__v)}}Le.__b=function(n){Ce=null,yp&&yp(n)},Le.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),xp&&xp(n,e)},Le.__r=function(n){Tp&&Tp(n),ti=0;var e=(Ce=n.__c).__H;e&&(Fc===Ce?(e.__h=[],Ce.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(pa),e.__h.forEach(jc),e.__h=[],ti=0)),Fc=Ce},Le.diffed=function(n){kp&&kp(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(bp.push(e)!==1&&vp===Le.requestAnimationFrame||((vp=Le.requestAnimationFrame)||R1)(E1)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Fc=Ce=null},Le.__c=function(n,e){e.some(function(t){try{t.__h.forEach(pa),t.__h=t.__h.filter(function(i){return!i.__||jc(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],Le.__e(i,t.__v)}}),Sp&&Sp(n,e)},Le.unmount=function(n){Cp&&Cp(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{pa(i)}catch(r){e=r}}),t.__H=void 0,e&&Le.__e(e,t.__v))};var _p=typeof requestAnimationFrame=="function";function R1(n){var e,t=function(){clearTimeout(i),_p&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);_p&&(e=requestAnimationFrame(t))}function pa(n){var e=Ce,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ce=e}function jc(n){var e=Ce;n.__c=n.__(),Ce=e}function Vc(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function Ep(n,e){return typeof e=="function"?e(n):e}function P1({size:n=24,color:e="#000"}){return g("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:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]})}function Rp({onClose:n}){return g("button",{class:"obi-button obi-close-button outline-none focus:outline-none",onClick:n,"aria-label":"Close",type:"button",autoFocus:!1,children:g(P1,{})})}function Pp({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Ie(null),a=Ie(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())},c=u=>{u.preventDefault(),a.current||(a.current="user-initiated");const d=a.current;a.current=null,t==null||t(d)},l=()=>{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",c),()=>{u.removeEventListener("click",o),u.removeEventListener("close",c)}},[t]),g("dialog",{ref:s,className:`modal-${i}`,children:[g(Rp,{onClose:l}),g("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Gc({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"),g("div",{className:o,onMouseEnter:r,onMouseLeave:s,children:g("div",{className:`obi-pill pill ${n}`,onClick:i,children:a})})}function I1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function O1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}const Ip=8,ma=8,A1=100,N1=.7,Li=3;function Op({getBands:n,color:e="white"}){const t=Ie(null);return Je(()=>{if(!n)return;let i=0,r;const s=a=>{try{if(a-i>=A1){const o=n();if(t.current){const c=t.current.querySelectorAll(".bar"),l=o&&o.length>0?o.slice(0,ma).map(u=>{const d=Math.abs(u);return Math.min(d/N1*Ip,Ip)||Li}):Array(ma).fill(Li);for(;l.length<ma;)l.push(Li);l.forEach((u,d)=>{if(u<Li&&(u=Li),c[d]){const h=u*2;c[d].style.height=`${h}px`,c[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]),g("div",{className:"obi-equaliser",ref:t,children:Array.from({length:ma},(i,r)=>g("div",{className:"column",children:g("div",{className:"bar",style:{height:`${Li}px`,backgroundColor:e,display:"block"}})},r))})}function M1(n){const{spectrum:e}=n;return g(Gc,{isActive:!0,children:g(Op,{getBands:e})})}function zc(n){const{children:e,className:t="",...i}=n;return g("div",{className:`${t} obi-panel`,...i,children:e})}function ni({type:n,size:e=24}){return g("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:L1(n)})}function L1(n){switch(n){case"pause":return g(nt,{children:[g("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),g("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return g(nt,{children:g("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return g(nt,{children:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]});case"message":return g(nt,{children:g("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return g(nt,{children:[g("path",{d:"m14 10 7-7"}),g("path",{d:"M20 10h-6V4"}),g("path",{d:"m3 21 7-7"}),g("path",{d:"M4 14h6v6"})]});case"voice":return g(nt,{children:[g("path",{d:"M2 10v3"}),g("path",{d:"M6 6v11"}),g("path",{d:"M10 3v18"}),g("path",{d:"M14 8v7"}),g("path",{d:"M18 5v13"}),g("path",{d:"M22 10v3"})]});case"open":return g(nt,{children:[g("path",{d:"M12 7v14"}),g("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const Hc=C1(null);function D1({children:n}){const e=wp(Hc);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:c,delayMs:l}=e,u=Ie(null),d=Ap(a,s),[h,f]=Y(!1);Je(()=>{t!==void 0&&t!==h&&(t?p():v()),f(t)},[t]),Je(()=>()=>{u.current&&clearTimeout(u.current)},[]);function m(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){m(),l>0?u.current=setTimeout(()=>{c==null||c(!0),r(!0),u.current=null},l):(c==null||c(!0),r(!0))}function v(){m(),c==null||c(!1),r(!1)}const b=()=>{o==="click"&&(i?v():p())};function C(){o==="hover"&&p()}function w(){o==="hover"&&v()}return g("div",{ref:d,class:"target",onClick:b,onMouseEnter:C,onMouseLeave:w,children:n})}function U1({children:n}){const e=wp(Hc);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=Ap(a,r);return yr(()=>{if(t&&!i&&s.current&&a.current){const c=a.current;if(!c)return;const l=s.current;if(!l)return;const u=c.getBoundingClientRect(),d=l.getBoundingClientRect(),h=d.right-d.left;c.style.top=`${u.top-u.bottom-(8+e.offset)}px`,c.style.left=`${-(u.right-u.left-h)/2}px`}},[t,i]),t?g("div",{ref:o,class:"content",style:{opacity:i?0:1},children:n}):null}function gt({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,c]=Y(!1),[l,u]=Y(!1),d=Ie(null),h=Ie(null),f={controlledOpen:e,isOpen:o,setIsOpen:c,animating:l,setAnimating:u,targetRef:d,contentRef:h,trigger:n,onChange:t,delayMs:r,offset:s};return g(Hc.Provider,{value:f,children:g("div",{class:`obi-popout ${a}`,children:i})})}gt.Target=D1,gt.Content=U1;function Ap(n,e){const t=Ie(null),i=Ie(null),r=Ie(!0),s=_1(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 Ft({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:g(ni,{type:"close",size:16}),pause:g(ni,{type:"pause",size:16}),play:g(ni,{type:"play",size:16}),message:g(ni,{type:"message",size:16}),minimize:g(ni,{type:"minimize",size:16}),voice:g(ni,{type:"voice",size:16}),open:g(ni,{type:"open",size:16})}[t],a={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=g("button",{class:`obi-button obi-round-button ${a} ${n}`,onClick:i?void 0:e,disabled:i,children:s});return r?g(gt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[g(gt.Target,{children:o}),g(gt.Content,{children:g("div",{className:"obi-round-button-title",children:r})})]}):o}function dn({className:n,children:e,onClick:t}){return t?g("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):g("div",{class:`obi-message ${n}`,children:e})}const B1=8;function F1({color:n="white"}){return g("div",{className:"obi-loading-dots",children:Array.from({length:B1},(e,t)=>g("div",{className:"column",children:[g("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),g("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function j1({onContinue:n,onWrapUp:e}){return g(zc,{className:"obi-exit-survey",children:g(G1,{onContinue:n,onWrapUp:()=>{e()}})})}function V1({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=Y("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return g(zc,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?g(z1,{onReasonSelect:s}):g(H1,{onReasonSelect:s,onClose:t})})}function G1({onContinue:n,onWrapUp:e}){return g("div",{className:"obi-exit-survey-container",children:[g("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),g("div",{className:"obi-exit-survey-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function z1({onReasonSelect:n}){return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),g("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"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function H1({onReasonSelect:n,onClose:e}){const[t,i]=Y("");return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:[g(Rp,{onClose:e}),g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:r=>i(r.target.value)}),g("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 W1(n,e){for(var t in e)n[t]=e[t];return n}function Np(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 Mp(n,e){this.props=n,this.context=e}(Mp.prototype=new un).isPureReactComponent=!0,Mp.prototype.shouldComponentUpdate=function(n,e){return Np(this.props,n)||Np(this.state,e)};var Lp=Z.__b;Z.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Lp&&Lp(n)};var q1=Z.__e;Z.__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)}q1(n,e,t,i)};var Dp=Z.unmount;function Up(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=W1({},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 Up(i,e,t)})),n}function Bp(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Bp(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 Wc(){this.__u=0,this.o=null,this.__b=null}function Fp(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function ga(){this.i=null,this.l=null}Z.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Dp&&Dp(n)},(Wc.prototype=new un).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=Fp(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 c=i.state.__a;i.__v.__k[0]=Bp(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),n.then(a,a)},Wc.prototype.componentWillUnmount=function(){this.o=[]},Wc.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]=Up(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&Lc(nt,null,n.fallback);return r&&(r.__u&=-33),[Lc(nt,null,e.__a?null:n.children),r]};var jp=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]}};(ga.prototype=new un).__a=function(n){var e=this,t=Fp(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),jp(e,n,i)):r()};t?t(s):s()}},ga.prototype.render=function(n){this.i=null,this.l=new Map;var e=da(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},ga.prototype.componentDidUpdate=ga.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){jp(n,t,e)})};var K1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,$1=/^(?: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]/,Y1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,X1=/[A-Z0-9]/g,J1=typeof document<"u",Q1=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};un.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(un.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var Vp=Z.event;function Z1(){}function ex(){return this.cancelBubble}function tx(){return this.defaultPrevented}Z.event=function(n){return Vp&&(n=Vp(n)),n.persist=Z1,n.isPropagationStopped=ex,n.isDefaultPrevented=tx,n.nativeEvent=n};var nx={enumerable:!1,configurable:!0,get:function(){return this.class}},Gp=Z.vnode;Z.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||J1&&a==="children"&&i==="noscript"||a==="class"||a==="className")){var c=a.toLowerCase();a==="defaultValue"&&"value"in t&&t.value==null?a="value":a==="download"&&o===!0?o="":c==="translate"&&o==="no"?o=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?a="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||Q1(t.type)?c==="onfocus"?a="onfocusin":c==="onblur"?a="onfocusout":Y1.test(a)&&(a=c):c=a="oninput":s&&$1.test(a)?a=a.replace(X1,"-$&").toLowerCase():o===null&&(o=void 0),c==="oninput"&&r[a=c]&&(a="oninputCapture"),r[a]=o}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=da(t.children).forEach(function(l){l.props.selected=r.value.indexOf(l.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=da(t.children).forEach(function(l){l.props.selected=r.multiple?r.defaultValue.indexOf(l.props.value)!=-1:r.defaultValue==l.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",nx)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=K1,Gp&&Gp(n)};var zp=Z.__r;Z.__r=function(n){zp&&zp(n),n.__c};var Hp=Z.diffed;Z.diffed=function(n){Hp&&Hp(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 ix(n){const{placeholder:e="Type your message...",value:t,defaultValue:i,onChange:r,onSend:s,onCancel:a,onExpand:o,isLoading:c=!1,disabled:l=!1,maxLength:u=500,children:d}=n,[h,f]=Y(t||i||""),[m,p]=Y((t||i||"").length>24),v=Ie(null);yr(()=>{m&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,C=k=>{const x=k.currentTarget.value;t===void 0&&f(x),r==null||r(x)},w=k=>{k.key==="Escape"&&(f(t||i||""),p(!1),a==null||a()),k.key==="Enter"&&!k.shiftKey&&b.trim()&&(k.preventDefault(),f(t||i||""),p(!1),T()),(b||"").length>=24&&!m&&(p(!0),o==null||o(!0))};Je(()=>{v.current&&v.current.focus()},[v.current]);const T=()=>{!b.trim()||c||l||(s==null||s(b.trim()),t===void 0&&f(""))};return g("div",{className:`obi-message-input ${m?"expanded":""}`,children:[g("div",{className:"container",children:g("textarea",{ref:v,className:"field",placeholder:e,value:b,onInput:C,onKeyDown:w,disabled:l||c,maxLength:u,rows:1})}),g("div",{className:"button-container",children:[m&&g("div",{children:d}),g("button",{className:"obi-button send",onClick:T,disabled:!b.trim()||c||l,type:"button",children:g("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function rx(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r,onStepClick:s}=n,[a,o]=Y(null),c=Array.from({length:t},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),l=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 ${l}`})();return g("div",{class:`obi-course-progress ${r||""}`,children:[g("div",{class:"obi-course-progress-steps",children:c.map((d,h)=>{const f=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,m=d.isCompleted?"completed":"future";function p(){s&&s(h,f)}function v(b){s&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p())}return g("div",{class:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>o(h),onMouseLeave:()=>o(null),onClick:s?p:void 0,onKeyDown:s?v:void 0,role:s?"button":void 0,tabIndex:s?0:void 0,children:g("div",{class:`obi-course-progress-step ${m}`,"aria-label":f})},h)})}),g("div",{class:"obi-course-progress-description",children:u})]})}function Wp({className:n="",size:e=64}){return g("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:g("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function sx(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=Y(null),[a,o]=Y(n.isActive??n.defaultIsActive??!1),[c,l]=Y(!1),[u,d]=Y(n.cancelling??!1),[h,f]=Y(n.messaging??!1),[m,p]=Y(!1),[v,b]=Y(h),[C,w]=Y(!1);function T(){o(!0),l(!1),w(!0)}function k(){}function x(){r&&(clearTimeout(r),s(null))}function _(){s(setTimeout(()=>{o(n.defaultIsActive??!1),w(!1)},400))}function R(te){var Ue;p(!1),(Ue=n.onMessage)==null||Ue.call(n,te)}function O(){var te;f(!1),p(!1),o(!1),l(!0),(te=n.onMinimize)==null||te.call(n)}function B(){var te;f(!1),d(!0),p(!1),(te=n.onCancelClick)==null||te.call(n)}function N(){var te;t||((te=n.onOpen)==null||te.call(n))}function W(te){var Ue,Qe,Vt,fn,Et,Qt;switch(te){case"need-help":(Ue=n.onMessage)==null||Ue.call(n,"I'm struggling, can you look at my screen and help me out."),(Qe=n.onOneClickAction)==null||Qe.call(n,"need-help");break;case"continue":(Vt=n.onMessage)==null||Vt.call(n,"Okay, let's continue."),(fn=n.onOneClickAction)==null||fn.call(n,"continue");break;case"say-again":(Et=n.onMessage)==null||Et.call(n,"Please say that again."),(Qt=n.onOneClickAction)==null||Qt.call(n,"say-again");break}}function K(te){var Ue,Qe;n.messaging===void 0?((Ue=n.onMessagingChange)==null||Ue.call(n,te),f(te)):((Qe=n.onMessagingChange)==null||Qe.call(n,!n.messaging),f(!n.messaging)),te||p(!1)}const M=n.isActive??((a||t)&&!c&&!e),Q=M&&t,X=M&&t&&!m,Te=n.speakingStatus==="user-speaking",me=n.speakingStatus==="thinking",xe=n.speakingStatus==="busy",ze=M&&!t&&!u&&C,G=M&&t&&i&&!Te&&!u,re=M&&t&&!G&&!Te&&h!==v&&!u,oe=M&&t&&i&&Te&&!u,we=M&&t&&!i&&Te&&!u,J=M&&t&&!i&&xe&&!u,ge=n.messaging!==void 0?n.messaging:h,De=ge&&Te,yt=ze||G||oe||we||re||u,Tt=400,ai=!!n.courseProgress&&!c,Fi=ze?5:10;return yr(()=>{b(h)},[Te]),!t&&!u?g(ax,{...n}):!t&&u?g(ox,{onOtherSelect:()=>{var te;(te=n.onCancelReasonOther)==null||te.call(n)},onCancelReason:te=>{var Ue;o(n.defaultIsActive??!1),d(!1),(Ue=n.onCancelReason)==null||Ue.call(n,te)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):g(zc,{className:`obi-widget-panel ${Q?"expanded":""} ${m?"maximized":""} ${ge?"messaging":""} ${xe?"tool-usage":""}`,children:[g("div",{className:`obi-widget ${M?"active":""} ${t?"in-plan":""}`,onMouseEnter:x,onMouseLeave:_,children:[X&&g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),X&&!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),X&&i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(gt,{className:"obi-widget-popout",open:yt,trigger:null,delayMs:Tt,offset:Fi,children:[g(gt.Target,{children:[De&&g(ix,{value:n.message,onCancel:()=>K(!1),onSend:R,onExpand:p,onChange:n.onMessageChange,children:g("div",{className:"obi-widget-buttons",children:[g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(Ft,{type:ge?"voice":"message",onClick:()=>K(!ge),title:ge?"Voice input":"Text input"}),g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]})}),!De&&g(Gc,{className:M&&!t?"button":"",isActive:M,speakingStatus:n.speakingStatus,onClick:N,onMouseEnter:T,onMouseLeave:k,children:[M&&!t&&!J&&g("span",{className:"obi-widget-pill-text",children:"Tutorials"}),M&&t&&J&&g("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),M&&t&&!me&&!J&&g(Op,{getBands:n.spectrum}),M&&me&&!J&&g(F1,{})]})]}),g(gt.Content,{children:g("div",{onMouseLeave:_,children:[ze&&g(dn,{onClick:N,children:"Click to see all"}),G&&g(dn,{children:"Session will pause shortly"}),re&&g(dn,{children:["Switched to ",ge?"chat":"voice"]}),oe&&g(dn,{children:"Paused"}),we&&g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[g(dn,{onClick:()=>W("need-help"),children:"Need help"}),g(dn,{onClick:()=>W("continue"),children:"Continue"}),g(dn,{onClick:()=>W("say-again"),children:"Say again"})]}),u&&g(j1,{onContinue:()=>{var te;(te=n.onCancelAbort)==null||te.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var te;(te=n.onCancel)==null||te.call(n)}})]})})]}),X&&g(Ft,{type:ge?"voice":"message",onClick:()=>K(!ge),title:ge?"Voice input":"Text input"}),X&&g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]}),ai&&n.courseProgress&&g("div",{className:`obi-widget-course-progress ${ge?"expanded":""}`,children:g(rx,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames,onStepClick:(te,Ue)=>{var Vt;const Qe=`Can we please jump to the steps related to: ${Ue}`;(Vt=n.onMessage)==null||Vt.call(n,Qe)}})})]})}function ax(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=Y(null),[o,c]=Y(n.isActive??n.defaultIsActive??!1),[l,u]=Y(!1),[d,h]=Y(n.hovered??!1),[f,m]=Y(null),[p,v]=Y(null);function b(){p&&(clearTimeout(p),v(null)),f&&m(null)}function C(){var K;c(!0),u(!1),h(!0),(K=n.onHover)==null||K.call(n,!0)}function w(){}function T(){s&&(clearTimeout(s),a(null))}function k(){o&&a(setTimeout(()=>{var K;c(n.defaultIsActive??!1),h(!1),(K=n.onHover)==null||K.call(n,!1)},400))}function x(){b(),c(!1),u(!0)}function _(){var K;b(),(K=n.onOpen)==null||K.call(n)}const R=n.hovered??(d&&!l),O=n.isActive??(o&&!e&&!l),B=O&&R||!!f,N=`round-button ${O?"active":""}`;let W=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(W=`${t}/${i} completed`),yr(()=>{if(n.toastMessage&&n.toastMessage.text){p&&clearTimeout(p);const K=n.toastMessage.autoCloseMs??3e3;m({text:n.toastMessage.text,autoCloseMs:K});const M=setTimeout(()=>{m(null)},K);v(M)}else n.toastMessage===null&&(p&&clearTimeout(p),m(null))},[n.toastMessage]),g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:`obi-widget-out-of-plan ${R?"hover":""} ${O?"active":""}`,onMouseEnter:T,onMouseLeave:k,onClickCapture:b,children:[g("div",{className:N,style:{width:"30px",height:"30px"}}),g(gt,{className:"obi-widget-popout",open:B,trigger:null,delayMs:400,offset:5,children:[g(gt.Target,{children:g(O1,{className:O?"button":"",active:O,onClick:_,onMouseEnter:C,onMouseLeave:w,children:g("span",{className:"text",children:[g(Wp,{size:16}),W]})})}),g(gt.Content,{children:[!!f&&g(dn,{onClick:()=>{b(),_()},children:f.text}),!f&&g("div",{onMouseLeave:k,children:g(dn,{className:"message",onClick:_,children:"Click to see all"})})]})]}),g(Ft,{className:N,type:"minimize",onClick:x,title:"Minimize widget"})]})})}function ox(n){return g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:"obi-widget-out-of-plan",children:g(gt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[g(gt.Target,{children:g(I1,{active:!1})}),g(gt.Content,{children:g(V1,{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 cx({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return g(Pp,{open:n,onClose:t,preventOutsideClick:i,size:"medium",children:g("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function lx(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var qp={exports:{}};(function(n){(function(){var e={}.hasOwnProperty;function t(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=r(s,i(o)))}return s}function i(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return t.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)e.call(s,o)&&s[o]&&(a=r(a,o));return a}function r(s,a){return a?s?s+" "+a:s+a:s}n.exports?(t.default=t,n.exports=t):window.classNames=t})()})(qp);var ux=qp.exports;const dx=lx(ux);function Di({className:n,title:e="",agentName:t="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:s=!1,footer:a,href:o=null,glow:c=!1,centerVisual:l,description:u,button:d,onAction:h}){const[f,m]=Y(s),[p,v]=Y(!1),[b,C]=Y(r);Je(()=>{p||(r==="listening"&&b!=="listening"&&f&&m(!1),r!=="listening"&&!f&&m(!0)),C(r)},[r,f]),Je(()=>{m(s)},[s]);const w=()=>{f||(m(!0),v(!0),h==null||h())},T=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return i}},k=o?"a":"button",x=o?{href:o,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return g("div",{className:dx("tour-content",n),children:g("div",{className:"container",children:[g("div",{className:`visual ${c?"glow":""}`,children:l}),g("div",{className:"header",children:[g("h1",{className:"title",children:e}),g("div",{className:"description",children:u})]}),g("div",{className:"button-container",children:d||g(k,{className:`action-button ${f?"disabled":""}`,onClick:w,disabled:f,...x,children:g("span",{className:"button-text",children:T()})})}),a&&g("div",{className:"tour-footer",children:a})]})})}function hx({logoUrl:n="",appName:e="App"}){const[t,i]=Y(!1),[r,s]=Y(!1),a=()=>{i(!0)},o=()=>{s(!0),i(!1)},c={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 g("div",{style:c.container,children:g("div",{style:c.logoContainer,children:[g("div",{style:c.backgroundPattern}),g("div",{style:c.logoWrapper,children:[n&&g("img",{style:c.appLogo,src:n,alt:`${e} logo`,onError:a,onLoad:o}),g("div",{style:c.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function fx({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 g(Di,{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:g(hx,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}const{entries:Kp,setPrototypeOf:$p,isFrozen:px,getPrototypeOf:mx,getOwnPropertyDescriptor:gx}=Object;let{freeze:st,seal:_t,create:Yp}=Object,{apply:qc,construct:Kc}=typeof Reflect<"u"&&Reflect;st||(st=function(n){return n}),_t||(_t=function(n){return n}),qc||(qc=function(n,e,t){return n.apply(e,t)}),Kc||(Kc=function(n,e){return new n(...e)});const va=ot(Array.prototype.forEach),vx=ot(Array.prototype.lastIndexOf),Xp=ot(Array.prototype.pop),Tr=ot(Array.prototype.push),bx=ot(Array.prototype.splice),ba=ot(String.prototype.toLowerCase),$c=ot(String.prototype.toString),Jp=ot(String.prototype.match),kr=ot(String.prototype.replace),yx=ot(String.prototype.indexOf),Tx=ot(String.prototype.trim),jt=ot(Object.prototype.hasOwnProperty),at=ot(RegExp.prototype.test),Sr=kx(TypeError);function ot(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 qc(n,e,i)}}function kx(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Kc(n,t)}}function ee(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ba;$p&&$p(n,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const s=t(r);s!==r&&(px(e)||(e[i]=s),r=s)}n[r]=!0}return n}function Sx(n){for(let e=0;e<n.length;e++)jt(n,e)||(n[e]=null);return n}function hn(n){const e=Yp(null);for(const[t,i]of Kp(n))jt(n,t)&&(Array.isArray(i)?e[t]=Sx(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=hn(i):e[t]=i);return e}function Cr(n,e){for(;n!==null;){const i=gx(n,e);if(i){if(i.get)return ot(i.get);if(typeof i.value=="function")return ot(i.value)}n=mx(n)}function t(){return null}return t}const Qp=st(["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"]),Yc=st(["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"]),Xc=st(["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"]),Cx=st(["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"]),Jc=st(["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"]),xx=st(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Zp=st(["#text"]),em=st(["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"]),Qc=st(["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"]),tm=st(["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"]),ya=st(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),wx=_t(/\{\{[\w\W]*|[\w\W]*\}\}/gm),_x=_t(/<%[\w\W]*|[\w\W]*%>/gm),Ex=_t(/\$\{[\w\W]*/gm),Rx=_t(/^data-[\-\w.\u00B7-\uFFFF]+$/),Px=_t(/^aria-[\-\w]+$/),nm=_t(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ix=_t(/^(?:\w+script|data):/i),Ox=_t(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),im=_t(/^html$/i),Ax=_t(/^[a-z][.\w]*(-[.\w]+)+$/i);var rm=Object.freeze({__proto__:null,ARIA_ATTR:Px,ATTR_WHITESPACE:Ox,CUSTOM_ELEMENT:Ax,DATA_ATTR:Rx,DOCTYPE_NAME:im,ERB_EXPR:_x,IS_ALLOWED_URI:nm,IS_SCRIPT_OR_DATA:Ix,MUSTACHE_EXPR:wx,TMPLIT_EXPR:Ex});const xr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Nx=function(){return typeof window>"u"?null:window},Mx=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}},sm=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function am(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Nx();const e=S=>am(S);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==xr.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:c,NodeFilter:l,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=n,m=c.prototype,p=Cr(m,"cloneNode"),v=Cr(m,"remove"),b=Cr(m,"nextSibling"),C=Cr(m,"childNodes"),w=Cr(m,"parentNode");if(typeof a=="function"){const S=t.createElement("template");S.content&&S.content.ownerDocument&&(t=S.content.ownerDocument)}let T,k="";const{implementation:x,createNodeIterator:_,createDocumentFragment:R,getElementsByTagName:O}=t,{importNode:B}=i;let N=sm();e.isSupported=typeof Kp=="function"&&typeof w=="function"&&x&&x.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:W,ERB_EXPR:K,TMPLIT_EXPR:M,DATA_ATTR:Q,ARIA_ATTR:X,IS_SCRIPT_OR_DATA:Te,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:xe}=rm;let{IS_ALLOWED_URI:ze}=rm,G=null;const re=ee({},[...Qp,...Yc,...Xc,...Jc,...Zp]);let oe=null;const we=ee({},[...em,...Qc,...tm,...ya]);let J=Object.seal(Yp(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}})),ge=null,De=null,yt=!0,Tt=!0,ai=!1,Fi=!0,te=!1,Ue=!0,Qe=!1,Vt=!1,fn=!1,Et=!1,Qt=!1,oi=!1,Er=!0,Rr=!1;const Ea="user-content-";let ji=!0,jn=!1,pn={},mn=null;const Pr=ee({},["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 A=null;const z=ee({},["audio","video","img","source","image","track"]);let $=null;const ve=ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Be="http://www.w3.org/1998/Math/MathML",ct="http://www.w3.org/2000/svg",vt="http://www.w3.org/1999/xhtml";let Vn=vt,Vi=!1,Gi=null;const Ra=ee({},[Be,ct,vt],$c);let Zt=ee({},["mi","mo","mn","ms","mtext"]),Pa=ee({},["annotation-xml"]);const f_=ee({},["title","style","font","a","script"]);let Ir=null;const p_=["application/xhtml+xml","text/html"],m_="text/html";let qe=null,zi=null;const g_=t.createElement("form"),Nm=function(S){return S instanceof RegExp||S instanceof Function},al=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(zi&&zi===S)){if((!S||typeof S!="object")&&(S={}),S=hn(S),Ir=p_.indexOf(S.PARSER_MEDIA_TYPE)===-1?m_:S.PARSER_MEDIA_TYPE,qe=Ir==="application/xhtml+xml"?$c:ba,G=jt(S,"ALLOWED_TAGS")?ee({},S.ALLOWED_TAGS,qe):re,oe=jt(S,"ALLOWED_ATTR")?ee({},S.ALLOWED_ATTR,qe):we,Gi=jt(S,"ALLOWED_NAMESPACES")?ee({},S.ALLOWED_NAMESPACES,$c):Ra,$=jt(S,"ADD_URI_SAFE_ATTR")?ee(hn(ve),S.ADD_URI_SAFE_ATTR,qe):ve,A=jt(S,"ADD_DATA_URI_TAGS")?ee(hn(z),S.ADD_DATA_URI_TAGS,qe):z,mn=jt(S,"FORBID_CONTENTS")?ee({},S.FORBID_CONTENTS,qe):Pr,ge=jt(S,"FORBID_TAGS")?ee({},S.FORBID_TAGS,qe):hn({}),De=jt(S,"FORBID_ATTR")?ee({},S.FORBID_ATTR,qe):hn({}),pn=jt(S,"USE_PROFILES")?S.USE_PROFILES:!1,yt=S.ALLOW_ARIA_ATTR!==!1,Tt=S.ALLOW_DATA_ATTR!==!1,ai=S.ALLOW_UNKNOWN_PROTOCOLS||!1,Fi=S.ALLOW_SELF_CLOSE_IN_ATTR!==!1,te=S.SAFE_FOR_TEMPLATES||!1,Ue=S.SAFE_FOR_XML!==!1,Qe=S.WHOLE_DOCUMENT||!1,Et=S.RETURN_DOM||!1,Qt=S.RETURN_DOM_FRAGMENT||!1,oi=S.RETURN_TRUSTED_TYPE||!1,fn=S.FORCE_BODY||!1,Er=S.SANITIZE_DOM!==!1,Rr=S.SANITIZE_NAMED_PROPS||!1,ji=S.KEEP_CONTENT!==!1,jn=S.IN_PLACE||!1,ze=S.ALLOWED_URI_REGEXP||nm,Vn=S.NAMESPACE||vt,Zt=S.MATHML_TEXT_INTEGRATION_POINTS||Zt,Pa=S.HTML_INTEGRATION_POINTS||Pa,J=S.CUSTOM_ELEMENT_HANDLING||{},S.CUSTOM_ELEMENT_HANDLING&&Nm(S.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=S.CUSTOM_ELEMENT_HANDLING.tagNameCheck),S.CUSTOM_ELEMENT_HANDLING&&Nm(S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),S.CUSTOM_ELEMENT_HANDLING&&typeof S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),te&&(Tt=!1),Qt&&(Et=!0),pn&&(G=ee({},Zp),oe=[],pn.html===!0&&(ee(G,Qp),ee(oe,em)),pn.svg===!0&&(ee(G,Yc),ee(oe,Qc),ee(oe,ya)),pn.svgFilters===!0&&(ee(G,Xc),ee(oe,Qc),ee(oe,ya)),pn.mathMl===!0&&(ee(G,Jc),ee(oe,tm),ee(oe,ya))),S.ADD_TAGS&&(G===re&&(G=hn(G)),ee(G,S.ADD_TAGS,qe)),S.ADD_ATTR&&(oe===we&&(oe=hn(oe)),ee(oe,S.ADD_ATTR,qe)),S.ADD_URI_SAFE_ATTR&&ee($,S.ADD_URI_SAFE_ATTR,qe),S.FORBID_CONTENTS&&(mn===Pr&&(mn=hn(mn)),ee(mn,S.FORBID_CONTENTS,qe)),ji&&(G["#text"]=!0),Qe&&ee(G,["html","head","body"]),G.table&&(ee(G,["tbody"]),delete ge.tbody),S.TRUSTED_TYPES_POLICY){if(typeof S.TRUSTED_TYPES_POLICY.createHTML!="function")throw Sr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof S.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Sr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=S.TRUSTED_TYPES_POLICY,k=T.createHTML("")}else T===void 0&&(T=Mx(f,r)),T!==null&&typeof k=="string"&&(k=T.createHTML(""));st&&st(S),zi=S}},Mm=ee({},[...Yc,...Xc,...Cx]),Lm=ee({},[...Jc,...xx]),v_=function(S){let q=w(S);(!q||!q.tagName)&&(q={namespaceURI:Vn,tagName:"template"});const F=ba(S.tagName),he=ba(q.tagName);return Gi[S.namespaceURI]?S.namespaceURI===ct?q.namespaceURI===vt?F==="svg":q.namespaceURI===Be?F==="svg"&&(he==="annotation-xml"||Zt[he]):!!Mm[F]:S.namespaceURI===Be?q.namespaceURI===vt?F==="math":q.namespaceURI===ct?F==="math"&&Pa[he]:!!Lm[F]:S.namespaceURI===vt?q.namespaceURI===ct&&!Pa[he]||q.namespaceURI===Be&&!Zt[he]?!1:!Lm[F]&&(f_[F]||!Mm[F]):!!(Ir==="application/xhtml+xml"&&Gi[S.namespaceURI]):!1},ci=function(S){Tr(e.removed,{element:S});try{w(S).removeChild(S)}catch{v(S)}},Hi=function(S,q){try{Tr(e.removed,{attribute:q.getAttributeNode(S),from:q})}catch{Tr(e.removed,{attribute:null,from:q})}if(q.removeAttribute(S),S==="is")if(Et||Qt)try{ci(q)}catch{}else try{q.setAttribute(S,"")}catch{}},Dm=function(S){let q=null,F=null;if(fn)S="<remove></remove>"+S;else{const Oe=Jp(S,/^[\r\n\t ]+/);F=Oe&&Oe[0]}Ir==="application/xhtml+xml"&&Vn===vt&&(S='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+S+"</body></html>");const he=T?T.createHTML(S):S;if(Vn===vt)try{q=new h().parseFromString(he,Ir)}catch{}if(!q||!q.documentElement){q=x.createDocument(Vn,"template",null);try{q.documentElement.innerHTML=Vi?k:he}catch{}}const Ze=q.body||q.documentElement;return S&&F&&Ze.insertBefore(t.createTextNode(F),Ze.childNodes[0]||null),Vn===vt?O.call(q,Qe?"html":"body")[0]:Qe?q.documentElement:Ze},Um=function(S){return _.call(S.ownerDocument||S,S,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ol=function(S){return S instanceof d&&(typeof S.nodeName!="string"||typeof S.textContent!="string"||typeof S.removeChild!="function"||!(S.attributes instanceof u)||typeof S.removeAttribute!="function"||typeof S.setAttribute!="function"||typeof S.namespaceURI!="string"||typeof S.insertBefore!="function"||typeof S.hasChildNodes!="function")},Bm=function(S){return typeof o=="function"&&S instanceof o};function gn(S,q,F){va(S,he=>{he.call(e,q,F,zi)})}const Fm=function(S){let q=null;if(gn(N.beforeSanitizeElements,S,null),ol(S))return ci(S),!0;const F=qe(S.nodeName);if(gn(N.uponSanitizeElement,S,{tagName:F,allowedTags:G}),Ue&&S.hasChildNodes()&&!Bm(S.firstElementChild)&&at(/<[/\w!]/g,S.innerHTML)&&at(/<[/\w!]/g,S.textContent)||S.nodeType===xr.progressingInstruction||Ue&&S.nodeType===xr.comment&&at(/<[/\w]/g,S.data))return ci(S),!0;if(!G[F]||ge[F]){if(!ge[F]&&Vm(F)&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,F)||J.tagNameCheck instanceof Function&&J.tagNameCheck(F)))return!1;if(ji&&!mn[F]){const he=w(S)||S.parentNode,Ze=C(S)||S.childNodes;if(Ze&&he){const Oe=Ze.length;for(let vn=Oe-1;vn>=0;--vn){const Gt=p(Ze[vn],!0);Gt.__removalCount=(S.__removalCount||0)+1,he.insertBefore(Gt,b(S))}}}return ci(S),!0}return S instanceof c&&!v_(S)||(F==="noscript"||F==="noembed"||F==="noframes")&&at(/<\/no(script|embed|frames)/i,S.innerHTML)?(ci(S),!0):(te&&S.nodeType===xr.text&&(q=S.textContent,va([W,K,M],he=>{q=kr(q,he," ")}),S.textContent!==q&&(Tr(e.removed,{element:S.cloneNode()}),S.textContent=q)),gn(N.afterSanitizeElements,S,null),!1)},jm=function(S,q,F){if(Er&&(q==="id"||q==="name")&&(F in t||F in g_))return!1;if(!(Tt&&!De[q]&&at(Q,q))&&!(yt&&at(X,q))){if(!oe[q]||De[q]){if(!(Vm(S)&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,S)||J.tagNameCheck instanceof Function&&J.tagNameCheck(S))&&(J.attributeNameCheck instanceof RegExp&&at(J.attributeNameCheck,q)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(q))||q==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,F)||J.tagNameCheck instanceof Function&&J.tagNameCheck(F))))return!1}else if(!$[q]&&!at(ze,kr(F,me,""))&&!((q==="src"||q==="xlink:href"||q==="href")&&S!=="script"&&yx(F,"data:")===0&&A[S])&&!(ai&&!at(Te,kr(F,me,"")))&&F)return!1}return!0},Vm=function(S){return S!=="annotation-xml"&&Jp(S,xe)},Gm=function(S){gn(N.beforeSanitizeAttributes,S,null);const{attributes:q}=S;if(!q||ol(S))return;const F={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:oe,forceKeepAttr:void 0};let he=q.length;for(;he--;){const Ze=q[he],{name:Oe,namespaceURI:vn,value:Gt}=Ze,en=qe(Oe),cl=Gt;let it=Oe==="value"?cl:Tx(cl);if(F.attrName=en,F.attrValue=it,F.keepAttr=!0,F.forceKeepAttr=void 0,gn(N.uponSanitizeAttribute,S,F),it=F.attrValue,Rr&&(en==="id"||en==="name")&&(Hi(Oe,S),it=Ea+it),Ue&&at(/((--!?|])>)|<\/(style|title)/i,it)){Hi(Oe,S);continue}if(F.forceKeepAttr)continue;if(!F.keepAttr){Hi(Oe,S);continue}if(!Fi&&at(/\/>/i,it)){Hi(Oe,S);continue}te&&va([W,K,M],y_=>{it=kr(it,y_," ")});const zm=qe(S.nodeName);if(!jm(zm,en,it)){Hi(Oe,S);continue}if(T&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!vn)switch(f.getAttributeType(zm,en)){case"TrustedHTML":{it=T.createHTML(it);break}case"TrustedScriptURL":{it=T.createScriptURL(it);break}}if(it!==cl)try{vn?S.setAttributeNS(vn,Oe,it):S.setAttribute(Oe,it),ol(S)?ci(S):Xp(e.removed)}catch{Hi(Oe,S)}}gn(N.afterSanitizeAttributes,S,null)},b_=function S(q){let F=null;const he=Um(q);for(gn(N.beforeSanitizeShadowDOM,q,null);F=he.nextNode();)gn(N.uponSanitizeShadowNode,F,null),Fm(F),Gm(F),F.content instanceof s&&S(F.content);gn(N.afterSanitizeShadowDOM,q,null)};return e.sanitize=function(S){let q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},F=null,he=null,Ze=null,Oe=null;if(Vi=!S,Vi&&(S="<!-->"),typeof S!="string"&&!Bm(S))if(typeof S.toString=="function"){if(S=S.toString(),typeof S!="string")throw Sr("dirty is not a string, aborting")}else throw Sr("toString is not a function");if(!e.isSupported)return S;if(Vt||al(q),e.removed=[],typeof S=="string"&&(jn=!1),jn){if(S.nodeName){const en=qe(S.nodeName);if(!G[en]||ge[en])throw Sr("root node is forbidden and cannot be sanitized in-place")}}else if(S instanceof o)F=Dm("<!---->"),he=F.ownerDocument.importNode(S,!0),he.nodeType===xr.element&&he.nodeName==="BODY"||he.nodeName==="HTML"?F=he:F.appendChild(he);else{if(!Et&&!te&&!Qe&&S.indexOf("<")===-1)return T&&oi?T.createHTML(S):S;if(F=Dm(S),!F)return Et?null:oi?k:""}F&&fn&&ci(F.firstChild);const vn=Um(jn?S:F);for(;Ze=vn.nextNode();)Fm(Ze),Gm(Ze),Ze.content instanceof s&&b_(Ze.content);if(jn)return S;if(Et){if(Qt)for(Oe=R.call(F.ownerDocument);F.firstChild;)Oe.appendChild(F.firstChild);else Oe=F;return(oe.shadowroot||oe.shadowrootmode)&&(Oe=B.call(i,Oe,!0)),Oe}let Gt=Qe?F.outerHTML:F.innerHTML;return Qe&&G["!doctype"]&&F.ownerDocument&&F.ownerDocument.doctype&&F.ownerDocument.doctype.name&&at(im,F.ownerDocument.doctype.name)&&(Gt="<!DOCTYPE "+F.ownerDocument.doctype.name+`>
|
|
42
|
+
`},gc}var _f;function gC(){if(_f)return Dt;_f=1;var n=pC(),e=mC(),t=mc();return Dt.grammar=t,Dt.write=e,Dt.parse=n.parse,Dt.parseParams=n.parseParams,Dt.parseFmtpConfig=n.parseFmtpConfig,Dt.parsePayloads=n.parsePayloads,Dt.parseRemoteCandidates=n.parseRemoteCandidates,Dt.parseImageAttributes=n.parseImageAttributes,Dt.parseSimulcastStreamList=n.parseSimulcastStreamList,Dt}var Un=gC();function vc(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,c=t.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),m=this;return new Promise(function(p,v){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!a){var w=n.apply(m,f);o&&o(w),u.forEach(function(T){return(0,T.resolve)(w)}),u=[]}},d()),b){var C=n.apply(m,f);return o&&o(C),p(C)}u.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(m){return(0,m.reject)(f)}),u=[]},h}const vC=.7,bC=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Ef extends Xt.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=ie,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=vc(r=>y(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),bC),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=sn((i=t.loggerName)!==null&&i!==void 0?i:Mt.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}=yC(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=Un.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(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0)return!0;let c=!1;for(const l of s.fmtp)if(l.payload===o){l.config=l.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(l.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Un.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(Oi.NegotiationComplete),e.sdp&&Un.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Oi.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=Un.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{Pf(s),s.type==="audio"?Rf(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(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0||(dr(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*vC);for(const l of s.fmtp)if(l.payload===o){l.config.includes("x-google-start-bitrate")||(l.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,Un.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Un.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Pf(r),r.type==="audio"&&Rf(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Un.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 Ge("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 Ge("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 Wo(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===of))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:of})}}}function Rf(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 yC(n){var e;const t=[],i=[],r=Un.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(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function Pf(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 bc="vp8",TC={audioPreset:Yo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Jo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:bc,backupCodec:!0},If={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Of={deviceId:{ideal:"default"},resolution:ur.h720.resolution},kC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new dS,disconnectOnPageLeave:!0,webAudioMix:!1},yc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Re;(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"})(Re||(Re={}));class SC{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=yc.peerConnectionTimeout,this.log=ie,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Re.CONNECTED:o.some(c=>c==="failed")?this.state=Re.FAILED:o.some(c=>c==="connecting")?this.state=Re.CONNECTING:o.every(c=>c==="closed")?this.state=Re.CLOSED:o.some(c=>c==="closed")?this.state=Re.CLOSING:o.every(c=>c==="new")&&(this.state=Re.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Re[a]," to ").concat(Re[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=sn((r=i.loggerName)!==null&&r!==void 0?r:Mt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Ef(e,i),this.subscriber=new Ef(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,Nt.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Nt.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=Re.NEW,this.connectionLock=new dt,this.remoteOfferLock=new dt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return 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===Nt.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(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.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===Nt.PUBLISHER?this.publisher.getConnectedAddress():e===Nt.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((c,l)=>y(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Xe.clearTimeout(d),l(new pe("room connection has been cancelled",se.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Xe.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(new pe("could not establish pc connection",se.InternalError))},a);for(;this.state!==Re.CONNECTED;)if(yield pt(50),r!=null&&r.signal.aborted){l(new pe("room connection has been cancelled",se.Cancelled));return}Xe.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class Pe extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Nf(t,Pe.MAX_MESSAGE_BYTES),this.data=i?Nf(i,Pe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Pe(e.code,e.message,e.data)}toProto(){return new Kd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Pe(Pe.ErrorCode[e],Pe.ErrorMessage[e],t)}}Pe.MAX_MESSAGE_BYTES=256,Pe.MAX_DATA_BYTES=15360,Pe.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},Pe.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 Af=15360;function Tc(n){return new TextEncoder().encode(n).length}function Nf(n,e){if(Tc(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 kc=2e3;function Zs(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 CC=1e3;class Mf 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=vc(()=>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(D.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new dt,this.pauseUpstreamLock=new dt,this.processorLock=new dt,this.restartLock=new dt,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=>{Ei(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&&(_i(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=>{_i(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]:CC;return function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Lt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield pt(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield pt(50)}throw new an("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===Ln(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ln(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?We.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 an("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=hS(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(l=>{Ei(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(D.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?D.Muted:D.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),cf()&&(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(D.UpstreamPaused,this);const i=Lt();if((i==null?void 0:i.name)==="Safari"&&Jn(i.version,"12.0")<0)throw new Ho("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(D.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),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),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(_i(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Ei(i._mediaStreamTrack,l),_i(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(D.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(D.TrackProcessorUpdate))}()})}}class ea extends Mf{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=Zs(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.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!==Ln(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=uc({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(){mt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},kc)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Jt()&&!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(D.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 vf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(D.AudioSilenceDetected)),e})}}function xC(n,e,t){switch(n.kind){case"audio":return new ea(n,e,!1,void 0,t);case"video":return new na(n,e,!1,t);default:throw new an("unsupported track type: ".concat(n.kind))}}const wC=Object.values(ur),_C=Object.values(Xo),EC=Object.values(Jo),RC=[ur.h180,ur.h360],PC=[Xo.h180,Xo.h360],IC=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new fe(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)}),Sc=["q","h","f"];function Cc(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,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=AC(n,e,t,l),ie.debug("using video encoding",a));const u=a.maxFramerate,d=new fe(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&dr(l)){const m=new ta(c),p=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Lt();if(Mn()||Jt()||(v==null?void 0:v.name)==="Chrome"&&Jn(v==null?void 0:v.version,"113")<0){const b=m.suffix=="h"?2:3;for(let C=0;C<m.spatial;C+=1)p.push({rid:Sc[2-C],maxBitrate:a.maxBitrate/Math.pow(b,C),maxFramerate:d.encoding.maxFramerate});p[0].scalabilityMode=c}else p.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),ie.debug("using svc encoding",{encodings:p}),p}if(!o)return[a];let h=[];n?h=(r=Df(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Lf(n,d):h=(s=Df(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Lf(n,d);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const p=Math.max(e,t);if(p>=960&&f)return xc(e,t,[m,f,d],u);if(p>=480)return xc(e,t,[m,d],u)}return xc(e,t,[d])}function OC(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ie.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(),c=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,l=(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),Cc(n.source===I.Source.ScreenShare,c,l,t)}function AC(n,e,t,i){const r=NC(n,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.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 NC(n,e,t){if(n)return EC;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?wC:_C}function Lf(n,e){if(n)return IC(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)?RC:PC}function xc(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=Sc.length)return;const o=Math.min(n,e),l={rid:Sc[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&&(l.maxFramerate=u);const d=Ri()||a===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),Jt()&&uf()==="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 c;o.maxFramerate!=s&&(a&&(a=!1,ie.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ie.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Df(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 ta{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 MC(n){return n.source===I.Source.ScreenShare||n.constraints.height&&Ln(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const LC=5e3;class na extends Mf{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((c,l)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);o+=Zs(c,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new dt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!mt())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()},kc))}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,c=In(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)s=l.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=c.return)&&(yield r.call(c))}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,c=In(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){s=l.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=c.return)&&(yield r.call(c))}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=wt.LOW;i<=wt.HIGH;i+=1)t.push(new Ao({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=uc({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var c=!0,l=In(this.simulcastCodecs.values()),u;u=yield l.next(),t=u.done,!t;c=!0){s=u.value,c=!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{!c&&!t&&(r=l.return)&&(yield r.call(l))}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,c,l,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=In(r.simulcastCodecs.values()),m;m=yield f.next(),a=m.done,!a;h=!0)l=m.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(p){o={error:p}}finally{try{!h&&!a&&(c=f.return)&&(yield c.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)},LC))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,i=In(e);r=yield i.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const u=c;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){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Uf(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 l})}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 Uf(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),cf()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Uf(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:c}=o;if(!c)return;if(c.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:c,senderEncodings:e}));return}let l=!1;const u=Lt();if((u==null?void 0:u.name)==="Chrome"&&Jn(u==null?void 0:u.version,"133")>0&&c[0].scalabilityMode){const h=c[0],f=new ta(h.scalabilityMode);let m=Ti.OFF;if(t.forEach(p=>{p.enabled&&(m===Ti.OFF||p.quality>m)&&(m=p.quality)}),m===Ti.OFF)h.active&&(h.active=!1,l=!0);else if(!h.active||f.spatial!==m+1){l=!0,h.active=!0;const p=new ta(e[0].scalabilityMode);f.spatial=m+1,f.suffix=p.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-m),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,f)=>{var m;let p=(m=h.rid)!==null&&m!==void 0?m:"";p===""&&(p="q");const v=Bf(p),b=t.find(C=>C.quality===v);b&&h.active!==b.enabled&&(l=!0,h.active=b.enabled,r.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),s),Ri()&&(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)))});l&&(o.encodings=c,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Bf(n){switch(n){case"f":return wt.HIGH;case"h":return wt.MEDIUM;case"q":return wt.LOW;default:return wt.HIGH}}function Ff(n,e,t,i){if(!t)return[new $n({quality:wt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new ta(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)a.push(new $n({quality:Math.min(wt.HIGH,s.spatial-1)-l,width:Math.ceil(n/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Bf((a=r.rid)!==null&&a!==void 0?a:"");return new $n({quality:l,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const jf="_lossy",Vf="_reliable",DC=2*1e3,wc="leave-reconnect";var Ut;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ut||(Ut={}));class UC extends Xt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=yc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ut.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ie,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===Vf)s.reliableDCSub=a;else if(a.label===jf)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 c=ft.fromBinary(new Uint8Array(o));((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(U.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&FC(c,c.value.value),this.emit(U.DataPacketReceived,c))}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?ae.LOSSY:ae.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(U.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===wc&&(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=Xe.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ut.Connected&&i();const s=()=>{this.off(U.Disconnected,a),i()},a=()=>{this.off(U.Restarted,s),r()};this.once(U.Restarted,s),this.once(U.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(U.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ye.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=sn((t=e.loggerName)!==null&&t!==void 0?t:Mt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new hc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new dt,this.dataProcessLock=new dt,this.dcBufferStatus=new Map([[ae.LOSSY,!0],[ae.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(U.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(U.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(U.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(U.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(U.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(U.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(U.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(U.SignalRequestResponse,i)}get logContext(){var e,t,i,r,s,a,o,c;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:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.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(U.SignalConnected)},10),s}catch(s){if(s instanceof pe&&s.reason===se.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(U.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 an("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 pe("publication of local track timed out, no response from server",se.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!==Re.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new SC(r,e.subscriberPrimary,this.loggerOptions),this.emit(U.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===Re.CONNECTED){const u=this.pcState===Ut.New;this.pcState=Ut.Connected,u&&this.emit(U.Connected,e)}else s===Re.FAILED&&this.pcState===Ut.Connected&&(this.pcState=Ut.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ye.RECONNECTING,l=[Re.FAILED,Re.CLOSING,Re.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(U.Offline)}),this.pcManager.onTrack=s=>{this.emit(U.MediaTrackAdded,s.track,s.streams[0],s.receiver)},BC((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(U.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(U.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(U.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(U.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(U.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ki.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 xi.DISCONNECT:this.emit(U.Disconnected,e==null?void 0:e.reason),this.close();break;case xi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case xi.RESUME:this.handleDisconnect(wc)}}}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===or.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(jf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Vf,{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(Qo())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Zo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(Qo())return this.createSimulcastTransceiverSender(e,t,i,r);if(Zo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ii(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 Ge("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 Ge("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){ie.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===or.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Re.NEW)===Re.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 Ge?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof Ai||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ki.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(U.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 Ge("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(U.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 Ai;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof pe&&a.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):new Ai}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(U.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ye.CONNECTED)throw new Ai("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(U.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 Ge("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ge("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(U.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 pe&&r.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):r instanceof pe&&r.reason===se.LeaveRequest?r:new Ai(s)}if(this.emit(U.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!==ye.CONNECTED)throw new Ai("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(U.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=Ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield pt(DC),!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ut.Connected}catch(e){throw this.pcState=Ut.Disconnected,new pe("could not establish PC connection, ".concat(e.message),se.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new ft({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcResponse",value:new qd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,ae.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new ft({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcAck",value:new Wd({requestId:t})}});yield this.sendDataPacket(i,ae.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(U.Closing,r);!this.dcBufferStatus.get(e);)yield pt(10);this.off(U.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 Ge("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new pe("".concat(o," connection not set"),se.InternalError);let c=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(t,r);if((l==null?void 0:l.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 pt(50)}throw new pe("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),se.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!==Re.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 Wo("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(U.Closing,r),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();KS(c)&&a.set(o.payload,c)}),this.emit(U.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Wo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(s)}finally{this.off(U.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===ae.LOSSY)return this.lossyDCSub;if(e===ae.RELIABLE)return this.reliableDCSub}else{if(e===ae.LOSSY)return this.lossyDC;if(e===ae.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,c=new Array,l=new Array;e.forEach(u=>{u.isDesired!==o&&c.push(u.trackSid),u.isEnabled||l.push(u.trackSid)}),this.client.sendSyncState(new uh({answer:s?Qs({sdp:s.sdp,type:s.type}):void 0,offer:a?Qs({sdp:a.sdp,type:a.type}):void 0,subscription:new Ds({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:nC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new dh({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(ae.LOSSY),Nt.PUBLISHER),t(this.dataChannelForKind(ae.RELIABLE),Nt.PUBLISHER),t(this.dataChannelForKind(ae.LOSSY,!0),Nt.SUBSCRIBER),t(this.dataChannelForKind(ae.RELIABLE,!0),Nt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Xe.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){mt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){mt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Ai extends Error{}function BC(n){return n!==void 0&&n>13}function FC(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 _c{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 tc(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),ie.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(jC(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 pe("Could not fetch region settings: ".concat(t.statusText),t.status===401?se.NotAllowed:se.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function jC(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Gf{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class VC extends Gf{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=In(this),c;c=yield o.next(),e=c.done,!e;a=!0){r=c.value,a=!1;const l=r;s.add(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class GC extends Gf{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Xs(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=In(this),c;c=yield o.next(),e=c.done,!e;a=!0)r=c.value,a=!1,s+=r}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return s})}}class zf{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 zC extends zf{}class HC extends zf{}class Hf 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?D.Muted:D.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(D.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(),kc)),iC()&&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(D.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class WC extends Hf{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=Zs(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;Jt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Jt())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(ec(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&ec(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(D.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(D.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 Ec=100;class qC extends Hf{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=Zs(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=vc(()=>{this.updateDimensions()},Ec),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?Ei(this._mediaStreamTrack,t):_i(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 KC(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,c)=>Math.max(o,c.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<Ec){Xe.setTimeout(()=>{this.updateVisibility()},Ec);return}this.lastVisible=a,this.emit(D.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,c=a.height()*s;o+c>i+r&&(i=o,r=c)}((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(D.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?df():t||(df()>2?2:1)}}class KC{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=pr(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=pr(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=pr(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Rc(e),this.isPiP=mt()&&pr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Rc(this.element),this.isPiP=pr(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ff().observe(this.element),hf().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=ff())===null||e===void 0||e.unobserve(this.element),(t=hf())===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 pr(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Rc(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Rc(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=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&&c!=="none"}class cn extends Xt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=bt.NONE,this.log=ie,this.handleMuted=()=>{this.emit(D.Muted)},this.handleUnmuted=()=>{this.emit(D.Unmuted)},this.log=sn((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Mt.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(D.Muted,this.handleMuted),this.track.off(D.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(D.Muted,this.handleMuted),e.on(D.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ue(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==bt.NONE}get audioTrack(){if(on(this.track))return this.track}get videoTrack(){if(Ii(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={}))})(cn||(cn={}));class Pc extends cn{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(D.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(D.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(D.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(on(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(At.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(At.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(At.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(At.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(At.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(At.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ia(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=Tf(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 c=gf(s,If,Of),l=uc(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(We.userMediaPromiseMap.set("audioinput",u),u.catch(()=>We.userMediaPromiseMap.delete("audioinput"))),s.video&&(We.userMediaPromiseMap.set("videoinput",u),u.catch(()=>We.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 m=f?c.audio:c.video;(typeof m=="boolean"||!m)&&(m={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&Ln(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const C=xC(h,p,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,on(C)&&i?yield C.setProcessor(i):Ii(C)&&r&&(yield C.setProcessor(r)),C})))}catch(d){if(!t)throw d;return ia(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function $C(n){return y(this,void 0,void 0,function*(){return(yield ia({audio:!1,video:n??!0}))[0]})}function YC(n){return y(this,void 0,void 0,function*(){return(yield ia({audio:n??!0,video:!1}))[0]})}var Bn;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Bn||(Bn={}));function XC(n){switch(n){case ar.EXCELLENT:return Bn.Excellent;case ar.GOOD:return Bn.Good;case ar.POOR:return Bn.Poor;case ar.LOST:return Bn.Lost;default:return Bn.Unknown}}class Wf extends Xt.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===Ls.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Si.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]:Ls.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Bn.Unknown,this.log=ie,this.log=sn((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Mt.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 sc,this.once(j.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===Si.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Si.ACTIVE&&this.emit(j.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(j.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(j.ParticipantNameChanged,e)}_setAttributes(e){const t=rC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(j.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const c=this.permissions,l=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,l&&this.emit(j.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(j.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=XC(e),t!==this._connectionQuality&&this.emit(j.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=>on(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(D.Muted,()=>{this.emit(j.TrackMuted,e)}),e.on(D.Unmuted,()=>{this.emit(j.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 JC(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 ch({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 qf=15e3;class QC extends Wf{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=bt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sc)},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(c=>this.log.warn(c.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:c,message:l}=a,u=this.pendingSignalRequests.get(o);u&&(c!==No.OK&&u.reject(new rf(l,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,l=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(l=Pe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,l);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=>JC(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),ue(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ue(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ue(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,c,l,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 m=!0,p=In(b),v;v=yield p.next(),o=v.done,!o;m=!0){u=v.value,m=!1;const C=u;DS(C)&&(this.log.debug("publish ".concat(C," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ue(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,C,f.options))}}catch(C){c={error:C}}finally{try{!m&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(c)throw c.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),ue(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Zn(a)||Dn(a))try{if(mt())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),ue(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),ue(a))),Zn(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),ue(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!==bt.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(U.RemoteMute,(t,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(U.Connected,this.handleReconnected).on(U.SignalRestarted,this.handleReconnected).on(U.SignalResumed,this.handleReconnected).on(U.Restarting,this.handleReconnecting).on(U.Resuming,this.handleReconnecting).on(U.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(U.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(U.Disconnected,this.handleDisconnected).on(U.SignalRequestResponse,this.handleSignalRequestResponse).on(U.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,c)=>y(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:m=>{c(m),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(m=>{let[p,v]=m;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),o();return}yield pt(50)}c(new rf("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&c(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(j.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?bt.GCM:bt.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 c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case I.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case I.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case I.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new an(e)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(j.MediaDevicesError,l),this.pendingPublishing.delete(e),l}try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ue(d))),l.push(this.publishTrack(d,r));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}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 c=this.getTrackPublication(I.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.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=gf(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 ia(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(on(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=I.Source.Microphone,this.emit(j.AudioStreamAcquired)),Ii(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 Ho("getDisplayMedia not supported");e.resolution===void 0&&!GS()&&(e.resolution=Jo.h1080fps30.resolution);const t=tC(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new an("no video track found");const s=new na(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(j.AudioStreamAcquired);const o=new ea(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,c,l,u;Zn(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 ea(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new na(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new an("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),ue(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;m&&(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),ue(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!zS()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,C)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ye.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ue(i)}));const w=()=>y(this,void 0,void 0,function*(){try{const T=yield this.publish(i,p,m);b(T)}catch(T){C(T)}});setTimeout(()=>{this.engine.off(U.SignalConnected,w),C(new qo("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(U.SignalConnected,w),this.engine.on(U.Closing,()=>{this.engine.off(U.SignalConnected,w),C(new qo("publishing rejected as engine closed",499))})}else try{const w=yield this.publish(i,p,m);b(w)}catch(w){C(w)}}catch(w){C(w)}}));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),ue(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>sC(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ue(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var r,s,a,o,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new qo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(k=>Pi(e)&&k.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),ue(e))),t.stopMicTrackOnMute&&on(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&Ri()&&(t.simulcast=!1),t.videoCodec==="av1"&&!FS()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!jS()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=bc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(k=>t.videoCodec===Js(k.mime))||(t.videoCodec=Js(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(D.Muted,this.onTrackMuted),e.on(D.Unmuted,this.onTrackUnmuted),e.on(D.Ended,this.handleTrackEnded),e.on(D.UpstreamPaused,this.onTrackUpstreamPaused),e.on(D.UpstreamResumed,this.onTrackUpstreamResumed),e.on(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new Ro({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 k={width:0,height:0};try{k=yield e.waitForDimensions()}catch{const _=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:ur.h720.resolution;k={width:_.width,height:_.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{dims:k}))}v.width=k.width,v.height=k.height,Dn(e)&&(dr(p)&&(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),ue(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),v.simulcastCodecs=[new Eo({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:bc}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===bt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Eo({codec:t.backupCodec.codec,cid:""})))),b=Cc(e.source===I.Source.ScreenShare,v.width,v.height,t),v.layers=Ff(v.width,v.height,b,dr(t.videoCodec))}else e.kind===I.Kind.Audio&&(b=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.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 Ge("cannot publish track when not connected");const C=()=>y(this,void 0,void 0,function*(){var k,x,_;if(!this.engine.pcManager)throw new Ge("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Dn(e)&&((k=t.degradationPreference)!==null&&k!==void 0||(t.degradationPreference=MC(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Ri()&&e.kind===I.Kind.Audio){let R;for(const O of this.engine.pcManager.publisher.getTransceivers())if(O.sender===e.sender){R=O;break}R&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:R,codec:"opus",maxbr:!((x=b[0])===null||x===void 0)&&x.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&dr(e.codec)&&(!((_=b[0])===null||_===void 0)&&_.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let w;if(this.enabledPublishVideoCodecs.length>0)w=(yield Promise.all([this.engine.addTrack(v),C()]))[0];else{w=yield this.engine.addTrack(v);let k;if(w.codecs.forEach(x=>{k===void 0&&(k=x.mimeType)}),k&&e.kind===I.Kind.Video){const x=Js(k);x!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{codec:x})),t.videoCodec=x,b=Cc(e.source===I.Source.ScreenShare,v.width,v.height,t))}yield C()}const T=new Pc(e.kind,w,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return T.options=t,e.sid=w.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:w})),Dn(e)?e.startMonitor(this.engine.client):Zn(e)&&e.startMonitor(),this.addTrackPublication(T),this.emit(j.LocalTrackPublished,T),T})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==bt.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new an("track is not published");if(!Dn(e))throw new an("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=OC(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),ue(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=new Ro({cid:c.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Ff(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Ge("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),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 l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ue(e))),yield l)}const s=this.getPublicationForTrack(e),a=s?ue(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(D.Muted,this.onTrackMuted),e.off(D.Unmuted,this.onTrackUnmuted),e.off(D.Ended,this.handleTrackEnded),e.off(D.UpstreamPaused,this.onTrackUpstreamPaused),e.off(D.UpstreamResumed,this.onTrackUpstreamResumed),e.off(D.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 c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Re.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Dn(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}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(j.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(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>y(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==I.Source.ScreenShare&&l.source!==I.Source.ScreenShareAudio&&(Zn(l)||Dn(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(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?ae.RELIABLE:ae.LOSSY,a=r.destinationIdentities,o=r.topic,c=new ft({kind:s,value:{case:"user",value:new Gd({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new ft({kind:ae.RELIABLE,value:{case:"sipDtmf",value:new zd({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ae.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 ft({value:{case:"chatMessage",value:new ko(Object.assign(Object.assign({},i),{timestamp:Se.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.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 ft({value:{case:"chatMessage",value:new ko(Object.assign(Object.assign({},i),{timestamp:Se.parse(i.timestamp),editTimestamp:Se.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.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()),c=new Array(o?o.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const m=c.reduce((p,v)=>p+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,m)},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),l(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=>{l(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:Qn(s.timestamp),totalLength:Qn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new eh({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"?So.UPDATE:So.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new ft({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,ae.RELIABLE);let l=0;const u=this,d=new WritableStream({write(m){return y(this,void 0,void 0,function*(){for(const p of ZS(m,qf)){yield u.engine.waitForBufferStatusLow(ae.RELIABLE);const v=new xo({content:p,streamId:r,chunkIndex:Qn(l)}),b=new ft({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,ae.RELIABLE),l+=1}})},close(){return y(this,void 0,void 0,function*(){const m=new wo({streamId:r}),p=new ft({destinationIdentities:o,value:{case:"streamTrailer",value:m}});yield u.engine.sendDataPacket(p,ae.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(U.Closing,h);const f=new zC(d,s,()=>this.engine.off(U.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:c}=yield a.read();if(o)break;yield s.write(c)}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(),c=e==null?void 0:e.destinationIdentities,l={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:Qn((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:Qn(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new th({name:l.name})}}),d=new ft({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,ae.RELIABLE);let h=0;const f=new dt,m=this.engine,p=this.log,v=new WritableStream({write(C){return y(this,void 0,void 0,function*(){const w=yield f.lock();let T=0;try{for(;T<C.byteLength;){const k=C.slice(T,T+qf);yield m.waitForBufferStatusLow(ae.RELIABLE);const x=new ft({destinationIdentities:c,value:{case:"streamChunk",value:new xo({content:k,streamId:o,chunkIndex:Qn(h)})}});yield m.sendDataPacket(x,ae.RELIABLE),h+=1,T+=k.byteLength}}finally{w()}})},close(){return y(this,void 0,void 0,function*(){const C=new wo({streamId:o}),w=new ft({destinationIdentities:c,value:{case:"streamTrailer",value:C}});yield m.sendDataPacket(w,ae.RELIABLE)})},abort(C){p.error("Sink error:",C)}});return new HC(v,l)})}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((l,u)=>y(i,void 0,void 0,function*(){var d,h,f,m;if(Tc(a)>Af){u(Pe.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&&Jn((m=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){u(Pe.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),u(Pe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),u(Pe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(C,w)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),w?u(w):l(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 ft({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcRequest",value:new Hd({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,ae.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,Pe.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),ue(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?(Zn(r)||Dn(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 pt(20)}})}}class ZC extends cn{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=wt.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(D.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 Ds({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $d({participantSid:"",trackSids:[this.trackSid]})]});this.emit(D.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?cn.SubscriptionStatus.Unsubscribed:super.isSubscribed?cn.SubscriptionStatus.Subscribed:cn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?cn.PermissionStatus.Allowed:cn.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||(cc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&cc(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(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(D.VisibilityChanged,this.handleVisibilityChange),r.off(D.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(D.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(D.VisibilityChanged,this.handleVisibilityChange),e.on(D.Ended,this.handleEnded),this.emit(D.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(D.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?D.Muted:D.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(D.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(D.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 cc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ih({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=wt.HIGH,this.emit(D.UpdateSettings,e)}}class ra extends Wf{static fromParticipantInfo(e,t,i){return new ra(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 c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ls.STANDARD;super(t,i||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(D.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ue(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(D.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(D.SubscriptionPermissionChanged,t=>{this.emit(j.TrackSubscriptionPermissionChanged,e,t)}),e.on(D.SubscriptionStatusChanged,t=>{this.emit(j.TrackSubscriptionStatusChanged,e,t)}),e.on(D.Subscribed,t=>{this.emit(j.TrackSubscribed,t,e)}),e.on(D.Unsubscribed,t=>{this.emit(j.TrackUnsubscribed,t,e)}),e.on(D.SubscriptionFailed,t=>{this.emit(j.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(j.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),ue(o))),this.emit(j.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new qC(e,t,r,s):l=new WC(e,t,r,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(i),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&oc(l)&&on(l)&&l.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 c=I.kindFromProto(r.type);if(!c)return;o=new ZC(c,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 l=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));l&&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:ue(l),newTrack:ue(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),ue(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(j.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(j.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;on(i.track)&&oc(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 ce;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ce||(ce={}));const e1=4*1e3;class Ni extends Xt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=ce.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ie,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,c)=>y(this,void 0,void 0,function*(){var l;if(!VS())throw Jt()?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===ce.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(ce.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),tc(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new _c(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,m,p)=>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(p??a,o,c,C),this.abortController=void 0,f()}catch(w){if(this.regionUrlProvider&&w instanceof pe&&w.reason!==se.Cancelled&&w.reason!==se.NotAllowed){let T=null;try{T=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(k){if(k instanceof pe&&(k.status===401||k.reason===se.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(k);return}}T&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(T),this.logContext),this.recreateEngine(),yield d(f,m,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,mf(w)),m(w))}else{let T=Ot.UNKNOWN_REASON;w instanceof pe&&(T=mf(w)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),m(w)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sc((f,m)=>{d(f,m,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,l,u,d)=>y(this,void 0,void 0,function*(){var h,f,m;const p=yield c.join(a,o,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},d.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[C,w]=b;return"".concat(C,": ").concat(w)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(m=p.participant)===null||m===void 0?void 0:m.identity}),!v.version)throw new _S("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),p}),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(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,l)=>y(this,void 0,void 0,function*(){var u,d;this.state===ce.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({},yc),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new pe("could not establish signal connection",se.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof pe&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new pe("Connection attempt aborted",se.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}mt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),mt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ce.Connected),this.emit(L.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return y(t,[...o],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,m;const p=yield l.disconnectLock.lock();try{if(l.state===ce.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ce.Connecting||l.state===ce.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(d=l.abortController)===null||d===void 0||d.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new pe("Client initiated disconnect",se.Cancelled)),l.connectFuture=void 0),!((m=l.engine)===null||m===void 0)&&m.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(u,Ot.CLIENT_INITIATED),l.engine=void 0}finally{p()}}()})},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=Lt();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const u=rc();u.enabled=!0;const d=new MediaStream([u]);l.srcObject=d,document.addEventListener("visibilitychange",()=>{l&&(l.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(l),this.once(L.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.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(ce.Reconnecting)&&this.emit(L.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(ce.Connected),this.emit(L.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(o.identity);o.state===Si.DISCONNECTED?this.handleParticipantDisconnected(o.identity,l):l=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),o.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(L.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||o.set(l.sid,l)}),a.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?o.set(l.sid,u):o.delete(l.sid))});const c=Array.from(o.values());c.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(L.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);if(!l||!l.track)return;const u=I.streamStateFromProto(o.state);u!==l.track.streamState&&(l.track.streamState=u,c.emit(j.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(L.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.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 c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(L.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(j.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(L.SipDTMFReceived,o,a),a==null||a.emit(j.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(o.trackId),u=YS(o,this.transcriptionReceivedTimes);l==null||l.emit(D.TranscriptionReceived,u),c==null||c.emit(j.TranscriptionReceived,u,l),this.emit(L.TranscriptionReceived,u,c,l)},this.handleChatMessage=(a,o)=>{const c=XS(o);this.emit(L.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(L.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(L.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(L.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(L.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(L.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,c;const l=We.getInstance().previousDevices,u=yield We.getInstance().getDevices(void 0,!1),d=Lt();if((d==null?void 0:d.name)==="Chrome"&&d.os!=="iOS")for(let f of u){const m=l.find(p=>p.deviceId===f.deviceId);m&&m.label!==""&&m.kind===f.kind&&m.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(L.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const m=eC(f),p=this.localParticipant.getTrackPublication(m);if(p&&(!((a=p.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(C=>C.kind===f),b=this.getActiveDevice(f);if(b===((o=l.filter(C=>C.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((c=v[0])===null||c===void 0?void 0:c.deviceId)!==b){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Mn()||f==="videoinput"||v.length>0&&!v.find(C=>C.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(L.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(L.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(L.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(L.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(L.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(L.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(L.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(L.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,c,l,u,d,h;(o=a.track)===null||o===void 0||o.on(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(D.Restarted,this.onLocalTrackRestarted),(d=(u=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(L.LocalTrackPublished,a,this.localParticipant),Zn(a.track)&&(yield a.track.checkForSilence())&&this.emit(L.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),m=yf(a.source);m&&f&&f!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,f),this.emit(L.ActiveDeviceChanged,m,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(D.Restarted,this.onLocalTrackRestarted),this.emit(L.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=yf(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(L.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(L.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(L.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(L.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(L.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},kC),e),this.log=sn((i=this.options.loggerName)!==null&&i!==void 0?i:Mt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},If),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Of),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},TC),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new dt,this.localParticipant=new QC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ln(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ln(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Ln(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),mt()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Ni.cleanupRegistry&&Ni.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,Pe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,Pe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});Tc(u)>Af?(c=Pe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof Pe?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=Pe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}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 aC(this.options.e2ee),this.e2eeManager.on(An.ParticipantEncryptionStatusChanged,(t,i)=>{QS(i)&&(this.isE2EEEnabled=t),this.emit(L.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(An.EncryptionError,t=>this.emit(L.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return y(this,void 0,void 0,function*(){return this.state===ce.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(U.RoomUpdate,i),e(r.sid))};this.engine.on(U.RoomUpdate,i),this.once(L.Disconnected,()=>{this.engine.off(U.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 UC(this.options),this.engine.on(U.ParticipantUpdate,this.handleParticipantUpdates).on(U.RoomUpdate,this.handleRoomUpdate).on(U.SpeakersChanged,this.handleSpeakersChanged).on(U.StreamStateChanged,this.handleStreamStateUpdate).on(U.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(U.SubscriptionError,this.handleSubscriptionError).on(U.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(U.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(U.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(U.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(U.DataPacketReceived,this.handleDataPacket).on(U.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ce.SignalReconnecting)&&this.emit(L.SignalReconnecting)}).on(U.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ce.Connected)&&this.emit(L.Reconnected)}).on(U.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ce.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(U.Restarting,this.handleRestarting).on(U.SignalRestarted,this.handleSignalRestarted).on(U.Offline,()=>{this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(L.Reconnecting)}).on(U.DCBufferStatusChanged,(e,t)=>{this.emit(L.DCBufferStatusChanged,e,t)}).on(U.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(j.LocalTrackSubscribed,t),this.emitWhenConnected(L.LocalTrackSubscribed,t,this.localParticipant)}).on(U.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(L.Moved,e.room.name,e.token),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return We.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ce.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(tc(new URL(e))&&t){this.regionUrlProvider=new _c(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ce.Disconnected&&(this.regionUrl=i,yield fetch(ac(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(ac(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 Yt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Yt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Yt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Yt({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 Yt({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 Yt({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 Yt({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 Us({reason:Ot.CLIENT_INITIATED,action:xi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Yt({scenario:{case:"subscriberBandwidth",value:Qn(t)}});break;case"leave-full-reconnect":r=new Yt({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,c,l,u,d,h,f,m;let p=!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 w=Array.from(s.localParticipant.audioTrackPublications.values()).filter(T=>T.source===I.Source.Microphone);try{p=(yield Promise.all(w.map(T=>{var k;return(k=T.audioTrack)===null||k===void 0?void 0:k.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=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const w=Array.from(s.localParticipant.videoTrackPublications.values()).filter(T=>T.source===I.Source.Camera);try{p=(yield Promise.all(w.map(T=>{var k;return(k=T.videoTrack)===null||k===void 0?void 0:k.setDeviceId(b)}))).every(T=>T===!0)}catch(T){throw s.options.videoCaptureDefaults.deviceId=C,T}}else if(i==="audiooutput"){if(!ec()&&!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=(l=yield We.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(m=s.options).audioOutput)!==null&&u!==void 0||(m.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(w=>w.setAudioOutput({deviceId:r})))}catch(w){throw s.options.audioOutput.deviceId=C,w}}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(L.ActiveDeviceChanged,i,r)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(j.AttributesChanged,this.onLocalAttributesChanged).on(j.TrackMuted,this.onLocalTrackMuted).on(j.TrackUnmuted,this.onLocalTrackUnmuted).on(j.LocalTrackPublished,this.onLocalTrackPublished).on(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(j.MediaDevicesError,this.onMediaDevicesError).on(j.AudioStreamAcquired,this.startAudio).on(j.ChatMessage,this.onLocalChatMessageSent).on(j.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===ce.Connecting||this.state===ce.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(L.Reconnected,u),this.off(L.Connected,u),this.off(L.Disconnected,d)};this.once(L.Reconnected,u),this.once(L.Connected,u),this.once(L.Disconnected,d);return}if(this.state===ce.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=BS(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 c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,o,t,i,l)}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!==ce.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(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(j.AttributesChanged,this.onLocalAttributesChanged).off(j.TrackMuted,this.onLocalTrackMuted).off(j.TrackUnmuted,this.onLocalTrackUnmuted).off(j.LocalTrackPublished,this.onLocalTrackPublished).off(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(j.MediaDevicesError,this.onMediaDevicesError).off(j.AudioStreamAcquired,this.startAudio).off(j.ChatMessage,this.onLocalChatMessageSent).off(j.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),mt()&&(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(ce.Disconnected),this.emit(L.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(L.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:Xs(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new VC(a,o,Xs(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:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new GC(a,o,Xs(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=bf())!==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(),pt(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(L.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=ra.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new ra(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(L.ParticipantConnected,i),i.on(j.TrackPublished,r=>{this.emitWhenConnected(L.TrackPublished,r,i)}).on(j.TrackSubscribed,(r,s)=>{r.kind===I.Kind.Audio?(r.on(D.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(D.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===I.Kind.Video&&(r.on(D.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(D.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(L.TrackSubscribed,r,s,i)}).on(j.TrackUnpublished,r=>{this.emit(L.TrackUnpublished,r,i)}).on(j.TrackUnsubscribed,(r,s)=>{this.emit(L.TrackUnsubscribed,r,s,i)}).on(j.TrackMuted,r=>{this.emitWhenConnected(L.TrackMuted,r,i)}).on(j.TrackUnmuted,r=>{this.emitWhenConnected(L.TrackUnmuted,r,i)}).on(j.ParticipantMetadataChanged,r=>{this.emitWhenConnected(L.ParticipantMetadataChanged,r,i)}).on(j.ParticipantNameChanged,r=>{this.emitWhenConnected(L.ParticipantNameChanged,r,i)}).on(j.AttributesChanged,r=>{this.emitWhenConnected(L.ParticipantAttributesChanged,r,i)}).on(j.ConnectionQualityChanged,r=>{this.emitWhenConnected(L.ConnectionQualityChanged,r,i)}).on(j.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(L.ParticipantPermissionsChanged,r,i)}).on(j.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(L.TrackSubscriptionStatusChanged,r,s,i)}).on(j.TrackSubscriptionFailed,(r,s)=>{this.emit(L.TrackSubscriptionFailed,r,i,s)}).on(j.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(L.TrackSubscriptionPermissionChanged,r,s,i)}).on(j.Active,()=>{this.emitWhenConnected(L.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&&JS(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=Xe.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,Ot.STATE_MISMATCH))):e=0},e1)}clearConnectionReconcile(){this.connectionReconcileInterval&&Xe.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(L.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,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===ce.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ce.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 Ns({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Se.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected),this.emit(L.Connected),this.setAndEmitConnectionState(ce.Connected),r.video){const a=new Pc(I.Kind.Video,new Ci({source:je.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO,name:"video-dummy"}),new na(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:pf(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(j.LocalTrackPublished,a)}if(r.audio){const a=new Pc(I.Kind.Audio,new Ci({source:je.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO}),new ea(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rc(),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(j.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Kn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Si.ACTIVE,tracks:[],joinedAt:Se.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(s.video){const l=pf(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Ci({source:je.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const l=rc(),u=new Ci({source:je.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}c.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!==L.ActiveSpeakersChanged&&e!==L.TranscriptionReceived){const s=Kf(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)}}Ni.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Kf(n){return n.map(e=>{if(e)return Array.isArray(e)?Kf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Bt;(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"})(Bt||(Bt={}));class Fn extends Xt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Bt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ni(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==Bt.IDLE)throw Error("check is running already");this.setStatus(Bt.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!==Bt.SKIPPED&&this.setStatus(this.isSuccess()?Bt.SUCCESS:Bt.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===ce.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!==ce.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Bt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(L.Reconnecting,()=>{t=!0}),this.room.once(L.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 pt(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 t1 extends Fn{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new _c(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,c=1e6/a,l="A".repeat(a),u=Date.now();for(let m=0;m<c;m++)yield s.write(l);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(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Ic=1e4;class n1 extends Fn{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/(Ic/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Ic/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],l=(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 l.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,Ic)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class i1 extends Fn{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield YC();if(yield vf(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 r1 extends Fn{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield $C();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,c;const l=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=(c=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),i.remove()})}}class s1 extends Fn{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(l=>{setTimeout(l,5e3),s=l}),o=()=>{i=!0};t.on(L.SignalReconnecting,o).on(L.Reconnecting,o).on(L.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!r||t.state!==ce.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 a1 extends Fn{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new hc,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 c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(a=!0,o=!0):l.startsWith("turns:")&&(a=!0,o=!0,s=!0),l.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(c=>setTimeout(c,0)))})}}class o1 extends Fn{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(L.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&&(c1(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(),ie.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 c1(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 l1 extends Fn{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 hc;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)===Yd.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 S_ extends Xt.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:Bt.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!==Bt.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(l1)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(o1)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(a1)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(s1)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(i1)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(r1)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(n1);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(t1)})}}const u1=/\{[^{}]+\}/g;function d1(){return Math.random().toString(36).slice(2,11)}function h1(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=Jf(e);const c=[];async function l(u,d){const{baseUrl:h,fetch:f=i,Request:m=t,headers:p,params:v={},parseAs:b="json",querySerializer:C,bodySerializer:w=s??p1,body:T,...k}=d||{};h&&(e=Jf(h));let x=typeof r=="function"?r:Xf(r);C&&(x=typeof C=="function"?C:Xf({...typeof r=="object"?r:{},...C}));const _=T===void 0?void 0:w(T),R=_===void 0||_ instanceof FormData?{}:{"Content-Type":"application/json"},O={redirect:"follow",...o,...k,body:_,headers:g1(R,a,p,v.header)};let B,N,W=new t(m1(u,{baseUrl:e,params:v,querySerializer:x}),O);for(const Q in k)Q in W||(W[Q]=k[Q]);if(c.length){B=d1(),N=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:x,bodySerializer:w});for(const Q of c)if(Q&&typeof Q=="object"&&typeof Q.onRequest=="function"){const X=await Q.onRequest({request:W,schemaPath:u,params:v,options:N,id:B});if(X){if(!(X instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");W=X}}}let K=await f(W);if(c.length)for(let Q=c.length-1;Q>=0;Q--){const X=c[Q];if(X&&typeof X=="object"&&typeof X.onResponse=="function"){const Te=await X.onResponse({request:W,response:K,schemaPath:u,params:v,options:N,id:B});if(Te){if(!(Te instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");K=Te}}}if(K.status===204||K.headers.get("Content-Length")==="0")return K.ok?{data:{},response:K}:{error:{},response:K};if(K.ok)return b==="stream"?{data:K.body,response:K}:{data:await K[b](),response:K};let M=await K.text();try{M=JSON.parse(M)}catch{}return{error:M,response:K}}return{GET(u,d){return l(u,{...d,method:"GET"})},PUT(u,d){return l(u,{...d,method:"PUT"})},POST(u,d){return l(u,{...d,method:"POST"})},DELETE(u,d){return l(u,{...d,method:"DELETE"})},OPTIONS(u,d){return l(u,{...d,method:"OPTIONS"})},HEAD(u,d){return l(u,{...d,method:"HEAD"})},PATCH(u,d){return l(u,{...d,method:"PATCH"})},TRACE(u,d){return l(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()`");c.push(d)}},eject(...u){for(const d of u){const h=c.indexOf(d);h!==-1&&c.splice(h,1)}}}}function sa(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 $f(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(sa(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function Yf(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(sa(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Xf(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(Yf(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($f(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(sa(r,s,n))}}return i.join("&")}}function f1(n,e){let t=n;for(const i of n.match(u1)??[]){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,Yf(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,$f(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${sa(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function p1(n){return n instanceof FormData?n:JSON.stringify(n)}function m1(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=f1(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function g1(...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 Jf(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Qf="Onboardee-Session-Token",Zf="OnboardeeSessionToken";class ep{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=h1({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest:({request:t})=>{if(this.trackOnboardeeToken&&window.localStorage){const i=window.localStorage.getItem(Zf);i&&t.headers.set(Qf,i)}return t},onResponse:({response:t})=>{if(this.trackOnboardeeToken){const i=t.headers.get(Qf);i&&window.localStorage&&window.localStorage.setItem(Zf,i)}return t}})}setTrackOnboardeeToken(e){this.trackOnboardeeToken=e}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 tp="https://app.coragents.ai";class aa extends Ia{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 ep({baseUrl:tp}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new Ni(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}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(L.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(L.TrackSubscribed,i=>{if(console.info("[obi] track subscribed kind=",i.kind,"source=",i.source),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(L.LocalTrackPublished,i=>{if(console.info("[obi] local track published kind=",i.kind,"source=",i.source),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(L.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(L.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),e&&(this.isPaused,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isPaused,this.isPaused&&this.muteMicrophone()),t){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?this.speakingStateChanged("speaking"):this.speakingStateChanged("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 l=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",l),!1}console.log("[obi] requesting audio track via getUserMedia"),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});const t=this.publishedAudioStream.getAudioTracks().map(l=>{var u,d;return{id:l.id,label:l.label,enabled:l.enabled,muted:l.muted,readyState:l.readyState,constraints:(u=l.getConstraints)==null?void 0:u.call(l),settings:(d=l.getSettings)==null?void 0:d.call(l)}});console.log("[obi] getUserMedia resolved",t);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const l=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",l),!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:c}=this.createFFT(this.publishedAudioStream);this.userAnalyser=o,this.userAudioContext=c,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,c=Math.pow(a/s,1/o);for(let l=0;l<o;l++){const u=s*Math.pow(c,l),d=s*Math.pow(c,l+1),h=Math.floor(u/i),f=Math.floor(d/i),m=Math.min(f,this.frequencyDataBuffer.length),p=Math.min(h,m);if(p<m){let v=0;for(let C=p;C<m;C++)v+=this.frequencyDataBuffer[C];const b=v/(m-p)/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 aa(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 oa extends Ia{constructor(e,t,i={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.engagement=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 ep({baseUrl:i.apiBaseUrl||tp}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new aa(r,s,a,o)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var t,i,r,s,a,o,c;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const l=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});this.identity=e.identity||null,this.product=((t=l.data)==null?void 0:t.product)||null,this.plans=((i=l.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=l.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((s=l.data)==null?void 0:s.plan_is_completed)||[],this.showWidget=((a=l.data)==null?void 0:a.show_widget)||!1,this.engagement=((o=l.data)==null?void 0:o.engagement)||null;const u=((c=this.product)==null?void 0:c.track_onboardee_token)??!0;if(this.api.setTrackOnboardeeToken(u),e.planUuid){let d=null;try{const h=await this.api.getPlanSDK(e.planUuid);if(h.error)throw new Error(`Plan not found: ${h.error}`);h.data&&(d=h.data)}catch(h){try{const f=await this.api.getSessionPlan(e.planUuid);if(f.error)throw new Error(`Session plan not found: ${f.error}`);f.data&&(d=f.data)}catch(f){console.error("[obi] error getting plan via both endpoints",{planErr:h,sessionErr:f})}}d?(this.selectedPlan=d,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(l){throw this.error=l instanceof Error?l:new Error(String(l)),this.setState("error"),l}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 c;return o.uuid===((c=this.selectedPlan)==null?void 0:c.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,engagement:this.engagement,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 oa(t,i,r);return a.state=s.state,a.identity=s.identity||null,a.product=s.product||null,a.engagement=s.engagement||null,a.plans=s.plans||[],a.selectedPlan=s.selectedPlan||null,a.selectedPlanUuid=s.selectedPlanUuid||null,a.showWidget=s.showWidget||!1,s.session&&(a.session=aa.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 ca,Z,np,ei,ip,rp,sp,ap,Oc,Ac,Nc,op,mr={},cp=[],v1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,gr=Array.isArray;function ln(n,e){for(var t in e)n[t]=e[t];return n}function Mc(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Lc(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?ca.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return la(n,a,i,r,null)}function la(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??++np,__i:-1,__u:0};return r==null&&Z.vnode!=null&&Z.vnode(s),s}function nt(n){return n.children}function un(n,e){this.props=n,this.context=e}function Mi(n,e){if(e==null)return n.__?Mi(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"?Mi(n):null}function lp(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 lp(n)}}function Dc(n){(!n.__d&&(n.__d=!0)&&ei.push(n)&&!ua.__r++||ip!=Z.debounceRendering)&&((ip=Z.debounceRendering)||rp)(ua)}function ua(){for(var n,e,t,i,r,s,a,o=1;ei.length;)ei.length>o&&ei.sort(sp),n=ei.shift(),o=ei.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=ln({},i)).__v=i.__v+1,Z.vnode&&Z.vnode(t),Uc(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??Mi(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,pp(s,t,a),t.__e!=r&&lp(t)));ua.__r=0}function up(n,e,t,i,r,s,a,o,c,l,u){var d,h,f,m,p,v,b=i&&i.__k||cp,C=e.length;for(c=b1(t,e,b,c,C),d=0;d<C;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?mr:b[f.__i]||mr,f.__i=d,v=Uc(n,f,h,r,s,a,o,c,l,u),m=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Bc(h.ref,null,f),u.push(f.ref,f.__c||m,f)),p==null&&m!=null&&(p=m),4&f.__u||h.__k===f.__k?c=dp(f,c,n):typeof f.type=="function"&&v!==void 0?c=v:m&&(c=m.nextSibling),f.__u&=-7);return t.__e=p,c}function b1(n,e,t,i,r){var s,a,o,c,l,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"?(c=s+h,(a=n.__k[s]=typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?la(null,a,null,null,null):gr(a)?la(nt,{children:a},null,null,null):a.constructor==null&&a.__b>0?la(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=n,a.__b=n.__b+1,o=null,(l=a.__i=y1(a,t,c,d))!=-1&&(d--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(r>u?h--:r<u&&h++),typeof a.type!="function"&&(a.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?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=Mi(o)),gp(o,o));return i}function dp(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=dp(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Mi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function da(n,e){return e=e||[],n==null||typeof n=="boolean"||(gr(n)?n.some(function(t){da(t,e)}):e.push(n)),e}function y1(n,e,t,i){var r,s,a=n.key,o=n.type,c=e[t];if(c===null&&n.key==null||c&&a==c.key&&o==c.type&&!(2&c.__u))return t;if(i>(c!=null&&!(2&c.__u)?1:0))for(r=t-1,s=t+1;r>=0||s<e.length;){if(r>=0){if((c=e[r])&&!(2&c.__u)&&a==c.key&&o==c.type)return r;r--}if(s<e.length){if((c=e[s])&&!(2&c.__u)&&a==c.key&&o==c.type)return s;s++}}return-1}function hp(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||v1.test(e)?t:t+"px"}function ha(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||hp(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||hp(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(ap,"$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=Oc,n.addEventListener(e,s?Nc:Ac,s)):n.removeEventListener(e,s?Nc:Ac,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 fp(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=Oc++;else if(e.t<t.u)return;return t(Z.event?Z.event(e):e)}}}function Uc(n,e,t,i,r,s,a,o,c,l){var u,d,h,f,m,p,v,b,C,w,T,k,x,_,R,O,B,N=e.type;if(e.constructor!=null)return null;128&t.__u&&(c=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=Z.__b)&&u(e);e:if(typeof N=="function")try{if(b=e.props,C="prototype"in N&&N.prototype.render,w=(u=N.contextType)&&i[u.__c],T=u?w?w.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 un(b,T),d.constructor=N,d.render=k1),w&&w.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=ln({},d.__s)),ln(d.__s,N.getDerivedStateFromProps(b,d.__s))),f=d.props,m=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(W){W&&(W.__=e)}),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);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,m,p)})}if(d.context=T,d.props=b,d.__P=n,d.__e=!1,x=Z.__r,_=0,C){for(d.state=d.__s,d.__d=!1,x&&x(e),u=d.render(d.props,d.state,d.context),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[]}else do d.__d=!1,x&&x(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++_<25);d.state=d.__s,d.getChildContext!=null&&(i=ln(ln({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(p=d.getSnapshotBeforeUpdate(f,m)),O=u,u!=null&&u.type===nt&&u.key==null&&(O=mp(u.props.children)),o=up(n,gr(O)?O:[O],e,t,i,r,s,a,o,c,l),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),v&&(d.__E=d.__=null)}catch(W){if(e.__v=null,c||s!=null)if(W.then){for(e.__u|=c?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--;)Mc(s[B]);else e.__e=t.__e,e.__k=t.__k;Z.__e(W,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=T1(t.__e,e,t,i,r,s,a,c,l);return(u=Z.diffed)&&u(e),128&e.__u?void 0:o}function pp(n,e,t){for(var i=0;i<t.length;i++)Bc(t[i],t[++i],t[++i]);Z.__c&&Z.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){Z.__e(s,r.__v)}})}function mp(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:gr(n)?n.map(mp):ln({},n)}function T1(n,e,t,i,r,s,a,o,c){var l,u,d,h,f,m,p,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(l=0;l<s.length;l++)if((f=s[l])&&"setAttribute"in f==!!C&&(C?f.localName==C:f.nodeType==3)){n=f,s[l]=null;break}}if(n==null){if(C==null)return document.createTextNode(b);n=document.createElementNS(r,C,b.is&&b),o&&(Z.__m&&Z.__m(e,s),o=!1),s=null}if(C==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&ca.call(n.childNodes),v=t.props||mr,!o&&s!=null)for(v={},l=0;l<n.attributes.length;l++)v[(f=n.attributes[l]).name]=f.value;for(l in v)if(f=v[l],l!="children"){if(l=="dangerouslySetInnerHTML")d=f;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;ha(n,l,null,f,r)}}for(l in b)f=b[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?u=f:l=="value"?m=f:l=="checked"?p=f:o&&typeof f!="function"||v[l]===f||ha(n,l,f,v[l],r);if(u)o||d&&(u.__html==d.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(d&&(n.innerHTML=""),up(e.type=="template"?n.content:n,gr(h)?h:[h],e,t,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&Mi(t,0),o,c),s!=null)for(l=s.length;l--;)Mc(s[l]);o||(l="value",C=="progress"&&m==null?n.removeAttribute("value"):m!=null&&(m!==n[l]||C=="progress"&&!m||C=="option"&&m!=v[l])&&ha(n,l,m,v[l],r),l="checked",p!=null&&p!=n[l]&&ha(n,l,p,v[l],r))}return n}function Bc(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){Z.__e(r,t)}}function gp(n,e,t){var i,r;if(Z.unmount&&Z.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||Bc(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){Z.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&gp(i[r],e,t||typeof n.type!="function");t||Mc(n.__e),n.__c=n.__=n.__e=void 0}function k1(n,e,t){return this.constructor(n,t)}function S1(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),Z.__&&Z.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Uc(e,n=(!i&&t||e).__k=Lc(nt,null,[n]),r||mr,mr,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?ca.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),pp(s,n,a)}function C1(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,Dc(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"+op++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}ca=cp.slice,Z={__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}},np=0,un.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ln({},this.state),typeof n=="function"&&(n=n(ln({},t),this.props)),n&&ln(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Dc(this))},un.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Dc(this))},un.prototype.render=nt,ei=[],rp=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,sp=function(n,e){return n.__v.__b-e.__v.__b},ua.__r=0,ap=/(PointerCapture)$|Capture$/i,Oc=0,Ac=fp(!1),Nc=fp(!0),op=0;var x1=0;function g(n,e,t,i,r,s){e||(e={});var a,o,c=e;if("ref"in c)for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var l={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--x1,__i:-1,__u:0,__source:r,__self:s};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)c[o]===void 0&&(c[o]=a[o]);return Z.vnode&&Z.vnode(l),l}var ti,Ce,Fc,vp,vr=0,bp=[],Le=Z,yp=Le.__b,Tp=Le.__r,kp=Le.diffed,Sp=Le.__c,Cp=Le.unmount,xp=Le.__;function br(n,e){Le.__h&&Le.__h(Ce,n,vr||e),vr=0;var t=Ce.__H||(Ce.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function Y(n){return vr=1,w1(Ep,n)}function w1(n,e,t){var i=br(ti++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):Ep(void 0,e),function(o){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,o);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=Ce,!Ce.__f)){var r=function(o,c,l){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,c,l);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,c,l)||d};Ce.__f=!0;var s=Ce.shouldComponentUpdate,a=Ce.componentWillUpdate;Ce.componentWillUpdate=function(o,c,l){if(this.__e){var u=s;s=void 0,r(o,c,l),s=u}a&&a.call(this,o,c,l)},Ce.shouldComponentUpdate=r}return i.__N||i.__}function Je(n,e){var t=br(ti++,3);!Le.__s&&Vc(t.__H,e)&&(t.__=n,t.u=e,Ce.__H.__h.push(t))}function yr(n,e){var t=br(ti++,4);!Le.__s&&Vc(t.__H,e)&&(t.__=n,t.u=e,Ce.__h.push(t))}function Ie(n){return vr=5,fa(function(){return{current:n}},[])}function fa(n,e){var t=br(ti++,7);return Vc(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function _1(n,e){return vr=8,fa(function(){return n},e)}function wp(n){var e=Ce.context[n.__c],t=br(ti++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ce)),e.props.value):n.__}function E1(){for(var n;n=bp.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(pa),n.__H.__h.forEach(jc),n.__H.__h=[]}catch(e){n.__H.__h=[],Le.__e(e,n.__v)}}Le.__b=function(n){Ce=null,yp&&yp(n)},Le.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),xp&&xp(n,e)},Le.__r=function(n){Tp&&Tp(n),ti=0;var e=(Ce=n.__c).__H;e&&(Fc===Ce?(e.__h=[],Ce.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(pa),e.__h.forEach(jc),e.__h=[],ti=0)),Fc=Ce},Le.diffed=function(n){kp&&kp(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(bp.push(e)!==1&&vp===Le.requestAnimationFrame||((vp=Le.requestAnimationFrame)||R1)(E1)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Fc=Ce=null},Le.__c=function(n,e){e.some(function(t){try{t.__h.forEach(pa),t.__h=t.__h.filter(function(i){return!i.__||jc(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],Le.__e(i,t.__v)}}),Sp&&Sp(n,e)},Le.unmount=function(n){Cp&&Cp(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{pa(i)}catch(r){e=r}}),t.__H=void 0,e&&Le.__e(e,t.__v))};var _p=typeof requestAnimationFrame=="function";function R1(n){var e,t=function(){clearTimeout(i),_p&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);_p&&(e=requestAnimationFrame(t))}function pa(n){var e=Ce,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ce=e}function jc(n){var e=Ce;n.__c=n.__(),Ce=e}function Vc(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function Ep(n,e){return typeof e=="function"?e(n):e}function P1({size:n=24,color:e="#000"}){return g("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:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]})}function Rp({onClose:n}){return g("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",style:"outline: none !important;",autoFocus:!1,children:g(P1,{})})}function Pp({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Ie(null),a=Ie(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())},c=u=>{u.preventDefault(),a.current||(a.current="user-initiated");const d=a.current;a.current=null,t==null||t(d)},l=()=>{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",c),()=>{u.removeEventListener("click",o),u.removeEventListener("close",c)}},[t]),g("dialog",{ref:s,className:`modal-${i}`,children:[g(Rp,{onClose:l}),g("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Gc({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"),g("div",{className:o,onMouseEnter:r,onMouseLeave:s,children:g("div",{className:`obi-pill pill ${n}`,onClick:i,children:a})})}function I1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function O1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}const Ip=8,ma=8,A1=100,N1=.7,Li=3;function Op({getBands:n,color:e="white"}){const t=Ie(null);return Je(()=>{if(!n)return;let i=0,r;const s=a=>{try{if(a-i>=A1){const o=n();if(t.current){const c=t.current.querySelectorAll(".bar"),l=o&&o.length>0?o.slice(0,ma).map(u=>{const d=Math.abs(u);return Math.min(d/N1*Ip,Ip)||Li}):Array(ma).fill(Li);for(;l.length<ma;)l.push(Li);l.forEach((u,d)=>{if(u<Li&&(u=Li),c[d]){const h=u*2;c[d].style.height=`${h}px`,c[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]),g("div",{className:"obi-equaliser",ref:t,children:Array.from({length:ma},(i,r)=>g("div",{className:"column",children:g("div",{className:"bar",style:{height:`${Li}px`,backgroundColor:e,display:"block"}})},r))})}function M1(n){const{spectrum:e}=n;return g(Gc,{isActive:!0,children:g(Op,{getBands:e})})}function zc(n){const{children:e,className:t="",...i}=n;return g("div",{className:`${t} obi-panel`,...i,children:e})}function ni({type:n,size:e=24}){return g("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:L1(n)})}function L1(n){switch(n){case"pause":return g(nt,{children:[g("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),g("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return g(nt,{children:g("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return g(nt,{children:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]});case"message":return g(nt,{children:g("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return g(nt,{children:[g("path",{d:"m14 10 7-7"}),g("path",{d:"M20 10h-6V4"}),g("path",{d:"m3 21 7-7"}),g("path",{d:"M4 14h6v6"})]});case"voice":return g(nt,{children:[g("path",{d:"M2 10v3"}),g("path",{d:"M6 6v11"}),g("path",{d:"M10 3v18"}),g("path",{d:"M14 8v7"}),g("path",{d:"M18 5v13"}),g("path",{d:"M22 10v3"})]});case"open":return g(nt,{children:[g("path",{d:"M12 7v14"}),g("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const Hc=C1(null);function D1({children:n}){const e=wp(Hc);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:c,delayMs:l}=e,u=Ie(null),d=Ap(a,s),[h,f]=Y(!1);Je(()=>{t!==void 0&&t!==h&&(t?p():v()),f(t)},[t]),Je(()=>()=>{u.current&&clearTimeout(u.current)},[]);function m(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){m(),l>0?u.current=setTimeout(()=>{c==null||c(!0),r(!0),u.current=null},l):(c==null||c(!0),r(!0))}function v(){m(),c==null||c(!1),r(!1)}const b=()=>{o==="click"&&(i?v():p())};function C(){o==="hover"&&p()}function w(){o==="hover"&&v()}return g("div",{ref:d,class:"target",onClick:b,onMouseEnter:C,onMouseLeave:w,children:n})}function U1({children:n}){const e=wp(Hc);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=Ap(a,r);return yr(()=>{if(t&&!i&&s.current&&a.current){const c=a.current;if(!c)return;const l=s.current;if(!l)return;const u=c.getBoundingClientRect(),d=l.getBoundingClientRect(),h=d.right-d.left;c.style.top=`${u.top-u.bottom-(8+e.offset)}px`,c.style.left=`${-(u.right-u.left-h)/2}px`}},[t,i]),t?g("div",{ref:o,class:"content",style:{opacity:i?0:1},children:n}):null}function gt({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,c]=Y(!1),[l,u]=Y(!1),d=Ie(null),h=Ie(null),f={controlledOpen:e,isOpen:o,setIsOpen:c,animating:l,setAnimating:u,targetRef:d,contentRef:h,trigger:n,onChange:t,delayMs:r,offset:s};return g(Hc.Provider,{value:f,children:g("div",{class:`obi-popout ${a}`,children:i})})}gt.Target=D1,gt.Content=U1;function Ap(n,e){const t=Ie(null),i=Ie(null),r=Ie(!0),s=_1(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 Ft({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:g(ni,{type:"close",size:16}),pause:g(ni,{type:"pause",size:16}),play:g(ni,{type:"play",size:16}),message:g(ni,{type:"message",size:16}),minimize:g(ni,{type:"minimize",size:16}),voice:g(ni,{type:"voice",size:16}),open:g(ni,{type:"open",size:16})}[t],a={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=g("button",{class:`obi-button obi-round-button ${a} ${n}`,onClick:i?void 0:e,disabled:i,children:s});return r?g(gt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[g(gt.Target,{children:o}),g(gt.Content,{children:g("div",{className:"obi-round-button-title",children:r})})]}):o}function dn({className:n,children:e,onClick:t}){return t?g("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):g("div",{class:`obi-message ${n}`,children:e})}const B1=8;function F1({color:n="white"}){return g("div",{className:"obi-loading-dots",children:Array.from({length:B1},(e,t)=>g("div",{className:"column",children:[g("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),g("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function j1({onContinue:n,onWrapUp:e}){return g(zc,{className:"obi-exit-survey",children:g(G1,{onContinue:n,onWrapUp:()=>{e()}})})}function V1({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=Y("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return g(zc,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?g(z1,{onReasonSelect:s}):g(H1,{onReasonSelect:s,onClose:t})})}function G1({onContinue:n,onWrapUp:e}){return g("div",{className:"obi-exit-survey-container",children:[g("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),g("div",{className:"obi-exit-survey-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function z1({onReasonSelect:n}){return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),g("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"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function H1({onReasonSelect:n,onClose:e}){const[t,i]=Y("");return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:[g(Rp,{onClose:e}),g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:r=>i(r.target.value)}),g("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 W1(n,e){for(var t in e)n[t]=e[t];return n}function Np(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 Mp(n,e){this.props=n,this.context=e}(Mp.prototype=new un).isPureReactComponent=!0,Mp.prototype.shouldComponentUpdate=function(n,e){return Np(this.props,n)||Np(this.state,e)};var Lp=Z.__b;Z.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Lp&&Lp(n)};var q1=Z.__e;Z.__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)}q1(n,e,t,i)};var Dp=Z.unmount;function Up(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=W1({},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 Up(i,e,t)})),n}function Bp(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Bp(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 Wc(){this.__u=0,this.o=null,this.__b=null}function Fp(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function ga(){this.i=null,this.l=null}Z.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Dp&&Dp(n)},(Wc.prototype=new un).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=Fp(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 c=i.state.__a;i.__v.__k[0]=Bp(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),n.then(a,a)},Wc.prototype.componentWillUnmount=function(){this.o=[]},Wc.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]=Up(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&Lc(nt,null,n.fallback);return r&&(r.__u&=-33),[Lc(nt,null,e.__a?null:n.children),r]};var jp=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]}};(ga.prototype=new un).__a=function(n){var e=this,t=Fp(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),jp(e,n,i)):r()};t?t(s):s()}},ga.prototype.render=function(n){this.i=null,this.l=new Map;var e=da(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},ga.prototype.componentDidUpdate=ga.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){jp(n,t,e)})};var K1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,$1=/^(?: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]/,Y1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,X1=/[A-Z0-9]/g,J1=typeof document<"u",Q1=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};un.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(un.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var Vp=Z.event;function Z1(){}function ex(){return this.cancelBubble}function tx(){return this.defaultPrevented}Z.event=function(n){return Vp&&(n=Vp(n)),n.persist=Z1,n.isPropagationStopped=ex,n.isDefaultPrevented=tx,n.nativeEvent=n};var nx={enumerable:!1,configurable:!0,get:function(){return this.class}},Gp=Z.vnode;Z.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||J1&&a==="children"&&i==="noscript"||a==="class"||a==="className")){var c=a.toLowerCase();a==="defaultValue"&&"value"in t&&t.value==null?a="value":a==="download"&&o===!0?o="":c==="translate"&&o==="no"?o=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?a="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||Q1(t.type)?c==="onfocus"?a="onfocusin":c==="onblur"?a="onfocusout":Y1.test(a)&&(a=c):c=a="oninput":s&&$1.test(a)?a=a.replace(X1,"-$&").toLowerCase():o===null&&(o=void 0),c==="oninput"&&r[a=c]&&(a="oninputCapture"),r[a]=o}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=da(t.children).forEach(function(l){l.props.selected=r.value.indexOf(l.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=da(t.children).forEach(function(l){l.props.selected=r.multiple?r.defaultValue.indexOf(l.props.value)!=-1:r.defaultValue==l.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",nx)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=K1,Gp&&Gp(n)};var zp=Z.__r;Z.__r=function(n){zp&&zp(n),n.__c};var Hp=Z.diffed;Z.diffed=function(n){Hp&&Hp(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 ix(n){const{placeholder:e="Type your message...",value:t,defaultValue:i,onChange:r,onSend:s,onCancel:a,onExpand:o,isLoading:c=!1,disabled:l=!1,maxLength:u=500,children:d}=n,[h,f]=Y(t||i||""),[m,p]=Y((t||i||"").length>24),v=Ie(null);yr(()=>{m&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,C=k=>{const x=k.currentTarget.value;t===void 0&&f(x),r==null||r(x)},w=k=>{k.key==="Escape"&&(f(t||i||""),p(!1),a==null||a()),k.key==="Enter"&&!k.shiftKey&&b.trim()&&(k.preventDefault(),f(t||i||""),p(!1),T()),(b||"").length>=24&&!m&&(p(!0),o==null||o(!0))};Je(()=>{v.current&&v.current.focus()},[v.current]);const T=()=>{!b.trim()||c||l||(s==null||s(b.trim()),t===void 0&&f(""))};return g("div",{className:`obi-message-input ${m?"expanded":""}`,children:[g("div",{className:"container",children:g("textarea",{ref:v,className:"field",placeholder:e,value:b,onInput:C,onKeyDown:w,disabled:l||c,maxLength:u,rows:1})}),g("div",{className:"button-container",children:[m&&g("div",{children:d}),g("button",{className:"obi-button send",onClick:T,disabled:!b.trim()||c||l,type:"button",children:g("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function rx(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r,onStepClick:s}=n,[a,o]=Y(null),c=Array.from({length:t},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),l=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 ${l}`})();return g("div",{class:`obi-course-progress ${r||""}`,children:[g("div",{class:"obi-course-progress-steps",children:c.map((d,h)=>{const f=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,m=d.isCompleted?"completed":"future";function p(){s&&s(h,f)}function v(b){s&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p())}return g("div",{class:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>o(h),onMouseLeave:()=>o(null),onClick:s?p:void 0,onKeyDown:s?v:void 0,role:s?"button":void 0,tabIndex:s?0:void 0,children:g("div",{class:`obi-course-progress-step ${m}`,"aria-label":f})},h)})}),g("div",{class:"obi-course-progress-description",children:u})]})}function Wp({className:n="",size:e=64}){return g("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:g("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function sx(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=Y(null),[a,o]=Y(n.isActive??n.defaultIsActive??!1),[c,l]=Y(!1),[u,d]=Y(n.cancelling??!1),[h,f]=Y(n.messaging??!1),[m,p]=Y(!1),[v,b]=Y(h),[C,w]=Y(!1);function T(){o(!0),l(!1),w(!0)}function k(){}function x(){r&&(clearTimeout(r),s(null))}function _(){s(setTimeout(()=>{o(n.defaultIsActive??!1),w(!1)},400))}function R(te){var Ue;p(!1),(Ue=n.onMessage)==null||Ue.call(n,te)}function O(){var te;f(!1),p(!1),o(!1),l(!0),(te=n.onMinimize)==null||te.call(n)}function B(){var te;f(!1),d(!0),p(!1),(te=n.onCancelClick)==null||te.call(n)}function N(){var te;t||((te=n.onOpen)==null||te.call(n))}function W(te){var Ue,Qe,Vt,fn,Et,Qt;switch(te){case"need-help":(Ue=n.onMessage)==null||Ue.call(n,"I'm struggling, can you look at my screen and help me out."),(Qe=n.onOneClickAction)==null||Qe.call(n,"need-help");break;case"continue":(Vt=n.onMessage)==null||Vt.call(n,"Okay, let's continue."),(fn=n.onOneClickAction)==null||fn.call(n,"continue");break;case"say-again":(Et=n.onMessage)==null||Et.call(n,"Please say that again."),(Qt=n.onOneClickAction)==null||Qt.call(n,"say-again");break}}function K(te){var Ue,Qe;n.messaging===void 0?((Ue=n.onMessagingChange)==null||Ue.call(n,te),f(te)):((Qe=n.onMessagingChange)==null||Qe.call(n,!n.messaging),f(!n.messaging)),te||p(!1)}const M=n.isActive??((a||t)&&!c&&!e),Q=M&&t,X=M&&t&&!m,Te=n.speakingStatus==="user-speaking",me=n.speakingStatus==="thinking",xe=n.speakingStatus==="busy",ze=M&&!t&&!u&&C,G=M&&t&&i&&!Te&&!u,re=M&&t&&!G&&!Te&&h!==v&&!u,oe=M&&t&&i&&Te&&!u,we=M&&t&&!i&&Te&&!u,J=M&&t&&!i&&xe&&!u,ge=n.messaging!==void 0?n.messaging:h,De=ge&&Te,yt=ze||G||oe||we||re||u,Tt=400,ai=!!n.courseProgress&&!c,Fi=ze?5:10;return yr(()=>{b(h)},[Te]),!t&&!u?g(ax,{...n}):!t&&u?g(ox,{onOtherSelect:()=>{var te;(te=n.onCancelReasonOther)==null||te.call(n)},onCancelReason:te=>{var Ue;o(n.defaultIsActive??!1),d(!1),(Ue=n.onCancelReason)==null||Ue.call(n,te)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):g(zc,{className:`obi-widget-panel ${Q?"expanded":""} ${m?"maximized":""} ${ge?"messaging":""} ${xe?"tool-usage":""}`,children:[g("div",{className:`obi-widget ${M?"active":""} ${t?"in-plan":""}`,onMouseEnter:x,onMouseLeave:_,children:[X&&g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),X&&!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),X&&i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(gt,{className:"obi-widget-popout",open:yt,trigger:null,delayMs:Tt,offset:Fi,children:[g(gt.Target,{children:[De&&g(ix,{value:n.message,onCancel:()=>K(!1),onSend:R,onExpand:p,onChange:n.onMessageChange,children:g("div",{className:"obi-widget-buttons",children:[g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(Ft,{type:ge?"voice":"message",onClick:()=>K(!ge),title:ge?"Voice input":"Text input"}),g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]})}),!De&&g(Gc,{className:M&&!t?"button":"",isActive:M,speakingStatus:n.speakingStatus,onClick:N,onMouseEnter:T,onMouseLeave:k,children:[M&&!t&&!J&&g("span",{className:"obi-widget-pill-text",children:"Tutorials"}),M&&t&&J&&g("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),M&&t&&!me&&!J&&g(Op,{getBands:n.spectrum}),M&&me&&!J&&g(F1,{})]})]}),g(gt.Content,{children:g("div",{onMouseLeave:_,children:[ze&&g(dn,{onClick:N,children:"Click to see all"}),G&&g(dn,{children:"Session will pause shortly"}),re&&g(dn,{children:["Switched to ",ge?"chat":"voice"]}),oe&&g(dn,{children:"Paused"}),we&&g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[g(dn,{onClick:()=>W("need-help"),children:"Need help"}),g(dn,{onClick:()=>W("continue"),children:"Continue"}),g(dn,{onClick:()=>W("say-again"),children:"Say again"})]}),u&&g(j1,{onContinue:()=>{var te;(te=n.onCancelAbort)==null||te.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var te;(te=n.onCancel)==null||te.call(n)}})]})})]}),X&&g(Ft,{type:ge?"voice":"message",onClick:()=>K(!ge),title:ge?"Voice input":"Text input"}),X&&g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]}),ai&&n.courseProgress&&g("div",{className:`obi-widget-course-progress ${ge?"expanded":""}`,children:g(rx,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames,onStepClick:(te,Ue)=>{var Vt;const Qe=`Can we please jump to the steps related to: ${Ue}`;(Vt=n.onMessage)==null||Vt.call(n,Qe)}})})]})}function ax(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=Y(null),[o,c]=Y(n.isActive??n.defaultIsActive??!1),[l,u]=Y(!1),[d,h]=Y(n.hovered??!1),[f,m]=Y(null),[p,v]=Y(null);function b(){p&&(clearTimeout(p),v(null)),f&&m(null)}function C(){var K;c(!0),u(!1),h(!0),(K=n.onHover)==null||K.call(n,!0)}function w(){}function T(){s&&(clearTimeout(s),a(null))}function k(){o&&a(setTimeout(()=>{var K;c(n.defaultIsActive??!1),h(!1),(K=n.onHover)==null||K.call(n,!1)},400))}function x(){b(),c(!1),u(!0)}function _(){var K;b(),(K=n.onOpen)==null||K.call(n)}const R=n.hovered??(d&&!l),O=n.isActive??(o&&!e&&!l),B=O&&R||!!f,N=`round-button ${O?"active":""}`;let W=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(W=`${t}/${i} completed`),yr(()=>{if(n.toastMessage&&n.toastMessage.text){p&&clearTimeout(p);const K=n.toastMessage.autoCloseMs??3e3;m({text:n.toastMessage.text,autoCloseMs:K});const M=setTimeout(()=>{m(null)},K);v(M)}else n.toastMessage===null&&(p&&clearTimeout(p),m(null))},[n.toastMessage]),g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:`obi-widget-out-of-plan ${R?"hover":""} ${O?"active":""}`,onMouseEnter:T,onMouseLeave:k,onClickCapture:b,children:[g("div",{className:N,style:{width:"30px",height:"30px"}}),g(gt,{className:"obi-widget-popout",open:B,trigger:null,delayMs:400,offset:5,children:[g(gt.Target,{children:g(O1,{className:O?"button":"",active:O,onClick:_,onMouseEnter:C,onMouseLeave:w,children:g("span",{className:"text",children:[g(Wp,{size:16}),W]})})}),g(gt.Content,{children:[!!f&&g(dn,{onClick:()=>{b(),_()},children:f.text}),!f&&g("div",{onMouseLeave:k,children:g(dn,{className:"message",onClick:_,children:"Click to see all"})})]})]}),g(Ft,{className:N,type:"minimize",onClick:x,title:"Minimize widget"})]})})}function ox(n){return g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:"obi-widget-out-of-plan",children:g(gt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[g(gt.Target,{children:g(I1,{active:!1})}),g(gt.Content,{children:g(V1,{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 cx({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return g(Pp,{open:n,onClose:t,preventOutsideClick:i,size:"medium",children:g("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function lx(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var qp={exports:{}};(function(n){(function(){var e={}.hasOwnProperty;function t(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=r(s,i(o)))}return s}function i(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return t.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)e.call(s,o)&&s[o]&&(a=r(a,o));return a}function r(s,a){return a?s?s+" "+a:s+a:s}n.exports?(t.default=t,n.exports=t):window.classNames=t})()})(qp);var ux=qp.exports;const dx=lx(ux);function Di({className:n,title:e="",agentName:t="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:s=!1,footer:a,href:o=null,glow:c=!1,centerVisual:l,description:u,button:d,onAction:h}){const[f,m]=Y(s),[p,v]=Y(!1),[b,C]=Y(r);Je(()=>{p||(r==="listening"&&b!=="listening"&&f&&m(!1),r!=="listening"&&!f&&m(!0)),C(r)},[r,f]),Je(()=>{m(s)},[s]);const w=()=>{f||(m(!0),v(!0),h==null||h())},T=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return i}},k=o?"a":"button",x=o?{href:o,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return g("div",{className:dx("tour-content",n),children:g("div",{className:"container",children:[g("div",{className:`visual ${c?"glow":""}`,children:l}),g("div",{className:"header",children:[g("h1",{className:"title",children:e}),g("div",{className:"description",children:u})]}),g("div",{className:"button-container",children:d||g(k,{className:`action-button ${f?"disabled":""}`,onClick:w,disabled:f,...x,children:g("span",{className:"button-text",children:T()})})}),a&&g("div",{className:"tour-footer",children:a})]})})}function hx({logoUrl:n="",appName:e="App"}){const[t,i]=Y(!1),[r,s]=Y(!1),a=()=>{i(!0)},o=()=>{s(!0),i(!1)},c={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 g("div",{style:c.container,children:g("div",{style:c.logoContainer,children:[g("div",{style:c.backgroundPattern}),g("div",{style:c.logoWrapper,children:[n&&g("img",{style:c.appLogo,src:n,alt:`${e} logo`,onError:a,onLoad:o}),g("div",{style:c.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function fx({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 g(Di,{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:g(hx,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}const{entries:Kp,setPrototypeOf:$p,isFrozen:px,getPrototypeOf:mx,getOwnPropertyDescriptor:gx}=Object;let{freeze:st,seal:_t,create:Yp}=Object,{apply:qc,construct:Kc}=typeof Reflect<"u"&&Reflect;st||(st=function(n){return n}),_t||(_t=function(n){return n}),qc||(qc=function(n,e,t){return n.apply(e,t)}),Kc||(Kc=function(n,e){return new n(...e)});const va=ot(Array.prototype.forEach),vx=ot(Array.prototype.lastIndexOf),Xp=ot(Array.prototype.pop),Tr=ot(Array.prototype.push),bx=ot(Array.prototype.splice),ba=ot(String.prototype.toLowerCase),$c=ot(String.prototype.toString),Jp=ot(String.prototype.match),kr=ot(String.prototype.replace),yx=ot(String.prototype.indexOf),Tx=ot(String.prototype.trim),jt=ot(Object.prototype.hasOwnProperty),at=ot(RegExp.prototype.test),Sr=kx(TypeError);function ot(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 qc(n,e,i)}}function kx(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Kc(n,t)}}function ee(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ba;$p&&$p(n,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const s=t(r);s!==r&&(px(e)||(e[i]=s),r=s)}n[r]=!0}return n}function Sx(n){for(let e=0;e<n.length;e++)jt(n,e)||(n[e]=null);return n}function hn(n){const e=Yp(null);for(const[t,i]of Kp(n))jt(n,t)&&(Array.isArray(i)?e[t]=Sx(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=hn(i):e[t]=i);return e}function Cr(n,e){for(;n!==null;){const i=gx(n,e);if(i){if(i.get)return ot(i.get);if(typeof i.value=="function")return ot(i.value)}n=mx(n)}function t(){return null}return t}const Qp=st(["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"]),Yc=st(["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"]),Xc=st(["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"]),Cx=st(["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"]),Jc=st(["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"]),xx=st(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Zp=st(["#text"]),em=st(["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"]),Qc=st(["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"]),tm=st(["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"]),ya=st(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),wx=_t(/\{\{[\w\W]*|[\w\W]*\}\}/gm),_x=_t(/<%[\w\W]*|[\w\W]*%>/gm),Ex=_t(/\$\{[\w\W]*/gm),Rx=_t(/^data-[\-\w.\u00B7-\uFFFF]+$/),Px=_t(/^aria-[\-\w]+$/),nm=_t(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ix=_t(/^(?:\w+script|data):/i),Ox=_t(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),im=_t(/^html$/i),Ax=_t(/^[a-z][.\w]*(-[.\w]+)+$/i);var rm=Object.freeze({__proto__:null,ARIA_ATTR:Px,ATTR_WHITESPACE:Ox,CUSTOM_ELEMENT:Ax,DATA_ATTR:Rx,DOCTYPE_NAME:im,ERB_EXPR:_x,IS_ALLOWED_URI:nm,IS_SCRIPT_OR_DATA:Ix,MUSTACHE_EXPR:wx,TMPLIT_EXPR:Ex});const xr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Nx=function(){return typeof window>"u"?null:window},Mx=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}},sm=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function am(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Nx();const e=S=>am(S);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==xr.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:c,NodeFilter:l,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=n,m=c.prototype,p=Cr(m,"cloneNode"),v=Cr(m,"remove"),b=Cr(m,"nextSibling"),C=Cr(m,"childNodes"),w=Cr(m,"parentNode");if(typeof a=="function"){const S=t.createElement("template");S.content&&S.content.ownerDocument&&(t=S.content.ownerDocument)}let T,k="";const{implementation:x,createNodeIterator:_,createDocumentFragment:R,getElementsByTagName:O}=t,{importNode:B}=i;let N=sm();e.isSupported=typeof Kp=="function"&&typeof w=="function"&&x&&x.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:W,ERB_EXPR:K,TMPLIT_EXPR:M,DATA_ATTR:Q,ARIA_ATTR:X,IS_SCRIPT_OR_DATA:Te,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:xe}=rm;let{IS_ALLOWED_URI:ze}=rm,G=null;const re=ee({},[...Qp,...Yc,...Xc,...Jc,...Zp]);let oe=null;const we=ee({},[...em,...Qc,...tm,...ya]);let J=Object.seal(Yp(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}})),ge=null,De=null,yt=!0,Tt=!0,ai=!1,Fi=!0,te=!1,Ue=!0,Qe=!1,Vt=!1,fn=!1,Et=!1,Qt=!1,oi=!1,Er=!0,Rr=!1;const Ea="user-content-";let ji=!0,jn=!1,pn={},mn=null;const Pr=ee({},["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 A=null;const z=ee({},["audio","video","img","source","image","track"]);let $=null;const ve=ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Be="http://www.w3.org/1998/Math/MathML",ct="http://www.w3.org/2000/svg",vt="http://www.w3.org/1999/xhtml";let Vn=vt,Vi=!1,Gi=null;const Ra=ee({},[Be,ct,vt],$c);let Zt=ee({},["mi","mo","mn","ms","mtext"]),Pa=ee({},["annotation-xml"]);const f_=ee({},["title","style","font","a","script"]);let Ir=null;const p_=["application/xhtml+xml","text/html"],m_="text/html";let qe=null,zi=null;const g_=t.createElement("form"),Nm=function(S){return S instanceof RegExp||S instanceof Function},al=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(zi&&zi===S)){if((!S||typeof S!="object")&&(S={}),S=hn(S),Ir=p_.indexOf(S.PARSER_MEDIA_TYPE)===-1?m_:S.PARSER_MEDIA_TYPE,qe=Ir==="application/xhtml+xml"?$c:ba,G=jt(S,"ALLOWED_TAGS")?ee({},S.ALLOWED_TAGS,qe):re,oe=jt(S,"ALLOWED_ATTR")?ee({},S.ALLOWED_ATTR,qe):we,Gi=jt(S,"ALLOWED_NAMESPACES")?ee({},S.ALLOWED_NAMESPACES,$c):Ra,$=jt(S,"ADD_URI_SAFE_ATTR")?ee(hn(ve),S.ADD_URI_SAFE_ATTR,qe):ve,A=jt(S,"ADD_DATA_URI_TAGS")?ee(hn(z),S.ADD_DATA_URI_TAGS,qe):z,mn=jt(S,"FORBID_CONTENTS")?ee({},S.FORBID_CONTENTS,qe):Pr,ge=jt(S,"FORBID_TAGS")?ee({},S.FORBID_TAGS,qe):hn({}),De=jt(S,"FORBID_ATTR")?ee({},S.FORBID_ATTR,qe):hn({}),pn=jt(S,"USE_PROFILES")?S.USE_PROFILES:!1,yt=S.ALLOW_ARIA_ATTR!==!1,Tt=S.ALLOW_DATA_ATTR!==!1,ai=S.ALLOW_UNKNOWN_PROTOCOLS||!1,Fi=S.ALLOW_SELF_CLOSE_IN_ATTR!==!1,te=S.SAFE_FOR_TEMPLATES||!1,Ue=S.SAFE_FOR_XML!==!1,Qe=S.WHOLE_DOCUMENT||!1,Et=S.RETURN_DOM||!1,Qt=S.RETURN_DOM_FRAGMENT||!1,oi=S.RETURN_TRUSTED_TYPE||!1,fn=S.FORCE_BODY||!1,Er=S.SANITIZE_DOM!==!1,Rr=S.SANITIZE_NAMED_PROPS||!1,ji=S.KEEP_CONTENT!==!1,jn=S.IN_PLACE||!1,ze=S.ALLOWED_URI_REGEXP||nm,Vn=S.NAMESPACE||vt,Zt=S.MATHML_TEXT_INTEGRATION_POINTS||Zt,Pa=S.HTML_INTEGRATION_POINTS||Pa,J=S.CUSTOM_ELEMENT_HANDLING||{},S.CUSTOM_ELEMENT_HANDLING&&Nm(S.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=S.CUSTOM_ELEMENT_HANDLING.tagNameCheck),S.CUSTOM_ELEMENT_HANDLING&&Nm(S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),S.CUSTOM_ELEMENT_HANDLING&&typeof S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),te&&(Tt=!1),Qt&&(Et=!0),pn&&(G=ee({},Zp),oe=[],pn.html===!0&&(ee(G,Qp),ee(oe,em)),pn.svg===!0&&(ee(G,Yc),ee(oe,Qc),ee(oe,ya)),pn.svgFilters===!0&&(ee(G,Xc),ee(oe,Qc),ee(oe,ya)),pn.mathMl===!0&&(ee(G,Jc),ee(oe,tm),ee(oe,ya))),S.ADD_TAGS&&(G===re&&(G=hn(G)),ee(G,S.ADD_TAGS,qe)),S.ADD_ATTR&&(oe===we&&(oe=hn(oe)),ee(oe,S.ADD_ATTR,qe)),S.ADD_URI_SAFE_ATTR&&ee($,S.ADD_URI_SAFE_ATTR,qe),S.FORBID_CONTENTS&&(mn===Pr&&(mn=hn(mn)),ee(mn,S.FORBID_CONTENTS,qe)),ji&&(G["#text"]=!0),Qe&&ee(G,["html","head","body"]),G.table&&(ee(G,["tbody"]),delete ge.tbody),S.TRUSTED_TYPES_POLICY){if(typeof S.TRUSTED_TYPES_POLICY.createHTML!="function")throw Sr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof S.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Sr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=S.TRUSTED_TYPES_POLICY,k=T.createHTML("")}else T===void 0&&(T=Mx(f,r)),T!==null&&typeof k=="string"&&(k=T.createHTML(""));st&&st(S),zi=S}},Mm=ee({},[...Yc,...Xc,...Cx]),Lm=ee({},[...Jc,...xx]),v_=function(S){let q=w(S);(!q||!q.tagName)&&(q={namespaceURI:Vn,tagName:"template"});const F=ba(S.tagName),he=ba(q.tagName);return Gi[S.namespaceURI]?S.namespaceURI===ct?q.namespaceURI===vt?F==="svg":q.namespaceURI===Be?F==="svg"&&(he==="annotation-xml"||Zt[he]):!!Mm[F]:S.namespaceURI===Be?q.namespaceURI===vt?F==="math":q.namespaceURI===ct?F==="math"&&Pa[he]:!!Lm[F]:S.namespaceURI===vt?q.namespaceURI===ct&&!Pa[he]||q.namespaceURI===Be&&!Zt[he]?!1:!Lm[F]&&(f_[F]||!Mm[F]):!!(Ir==="application/xhtml+xml"&&Gi[S.namespaceURI]):!1},ci=function(S){Tr(e.removed,{element:S});try{w(S).removeChild(S)}catch{v(S)}},Hi=function(S,q){try{Tr(e.removed,{attribute:q.getAttributeNode(S),from:q})}catch{Tr(e.removed,{attribute:null,from:q})}if(q.removeAttribute(S),S==="is")if(Et||Qt)try{ci(q)}catch{}else try{q.setAttribute(S,"")}catch{}},Dm=function(S){let q=null,F=null;if(fn)S="<remove></remove>"+S;else{const Oe=Jp(S,/^[\r\n\t ]+/);F=Oe&&Oe[0]}Ir==="application/xhtml+xml"&&Vn===vt&&(S='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+S+"</body></html>");const he=T?T.createHTML(S):S;if(Vn===vt)try{q=new h().parseFromString(he,Ir)}catch{}if(!q||!q.documentElement){q=x.createDocument(Vn,"template",null);try{q.documentElement.innerHTML=Vi?k:he}catch{}}const Ze=q.body||q.documentElement;return S&&F&&Ze.insertBefore(t.createTextNode(F),Ze.childNodes[0]||null),Vn===vt?O.call(q,Qe?"html":"body")[0]:Qe?q.documentElement:Ze},Um=function(S){return _.call(S.ownerDocument||S,S,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ol=function(S){return S instanceof d&&(typeof S.nodeName!="string"||typeof S.textContent!="string"||typeof S.removeChild!="function"||!(S.attributes instanceof u)||typeof S.removeAttribute!="function"||typeof S.setAttribute!="function"||typeof S.namespaceURI!="string"||typeof S.insertBefore!="function"||typeof S.hasChildNodes!="function")},Bm=function(S){return typeof o=="function"&&S instanceof o};function gn(S,q,F){va(S,he=>{he.call(e,q,F,zi)})}const Fm=function(S){let q=null;if(gn(N.beforeSanitizeElements,S,null),ol(S))return ci(S),!0;const F=qe(S.nodeName);if(gn(N.uponSanitizeElement,S,{tagName:F,allowedTags:G}),Ue&&S.hasChildNodes()&&!Bm(S.firstElementChild)&&at(/<[/\w!]/g,S.innerHTML)&&at(/<[/\w!]/g,S.textContent)||S.nodeType===xr.progressingInstruction||Ue&&S.nodeType===xr.comment&&at(/<[/\w]/g,S.data))return ci(S),!0;if(!G[F]||ge[F]){if(!ge[F]&&Vm(F)&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,F)||J.tagNameCheck instanceof Function&&J.tagNameCheck(F)))return!1;if(ji&&!mn[F]){const he=w(S)||S.parentNode,Ze=C(S)||S.childNodes;if(Ze&&he){const Oe=Ze.length;for(let vn=Oe-1;vn>=0;--vn){const Gt=p(Ze[vn],!0);Gt.__removalCount=(S.__removalCount||0)+1,he.insertBefore(Gt,b(S))}}}return ci(S),!0}return S instanceof c&&!v_(S)||(F==="noscript"||F==="noembed"||F==="noframes")&&at(/<\/no(script|embed|frames)/i,S.innerHTML)?(ci(S),!0):(te&&S.nodeType===xr.text&&(q=S.textContent,va([W,K,M],he=>{q=kr(q,he," ")}),S.textContent!==q&&(Tr(e.removed,{element:S.cloneNode()}),S.textContent=q)),gn(N.afterSanitizeElements,S,null),!1)},jm=function(S,q,F){if(Er&&(q==="id"||q==="name")&&(F in t||F in g_))return!1;if(!(Tt&&!De[q]&&at(Q,q))&&!(yt&&at(X,q))){if(!oe[q]||De[q]){if(!(Vm(S)&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,S)||J.tagNameCheck instanceof Function&&J.tagNameCheck(S))&&(J.attributeNameCheck instanceof RegExp&&at(J.attributeNameCheck,q)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(q))||q==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&at(J.tagNameCheck,F)||J.tagNameCheck instanceof Function&&J.tagNameCheck(F))))return!1}else if(!$[q]&&!at(ze,kr(F,me,""))&&!((q==="src"||q==="xlink:href"||q==="href")&&S!=="script"&&yx(F,"data:")===0&&A[S])&&!(ai&&!at(Te,kr(F,me,"")))&&F)return!1}return!0},Vm=function(S){return S!=="annotation-xml"&&Jp(S,xe)},Gm=function(S){gn(N.beforeSanitizeAttributes,S,null);const{attributes:q}=S;if(!q||ol(S))return;const F={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:oe,forceKeepAttr:void 0};let he=q.length;for(;he--;){const Ze=q[he],{name:Oe,namespaceURI:vn,value:Gt}=Ze,en=qe(Oe),cl=Gt;let it=Oe==="value"?cl:Tx(cl);if(F.attrName=en,F.attrValue=it,F.keepAttr=!0,F.forceKeepAttr=void 0,gn(N.uponSanitizeAttribute,S,F),it=F.attrValue,Rr&&(en==="id"||en==="name")&&(Hi(Oe,S),it=Ea+it),Ue&&at(/((--!?|])>)|<\/(style|title)/i,it)){Hi(Oe,S);continue}if(F.forceKeepAttr)continue;if(!F.keepAttr){Hi(Oe,S);continue}if(!Fi&&at(/\/>/i,it)){Hi(Oe,S);continue}te&&va([W,K,M],y_=>{it=kr(it,y_," ")});const zm=qe(S.nodeName);if(!jm(zm,en,it)){Hi(Oe,S);continue}if(T&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!vn)switch(f.getAttributeType(zm,en)){case"TrustedHTML":{it=T.createHTML(it);break}case"TrustedScriptURL":{it=T.createScriptURL(it);break}}if(it!==cl)try{vn?S.setAttributeNS(vn,Oe,it):S.setAttribute(Oe,it),ol(S)?ci(S):Xp(e.removed)}catch{Hi(Oe,S)}}gn(N.afterSanitizeAttributes,S,null)},b_=function S(q){let F=null;const he=Um(q);for(gn(N.beforeSanitizeShadowDOM,q,null);F=he.nextNode();)gn(N.uponSanitizeShadowNode,F,null),Fm(F),Gm(F),F.content instanceof s&&S(F.content);gn(N.afterSanitizeShadowDOM,q,null)};return e.sanitize=function(S){let q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},F=null,he=null,Ze=null,Oe=null;if(Vi=!S,Vi&&(S="<!-->"),typeof S!="string"&&!Bm(S))if(typeof S.toString=="function"){if(S=S.toString(),typeof S!="string")throw Sr("dirty is not a string, aborting")}else throw Sr("toString is not a function");if(!e.isSupported)return S;if(Vt||al(q),e.removed=[],typeof S=="string"&&(jn=!1),jn){if(S.nodeName){const en=qe(S.nodeName);if(!G[en]||ge[en])throw Sr("root node is forbidden and cannot be sanitized in-place")}}else if(S instanceof o)F=Dm("<!---->"),he=F.ownerDocument.importNode(S,!0),he.nodeType===xr.element&&he.nodeName==="BODY"||he.nodeName==="HTML"?F=he:F.appendChild(he);else{if(!Et&&!te&&!Qe&&S.indexOf("<")===-1)return T&&oi?T.createHTML(S):S;if(F=Dm(S),!F)return Et?null:oi?k:""}F&&fn&&ci(F.firstChild);const vn=Um(jn?S:F);for(;Ze=vn.nextNode();)Fm(Ze),Gm(Ze),Ze.content instanceof s&&b_(Ze.content);if(jn)return S;if(Et){if(Qt)for(Oe=R.call(F.ownerDocument);F.firstChild;)Oe.appendChild(F.firstChild);else Oe=F;return(oe.shadowroot||oe.shadowrootmode)&&(Oe=B.call(i,Oe,!0)),Oe}let Gt=Qe?F.outerHTML:F.innerHTML;return Qe&&G["!doctype"]&&F.ownerDocument&&F.ownerDocument.doctype&&F.ownerDocument.doctype.name&&at(im,F.ownerDocument.doctype.name)&&(Gt="<!DOCTYPE "+F.ownerDocument.doctype.name+`>
|
|
43
43
|
`+Gt),te&&va([W,K,M],en=>{Gt=kr(Gt,en," ")}),T&&oi?T.createHTML(Gt):Gt},e.setConfig=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};al(S),Vt=!0},e.clearConfig=function(){zi=null,Vt=!1},e.isValidAttribute=function(S,q,F){zi||al({});const he=qe(S),Ze=qe(q);return jm(he,Ze,F)},e.addHook=function(S,q){typeof q=="function"&&Tr(N[S],q)},e.removeHook=function(S,q){if(q!==void 0){const F=vx(N[S],q);return F===-1?void 0:bx(N[S],F,1)[0]}return Xp(N[S])},e.removeHooks=function(S){N[S]=[]},e.removeAllHooks=function(){N=sm()},e}var Lx=am();function Dx({}){return g("div",{className:"obi-static-voice",children:[g("div",{className:"obi-static-voice-visual-title",children:"AI Guided Tutorial"}),g("div",{style:{transform:"scale(1.25) translateY(-4px)"},children:g(Gc,{isActive:!0,children:g("div",{className:"obi-static-voice-visual",children:[g("div",{className:"column",children:g("div",{className:"bar bar-1"})}),g("div",{className:"column",children:g("div",{className:"bar bar-2"})}),g("div",{className:"column",children:g("div",{className:"bar bar-3"})}),g("div",{className:"column",children:g("div",{className:"bar bar-4"})}),g("div",{className:"column",children:g("div",{className:"bar bar-5"})}),g("div",{className:"column",children:g("div",{className:"bar bar-6"})}),g("div",{className:"column",children:g("div",{className:"bar bar-7"})}),g("div",{className:"column",children:g("div",{className:"bar bar-8"})})]})})})]})}function Ux({session:n,speakingState:e,onAction:t}){const i="Sessions are securely recorded for quality improvement purposes.",r=fa(()=>{var c;const o=(c=n.legalFooter)==null?void 0:c.trim();return o?Lx.sanitize(o):null},[n.legalFooter]),s=Ie(null);Je(()=>{if(!r)return;const o=s.current;o&&o.querySelectorAll("a").forEach(c=>{c.setAttribute("target","_blank");const l=(c.getAttribute("rel")||"").split(/\s+/);l.includes("noopener")||l.push("noopener"),l.includes("noreferrer")||l.push("noreferrer"),c.setAttribute("rel",l.filter(Boolean).join(" ")),c.style.color="black"})},[r]);const a=r?g("span",{ref:s,dangerouslySetInnerHTML:{__html:r}}):i;return g(Di,{className:"session-start-content",title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,footer:a,buttonText:"Get started",agentName:n.agentName||"Obi",speakingState:e,centerVisual:g(Dx,{}),onAction:t})}function Bx(){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 g("div",{style:n.host,children:[g("style",{children:`
|
|
44
44
|
@keyframes pointToAllow {
|
|
45
45
|
0%, 100% { transform: translate(0, 0); }
|
|
@@ -52,5 +52,5 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
|
52
52
|
100% { transform: translateX(344px); }
|
|
53
53
|
}
|
|
54
54
|
`}),g("article",{style:n.skeletonContainer,role:"status","aria-label":"Loading content",children:[g("section",{style:n.headerSection,children:[g("div",{style:n.avatar,role:"img","aria-label":"Loading avatar",children:g("div",{style:n.shimmer})}),g("div",{style:n.textLines,children:[g("div",{style:n.textLine,role:"presentation","aria-label":"Loading text line 1",children:g("div",{style:n.shimmer})}),g("div",{style:n.textLine,role:"presentation","aria-label":"Loading text line 2",children:g("div",{style:n.shimmer})})]})]}),g("section",{style:n.contentSection,children:g("div",{style:n.contentBlock,role:"presentation","aria-label":"Loading card content",children:g("div",{style:n.shimmer})})})]})]})}function Gx({}){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 g("div",{style:n.host,children:g("div",{style:n.shareContainer,children:[g("div",{style:n.controlsRow,children:[g("div",{style:n.monitorIconContainer,children:g("svg",{style:n.monitorIcon,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[g("rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",ry:"2"}),g("line",{x1:"8",x2:"16",y1:"21",y2:"21"}),g("line",{x1:"12",x2:"12",y1:"17",y2:"21"})]})}),g("div",{style:n.tabSelector,children:[g("button",{style:n.tabButton(!1),children:"Tab"}),g("button",{style:n.tabButton(!0),children:"Window"})]})]}),g("div",{style:n.skeletonContainer,children:g(Vx,{})})]})})}function zx({session:n,speakingState:e,onAction:t}){return g(Di,{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:g(Gx,{}),actionDisabled:!0,onAction:t})}function Hx({session:n,speakingState:e,spectrum:t,onAction:i}){return g(Di,{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:g(om,{spectrum:t}),actionDisabled:!0,onAction:i})}function Wx({id:n,name:e,description:t,duration:i=10,order:r=0,selected:s=!1,completed:a=!1,onClick:o}){return g("div",{className:`course-container ${s?"selected":""}`,onClick:()=>{o==null||o({id:n,name:e,description:t,duration:i,order:r})},children:[g("div",{className:"header-row",children:[g("h2",{className:"course-title",children:e}),a&&g("span",{className:"duration",children:"Completed"})]}),t&&g("p",{className:"course-description",children:t})]})}function qx({courses:n=[],selectedCourseId:e=null,loading:t=!1,error:i="",onCourseSelect:r}){const[s,a]=Y(""),o=u=>{const d=u.currentTarget;a(d.value)},c=u=>{r==null||r(u)};if(t)return g("div",{className:"loading",children:"Loading..."});if(i)return g("div",{className:"error",children:i});if(!n||n.length===0)return g("div",{className:"empty",children:"No courses available"});const l=n.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())||(u.description||"").toLowerCase().includes(s.toLowerCase()));return g("div",{className:"tour-select",children:[g("div",{className:"controls",children:[g("div",{className:"tabs",children:g("button",{className:"tab active",children:"All"})}),g("div",{className:"filter",children:[g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("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"})}),g("input",{type:"text",placeholder:"Search...",value:s,onInput:o})]})]}),g("div",{className:"course-grid",children:l.sort((u,d)=>(u.order||0)-(d.order||0)).map(u=>{const d=u.id===e;return g(Wx,{id:u.id,name:u.name,description:u.description||"",duration:u.duration,order:u.order||0,completed:u.completed,selected:d,onClick:c},u.id)})})]})}function Kx({open:n,courses:e=[],loading:t=!1,error:i="",title:r="AI Coach",productName:s,onClose:a,onCourseSelect:o,onCourseHighlight:c}){const[l,u]=Y(null),d=f=>{u(f),c==null||c(f)},h=()=>{l&&o&&o(l)};return g(Pp,{open:n,onClose:a,size:"large",preventOutsideClick:!0,children:g("div",{className:"tour-select-modal-container",children:[g("div",{className:"header",children:[g("div",{className:"icon",style:{color:"white"},children:g(Wp,{})}),g("div",{className:"title-section",children:t?g(nt,{children:[g("div",{className:"skeleton skeleton-title"}),g("div",{className:"skeleton skeleton-subtitle"})]}):g(nt,{children:[g("h1",{children:r}),g("p",{className:"subtitle",children:["Start a tutorial and learn how to use ",s," through an interactive conversation."]})]})})]}),g("div",{className:"course-list-wrapper",children:g(qx,{courses:e,selectedCourseId:(l==null?void 0:l.id)||"",loading:t,error:i,onCourseSelect:d})}),g("div",{className:"footer",children:[g("button",{className:"obi-button footer-button",onClick:h,disabled:!l,children:[g("span",{children:"Get started"}),g("svg",{xmlns:"http://www.w3.org/2000/svg",width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",children:g("path",{d:"M3.83325 8.00065H13.1666M13.1666 8.00065L8.49992 3.33398M13.1666 8.00065L8.49992 12.6673",stroke:l?"#FAFAFA":"#999","stroke-width":"1.33","stroke-linecap":"round","stroke-linejoin":"round"})})]}),g("p",{className:"footer-text",children:"Sessions are securely recorded for quality improvement purposes."})]})]})})}function $x({session:n,sessionState:e,speakingState:t,spectrum:i,onStart:r,onContinue:s,onShareMicrophone:a,onShareScreen:o,onModalChange:c}){const[l,u]=Y(null);function d(f){l!==f&&(c==null||c(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 fa(()=>{switch(e){case null:case"connecting":case"connected":return d("session-start"),g(Ux,{session:n,speakingState:t,onAction:h});case"volume-check":return d("voice-guidance"),g(jx,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-check":return d("overview"),g(Hx,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-share":return d("share-mic"),g(Fx,{session:n,speakingState:t,onAction:h});case"screen-share":return d("share-screen"),g(zx,{session:n,speakingState:t,onAction:h});case"navigate":return d("navigate"),g(fx,{session:n,speakingState:t,onAction:h});default:return null}},[e,t,r,s,a,o])}function Yx(n){const{session:e,sessionState:t,speakingState:i,spectrum:r,onClose:s,onStart:a,onContinue:o,onShareMicrophone:c,onShareScreen:l,onModalChange:u}=n,[d,h]=Y(null);function f(v){u==null||u(v),h(v)}function m(v){s(v,d),h(null)}const p=(n.open??!0)&&(!t||t==="connecting"||t==="connected"||t==="volume-check"||t==="mic-check"||t==="mic-share"||t==="screen-share"||t==="navigate");return g(cx,{open:p,onClose:m,preventOutsideClick:!0,children:()=>g($x,{session:e,sessionState:t,speakingState:i,spectrum:r,onStart:a,onContinue:o,onShareMicrophone:c,onShareScreen:l,onModalChange:f})})}const Xx={identify:()=>{},track:()=>{},page:()=>{},reset:()=>{}};function ii(){return Xx}const Jx=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,cm="9.23.0",Ui=globalThis;function Qx(n,e,t=Ui){const i=t.__SENTRY__=t.__SENTRY__||{},r=i[cm]=i[cm]||{};return r[n]||(r[n]=e())}const Zx="Sentry Logger ",lm=["debug","info","warn","error","log","assert","trace"],um={};function ew(n){if(!("console"in Ui))return n();const e=Ui.console,t={},i=Object.keys(um);i.forEach(r=>{const s=um[r];t[r]=e[r],e[r]=s});try{return n()}finally{i.forEach(r=>{e[r]=t[r]})}}function tw(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return Jx?lm.forEach(t=>{e[t]=(...i)=>{n&&ew(()=>{Ui.console[t](`${Zx}[${t}]:`,...i)})}}):lm.forEach(t=>{e[t]=()=>{}}),e}Qx("logger",tw);const dm=1e3;function nw(){return Date.now()/dm}function iw(){const{performance:n}=Ui;if(!(n!=null&&n.now))return nw;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/dm}iw();const hm=50,Bi="?",fm=/\(error: (.*)\)/,pm=/captureMessage|captureException/;function rw(...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 c=a[o];if(c.length>1024)continue;const l=fm.test(c)?c.replace(fm,"$1"):c;if(!l.match(/\S*Error: /)){for(const u of e){const d=u(l);if(d){s.push(d);break}}if(s.length>=hm+r)break}}return sw(s.slice(r))}}function sw(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(Ta(e).function||"")&&e.pop(),e.reverse(),pm.test(Ta(e).function||"")&&(e.pop(),pm.test(Ta(e).function||"")&&e.pop()),e.slice(0,hm).map(t=>({...t,filename:t.filename||Ta(e).filename,function:t.function||Bi}))}function Ta(n){return n[n.length-1]||{}}var mm;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(mm||(mm={})),Ui._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const aw=30,ow=50;function Zc(n,e,t,i){const r={filename:n,function:e==="<anonymous>"?Bi:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}const cw=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lw=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,uw=/\((\S*)(?::(\d+))(?::(\d+))\)/,dw=n=>{const e=cw.exec(n);if(e){const[,i,r,s]=e;return Zc(i,Bi,+r,+s)}const t=lw.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=uw.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=gm(t[1]||Bi,t[2]);return Zc(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},hw=[aw,dw],fw=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pw=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;rw(...[hw,[ow,n=>{const e=fw.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=pw.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]||Bi;return[i,t]=gm(i,t),Zc(t,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const gm=(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]:Bi,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function mw(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function gw(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(i=>{try{const r=mw(i);return r.test(t)||r.test(n)}catch(r){return console.warn(`Invalid URL pattern: ${i}`,r),!1}})}function ka(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return gw(e,n)}function vw(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{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function bw(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(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var vm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wr=typeof Uint8Array>"u"?[]:new Uint8Array(256),Sa=0;Sa<vm.length;Sa++)wr[vm.charCodeAt(Sa)]=Sa;for(var yw=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var l=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(l)?l:new Uint8Array(l);for(i=0;i<t;i+=4)s=wr[n.charCodeAt(i)],a=wr[n.charCodeAt(i+1)],o=wr[n.charCodeAt(i+2)],c=wr[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|c&63;return l},Tw=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},kw=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},ri=5,el=6+5,tl=2,Sw=el-ri,bm=65536>>ri,Cw=1<<ri,nl=Cw-1,xw=1024>>ri,ww=bm+xw,_w=ww,Ew=32,Rw=_w+Ew,Pw=65536>>el,Iw=1<<Sw,Ow=Iw-1,ym=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Aw=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},Nw=function(n,e){var t=yw(n),i=Array.isArray(t)?kw(t):new Uint32Array(t),r=Array.isArray(t)?Tw(t):new Uint16Array(t),s=24,a=ym(r,s/2,i[4]/2),o=i[5]===2?ym(r,(s+i[4])/2):Aw(i,Math.ceil((s+i[4])/4));return new Mw(i[0],i[1],i[2],i[3],a,o)},Mw=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>>ri],t=(t<<tl)+(e&nl),this.data[t];if(e<=65535)return t=this.index[bm+(e-55296>>ri)],t=(t<<tl)+(e&nl),this.data[t];if(e<this.highStart)return t=Rw-Pw+(e>>el),t=this.index[t],t+=e>>ri&Ow,t=this.index[t],t=(t<<tl)+(e&nl),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),Tm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Lw=typeof Uint8Array>"u"?[]:new Uint8Array(256),Ca=0;Ca<Tm.length;Ca++)Lw[Tm.charCodeAt(Ca)]=Ca;var km=null;function Dw(n){return vw(this,void 0,void 0,function(){var e;return bw(this,function(t){switch(t.label){case 0:return km!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw new Error("Invalid graphemes response");km=Nw(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}for(var Sm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Uw=typeof Uint8Array>"u"?[]:new Uint8Array(256),xa=0;xa<Sm.length;xa++)Uw[Sm.charCodeAt(xa)]=xa;function Bw(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{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function Fw(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(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var Cm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_r=typeof Uint8Array>"u"?[]:new Uint8Array(256),wa=0;wa<Cm.length;wa++)_r[Cm.charCodeAt(wa)]=wa;for(var jw=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var l=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(l)?l:new Uint8Array(l);for(i=0;i<t;i+=4)s=_r[n.charCodeAt(i)],a=_r[n.charCodeAt(i+1)],o=_r[n.charCodeAt(i+2)],c=_r[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|c&63;return l},Vw=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},Gw=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},si=5,il=6+5,rl=2,zw=il-si,xm=65536>>si,Hw=1<<si,sl=Hw-1,Ww=1024>>si,qw=xm+Ww,Kw=qw,$w=32,Yw=Kw+$w,Xw=65536>>il,Jw=1<<zw,Qw=Jw-1,wm=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Zw=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},e_=function(n,e){var t=jw(n),i=Array.isArray(t)?Gw(t):new Uint32Array(t),r=Array.isArray(t)?Vw(t):new Uint16Array(t),s=24,a=wm(r,s/2,i[4]/2),o=i[5]===2?wm(r,(s+i[4])/2):Zw(i,Math.ceil((s+i[4])/4));return new t_(i[0],i[1],i[2],i[3],a,o)},t_=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>>si],t=(t<<rl)+(e&sl),this.data[t];if(e<=65535)return t=this.index[xm+(e-55296>>si)],t=(t<<rl)+(e&sl),this.data[t];if(e<this.highStart)return t=Yw-Xw+(e>>il),t=this.index[t],t+=e>>si&Qw,t=this.index[t],t=(t<<rl)+(e&sl),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),_m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n_=typeof Uint8Array>"u"?[]:new Uint8Array(256),_a=0;_a<_m.length;_a++)n_[_m.charCodeAt(_a)]=_a;var Em=null;function i_(n){return Bw(this,void 0,void 0,function(){var e;return Fw(this,function(t){switch(t.label){case 0:return Em!==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");Em=e_(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}const r_=`:root,:host{--obi-modal-padding: 32px 48px;--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{height:45px;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;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}.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;display:flex;align-items:flex-end;justify-content:center;font-family:Inter,sans-serif;font-size:8px;font-weight:200;margin-top:20px}.session-start-content .description{height:48px}@media (max-width: 600px){dialog,dialog.modal-xsmall,dialog.modal-small,dialog.modal-medium,dialog.modal-large,dialog>.modal-content,dialog.modal-xsmall>.modal-content,dialog.modal-small>.modal-content,dialog.modal-medium>.modal-content,dialog.modal-large>.modal-content{width:min(280px,100vw - 32px);max-width:100vw;min-height:auto}dialog>.modal-content{padding:24px 20px}.tour-content .title{font-size:20px}.tour-content .subtitle{font-size:14px}.tour-content .description{font-size:13px;min-height:87px;height:auto;overflow:visible;text-overflow:unset;display:block;-webkit-line-clamp:unset;-webkit-box-orient:unset}.tour-content .button-text{font-size:14px}.tour-content .visual{display:none}.tour-content.session-start-content .visual{display:flex}.tour-content.session-start-content .obi-static-voice{height:auto}.tour-content.session-start-content .obi-static-voice-visual-title{margin-bottom:8px}.tour-content.session-start-content .obi-static-voice .obi-pill.container{display:none}}.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-close-button:focus{outline:none}.obi-close-button:focus-visible{outline:2px solid #005fcc}.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-widget-draggable .obi-widget-panel{cursor:grab}.obi-widget-draggable.dragging .obi-widget-panel{cursor:grabbing;-webkit-user-select:none;user-select:none}.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 c=a[o];if(c.length>1024)continue;const l=fm.test(c)?c.replace(fm,"$1"):c;if(!l.match(/\S*Error: /)){for(const u of e){const d=u(l);if(d){s.push(d);break}}if(s.length>=hm+r)break}}return sw(s.slice(r))}}function sw(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(Ta(e).function||"")&&e.pop(),e.reverse(),pm.test(Ta(e).function||"")&&(e.pop(),pm.test(Ta(e).function||"")&&e.pop()),e.slice(0,hm).map(t=>({...t,filename:t.filename||Ta(e).filename,function:t.function||Bi}))}function Ta(n){return n[n.length-1]||{}}var mm;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(mm||(mm={})),Ui._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const aw=30,ow=50;function Zc(n,e,t,i){const r={filename:n,function:e==="<anonymous>"?Bi:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}const cw=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lw=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,uw=/\((\S*)(?::(\d+))(?::(\d+))\)/,dw=n=>{const e=cw.exec(n);if(e){const[,i,r,s]=e;return Zc(i,Bi,+r,+s)}const t=lw.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=uw.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=gm(t[1]||Bi,t[2]);return Zc(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},hw=[aw,dw],fw=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pw=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;rw(...[hw,[ow,n=>{const e=fw.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=pw.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]||Bi;return[i,t]=gm(i,t),Zc(t,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const gm=(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]:Bi,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function mw(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function gw(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(i=>{try{const r=mw(i);return r.test(t)||r.test(n)}catch(r){return console.warn(`Invalid URL pattern: ${i}`,r),!1}})}function ka(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return gw(e,n)}function vw(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{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function bw(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(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var vm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wr=typeof Uint8Array>"u"?[]:new Uint8Array(256),Sa=0;Sa<vm.length;Sa++)wr[vm.charCodeAt(Sa)]=Sa;for(var yw=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var l=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(l)?l:new Uint8Array(l);for(i=0;i<t;i+=4)s=wr[n.charCodeAt(i)],a=wr[n.charCodeAt(i+1)],o=wr[n.charCodeAt(i+2)],c=wr[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|c&63;return l},Tw=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},kw=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},ri=5,el=6+5,tl=2,Sw=el-ri,bm=65536>>ri,Cw=1<<ri,nl=Cw-1,xw=1024>>ri,ww=bm+xw,_w=ww,Ew=32,Rw=_w+Ew,Pw=65536>>el,Iw=1<<Sw,Ow=Iw-1,ym=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Aw=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},Nw=function(n,e){var t=yw(n),i=Array.isArray(t)?kw(t):new Uint32Array(t),r=Array.isArray(t)?Tw(t):new Uint16Array(t),s=24,a=ym(r,s/2,i[4]/2),o=i[5]===2?ym(r,(s+i[4])/2):Aw(i,Math.ceil((s+i[4])/4));return new Mw(i[0],i[1],i[2],i[3],a,o)},Mw=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>>ri],t=(t<<tl)+(e&nl),this.data[t];if(e<=65535)return t=this.index[bm+(e-55296>>ri)],t=(t<<tl)+(e&nl),this.data[t];if(e<this.highStart)return t=Rw-Pw+(e>>el),t=this.index[t],t+=e>>ri&Ow,t=this.index[t],t=(t<<tl)+(e&nl),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),Tm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Lw=typeof Uint8Array>"u"?[]:new Uint8Array(256),Ca=0;Ca<Tm.length;Ca++)Lw[Tm.charCodeAt(Ca)]=Ca;var km=null;function Dw(n){return vw(this,void 0,void 0,function(){var e;return bw(this,function(t){switch(t.label){case 0:return km!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw new Error("Invalid graphemes response");km=Nw(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}for(var Sm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Uw=typeof Uint8Array>"u"?[]:new Uint8Array(256),xa=0;xa<Sm.length;xa++)Uw[Sm.charCodeAt(xa)]=xa;function Bw(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{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function Fw(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(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var Cm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_r=typeof Uint8Array>"u"?[]:new Uint8Array(256),wa=0;wa<Cm.length;wa++)_r[Cm.charCodeAt(wa)]=wa;for(var jw=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var l=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(l)?l:new Uint8Array(l);for(i=0;i<t;i+=4)s=_r[n.charCodeAt(i)],a=_r[n.charCodeAt(i+1)],o=_r[n.charCodeAt(i+2)],c=_r[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|c&63;return l},Vw=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},Gw=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},si=5,il=6+5,rl=2,zw=il-si,xm=65536>>si,Hw=1<<si,sl=Hw-1,Ww=1024>>si,qw=xm+Ww,Kw=qw,$w=32,Yw=Kw+$w,Xw=65536>>il,Jw=1<<zw,Qw=Jw-1,wm=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Zw=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},e_=function(n,e){var t=jw(n),i=Array.isArray(t)?Gw(t):new Uint32Array(t),r=Array.isArray(t)?Vw(t):new Uint16Array(t),s=24,a=wm(r,s/2,i[4]/2),o=i[5]===2?wm(r,(s+i[4])/2):Zw(i,Math.ceil((s+i[4])/4));return new t_(i[0],i[1],i[2],i[3],a,o)},t_=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>>si],t=(t<<rl)+(e&sl),this.data[t];if(e<=65535)return t=this.index[xm+(e-55296>>si)],t=(t<<rl)+(e&sl),this.data[t];if(e<this.highStart)return t=Yw-Xw+(e>>il),t=this.index[t],t+=e>>si&Qw,t=this.index[t],t=(t<<rl)+(e&sl),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),_m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n_=typeof Uint8Array>"u"?[]:new Uint8Array(256),_a=0;_a<_m.length;_a++)n_[_m.charCodeAt(_a)]=_a;var Em=null;function i_(n){return Bw(this,void 0,void 0,function(){var e;return Fw(this,function(t){switch(t.label){case 0:return Em!==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");Em=e_(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}const r_=`:root,:host{--obi-modal-padding: 32px 48px;--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{height:45px;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;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}.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;display:flex;align-items:flex-end;justify-content:center;font-family:Inter,sans-serif;font-size:8px;font-weight:200;margin-top:20px}.session-start-content .description{height:48px}@media (max-width: 600px){dialog,dialog.modal-xsmall,dialog.modal-small,dialog.modal-medium,dialog.modal-large,dialog>.modal-content,dialog.modal-xsmall>.modal-content,dialog.modal-small>.modal-content,dialog.modal-medium>.modal-content,dialog.modal-large>.modal-content{width:min(280px,100vw - 32px);max-width:100vw;min-height:auto}dialog>.modal-content{padding:24px 20px}.tour-content .title{font-size:20px}.tour-content .subtitle{font-size:14px}.tour-content .description{font-size:13px;min-height:87px;height:auto;overflow:visible;text-overflow:unset;display:block;-webkit-line-clamp:unset;-webkit-box-orient:unset}.tour-content .button-text{font-size:14px}.tour-content .visual{display:none}.tour-content.session-start-content .visual{display:flex}.tour-content.session-start-content .obi-static-voice{height:auto}.tour-content.session-start-content .obi-static-voice-visual-title{margin-bottom:8px}.tour-content.session-start-content .obi-static-voice .obi-pill.container{display:none}}.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;outline:none}.obi-close-button:focus{outline:none!important}.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-widget-draggable .obi-widget-panel{cursor:grab}.obi-widget-draggable.dragging .obi-widget-panel{cursor:grabbing;-webkit-user-select:none;user-select:none}.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 s_(n){var Et,Qt,oi,Er,Rr,Ea,ji,jn,pn,mn,Pr;const[e,t]=Y(!1),[i,r]=Y(!1),[s,a]=Y(!1),[o,c]=Y(!1),[l,u]=Y(null),[d,h]=Y(!1),[f,m]=Y(null),[p,v]=Y(null),[b,C]=Y(null),[w,T]=Y(!1),k=Ie(null),x=Ie(0),_=Ie(0),R=Ie(0),O=Ie(0),B=Ie({width:0,height:0}),N=Ie(null),W=Ie(!1),K=6,M=a_(n.sdk,Q,n.shadowHost,v,A=>{var z,$;a(A),A&&(($=(z=M.client.session)==null?void 0:z.muteMicrophone)==null||$.call(z))},A=>{if(!A){u(null);return}if(ge&&(u(A),!re&&me==="minimized")){h(!0);const z=Math.max(0,A.autoCloseMs??3e3);f&&window.clearTimeout(f);const $=window.setTimeout(()=>h(!1),z);m($)}});function Q(A){var z;(z=M.client)!=null&&z.session||(A?fn():t(!1))}if(!M.client)return null;const X=M.client.planIsCompleted.filter(Boolean).length===M.client.plans.length,Te=o_((Et=M.client.product)==null?void 0:Et.widget_url_blacklist),me=X?M.completedWidgetDisplay||((Qt=M.client.product)==null?void 0:Qt.completed_widget_display):M.widgetDisplay||((oi=M.client.product)==null?void 0:oi.widget_display),xe=M.widgetPosition||((Er=M.client.product)==null?void 0:Er.widget_position);let ze=M.isActive;((Ea=(Rr=M.client)==null?void 0:Rr.product)==null?void 0:Ea.name)==="Canibuild"&&(ze=!0);const G=M.client.session,re=!!G;Je(()=>{c(!1)},[G]);const oe=re&&!e;let we;switch(G==null?void 0:G.speakingState){case"listening":we="user-speaking";break;case"speaking":we="agent-speaking";break;case"thinking":we="thinking";break;case"busy":we="busy";break}const J=G==null?void 0:G.isPaused,ge=re||M.client.state==="ready"&&ze&&!Te&&(me!=="invisible"||M.client.selectedPlan),De=()=>{var A,z,$,ve,Be,ct,vt;return{name:(A=M.client.selectedPlan)==null?void 0:A.name,description:(z=M.client.selectedPlan)==null?void 0:z.description,appName:($=M.client.product)==null?void 0:$.name,appLogoUrl:((ve=M.client.product)==null?void 0:ve.logo_url)||"",url:(Be=M.client.product)==null?void 0:Be.url,agentName:((ct=M.client.product)==null?void 0:ct.agent_name)||"Obi",legalFooter:((vt=M.client.product)==null?void 0:vt.legal_footer_text)||void 0}};function yt(){const A=xe==="bottom-right"?{position:"fixed",right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",left:"50%",transform:"translateX(-50%)",width:"max-content"};return oe?A.top="calc(100vh - 100px)":A.bottom="20px",A}const Tt=(()=>{if(re&&b)return{position:"fixed",left:`${Math.round(b.left)}px`,top:`${Math.round(b.top)}px`,width:"max-content",right:void 0,bottom:void 0,transform:void 0,touchAction:"none"};const A=yt();return re&&(A.touchAction="none"),A})();Je(()=>{re||(C(null),T(!1),k.current=null,W.current=!1,N.current&&(cancelAnimationFrame(N.current),N.current=null))},[re]);function ai(A,z,$){return Math.max(z,Math.min($,A))}function Fi(A){var ct;if(!re)return;const z=A.currentTarget;if(!z)return;const $=A.target;if((ct=$==null?void 0:$.closest)==null?void 0:ct.call($,'button, a[href], input, textarea, select, [role="button"], [contenteditable="true"], [data-no-drag]'))return;k.current=A.pointerId;const Be=z.getBoundingClientRect();x.current=A.clientX,_.current=A.clientY,R.current=Be.left,O.current=Be.top,B.current={width:Be.width,height:Be.height},W.current=!1,C({left:Be.left,top:Be.top})}function te(A){var Gi;if(!re||k.current!==A.pointerId)return;const z=A.clientX-x.current,$=A.clientY-_.current;if(!w){if(Math.hypot(z,$)<K)return;const Zt=A.currentTarget;try{(Gi=Zt==null?void 0:Zt.setPointerCapture)==null||Gi.call(Zt,A.pointerId)}catch{}T(!0),W.current=!0,b||C({left:R.current,top:O.current})}const ve=8,Be=ve,ct=ve,vt=Math.max(ve,window.innerWidth-B.current.width-ve),Vn=Math.max(ve,window.innerHeight-B.current.height-ve),Vi={left:ai(R.current+z,Be,vt),top:ai(O.current+$,ct,Vn)};if(N.current==null){const Ra=Vi;N.current=requestAnimationFrame(()=>{C(Ra),N.current=null})}else C(Vi)}function Ue(A){var z,$;if(k.current!==null)try{($=(z=A.currentTarget)==null?void 0:z.releasePointerCapture)==null||$.call(z,k.current)}catch{}k.current=null,T(!1)}function Qe(A){re&&k.current===A.pointerId&&Ue(A)}function Vt(A){re&&k.current===A.pointerId&&Ue(A)}const fn=()=>{const A=M.client;if(!A)return;const z=A.plans||[];if(z.length===1){const[$]=z;A.selectedPlanUuid!==$.uuid&&(A.selectPlan($),ii().track("course-get-started",{courseName:$.name,courseUuid:$.uuid})),t(!1),r(!0);return}t(!0)};return g("div",{children:[e&&g(Kx,{open:e,courses:M.client.plans.map((A,z)=>{var $,ve;return{id:A.uuid,name:A.name,description:A.description||"",duration:A.duration||0,completed:((ve=($=M.client)==null?void 0:$.planIsCompleted)==null?void 0:ve[z])||!1}}),loading:!1,title:((ji=M.client.product)==null?void 0:ji.assistant_subtitle)||void 0,productName:((jn=M.client.product)==null?void 0:jn.name)||"",onCourseHighlight:A=>{A&&ii().track("course-selected",{courseName:A.name,courseUuid:A.id})},onCourseSelect:A=>{const z=M.client.plans.find($=>$.uuid===A.id)||null;z&&(z==null?void 0:z.uuid)!==M.client.selectedPlanUuid&&(M.client.selectPlan(z),t(!1),r(!0),ii().track("course-get-started",{courseName:A.name,courseUuid:A.id}))},onClose:A=>{A==="user-initiated"&&M.client.selectPlan(null),t(!1)}}),ge&&g(nt,{children:[g("div",{className:re?`obi-widget-draggable${w?" dragging":""}`:void 0,style:Tt,onPointerDown:Fi,onPointerMove:te,onPointerUp:Qe,onPointerCancel:Vt,onClickCapture:A=>{var z,$;W.current&&((z=A.preventDefault)==null||z.call(A),($=A.stopPropagation)==null||$.call(A),W.current=!1)},children:g(sx,{inPlan:re,isActive:i?!1:d?!0:void 0,defaultIsActive:me!=="minimized",isPaused:J,toastMessage:l,messaging:(G==null?void 0:G.isMicShared)===!1||s?!0:void 0,speakingStatus:we,spectrum:()=>(G==null?void 0:G.audioSpectrum())||null,courseProgress:p,onOpen:fn,onCancelClick:()=>{var A,z,$;o&&(c(!1),(A=M.client.session)!=null&&A.isPaused||($=(z=M.client.session)==null?void 0:z.unmuteMicrophone)==null||$.call(z))},onCancelAbort:()=>{},onCancel:()=>{var A;(A=M.client.session)==null||A.stop()},onCancelReason:(A,z)=>{},onPause:()=>{var A,z;(z=(A=M.client.session)==null?void 0:A.pause)==null||z.call(A)},onUnpause:()=>{var A,z,$,ve;(z=(A=M.client.session)==null?void 0:A.unpause)==null||z.call(A),(o||s)&&((ve=($=M.client.session)==null?void 0:$.muteMicrophone)==null||ve.call($))},onMessagingChange:A=>{var z,$,ve,Be,ct;a(!1),c(A),A?($=(z=M.client.session)==null?void 0:z.muteMicrophone)==null||$.call(z):(ve=M.client.session)!=null&&ve.isPaused||(ct=(Be=M.client.session)==null?void 0:Be.unmuteMicrophone)==null||ct.call(Be)},onMessageChange:A=>{ii().track("chat-input-provided",{message:A,length:A.length})},onMessage:A=>{var z,$;M.say(A),a(!1),!o&&!(G!=null&&G.isPaused)&&(G==null?void 0:G.isMicShared)!==!1&&(($=(z=M.client.session)==null?void 0:z.unmuteMicrophone)==null||$.call(z)),ii().track("chat-message-sent",{message:A,length:A.length})},onHover:A=>{},onOneClickAction:A=>{a(!1)},onMinimize:()=>{var A,z,$;o&&(c(!1),(A=M.client.session)!=null&&A.isPaused||($=(z=M.client.session)==null?void 0:z.unmuteMicrophone)==null||$.call(z))},agentName:((pn=M.client.product)==null?void 0:pn.agent_name)||"Obi",completedTutorials:((mn=M.client.product)==null?void 0:mn.widget_show_progress)===!1?void 0:M.client.planIsCompleted.filter(Boolean).length,totalTutorials:((Pr=M.client.product)==null?void 0:Pr.widget_show_progress)===!1?void 0:M.client.plans.length})}),!!M.client.selectedPlan&&g(Yx,{open:!0,session:De(),sessionState:(G==null?void 0:G.state)||null,speakingState:(G==null?void 0:G.speakingState)||null,spectrum:()=>(G==null?void 0:G.audioSpectrum())||null,onModalChange:A=>{},onClose:(A,z)=>{var $,ve;A==="user-initiated"&&((($=M.client.session)==null?void 0:$.state)==="mic-share"?(ve=M.client.session)==null||ve.shareMicrophoneFailed():M.client.stopSession()),r(!1)},onStart:()=>{M.client.selectedPlanUuid&&M.startSession()},onContinue:()=>{G==null||G.continue()},onShareMicrophone:()=>{G==null||G.shareMicrophone()}})]})]})}function a_(n,e,t,i,r,s){const[a,o]=Y(0),[c,l]=Y(()=>{var p;return((p=n.client)==null?void 0:p.session)||null}),u=Ie(s),d=Ie(null),h=Ie(null);Je(()=>{u.current=s},[s]);const f=p=>{var v;(v=u.current)==null||v.call(u,p)},m=p=>{if(!p||d.current===p)return;h.current&&(h.current(),h.current=null);const v=()=>{o(R=>R+1)},b=()=>{o(R=>R+1)},C=()=>{o(R=>R+1)},w=()=>{o(R=>R+1)},T=R=>{},k=(R,O)=>{},x=()=>{r==null||r(!0),o(R=>R+1)},_=R=>{i(R)};p.on("stateChanged",v),p.on("speakingStateChanged",b),p.on("paused",C),p.on("unpaused",w),p.on("micCheckComplete",T),p.on("transcript",k),p.on&&p.on("textInputRequested",x),p.on&&p.on("courseProgress",_),d.current=p,h.current=()=>{p.off&&p.off("stateChanged",v),p.off&&p.off("speakingStateChanged",b),p.off&&p.off("paused",C),p.off&&p.off("unpaused",w),p.off&&p.off("micCheckComplete",T),p.off&&p.off("transcript",k),p.off&&p.off("courseProgress",_),p.off&&p.off("textInputRequested",x)}};return Je(()=>{const p=b=>{e(b)};n.on("showMenu",p);const v=()=>{o(b=>b+1)};return n.on("configUpdated",v),n.on("showMessage",f),()=>{var b,C,w;(b=n.off)==null||b.call(n,"showMenu",p),(C=n.off)==null||C.call(n,"configUpdated",v),(w=n.off)==null||w.call(n,"showMessage",f)}},[n]),Je(()=>{var p;n.client&&(n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((p=n.client.product)==null?void 0:p.primary_color)||"#9500FF"),n.client.session&&(l(n.client.session),m(n.client.session)),n.client.on("sessionStarted",v=>{l(v),r==null||r(!1),o(b=>b+1),m(v)}),n.client.on("sessionStopped",()=>{h.current&&(h.current(),h.current=null),d.current=null,l(null),r==null||r(!1),o(v=>v+1)}),n.client.on("sessionShutdown",()=>{o(v=>v+1)}),n.client.on("sessionResumed",()=>{o(v=>v+1)}),n.client.on("stateChanged",()=>{var v;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((v=n.client.product)==null?void 0:v.primary_color)||"#9500FF"),o(b=>b+1)}),n.client.on("planSelected",()=>{o(v=>v+1)}))},[n,n.client]),yr(()=>{if(c)return m(c),()=>{d.current===c&&h.current&&(h.current(),h.current=null,d.current=null)}},[c]),n}function o_(n){const[e,t]=Y(()=>ka(n));return Je(()=>{t(ka(n))},[n]),Je(()=>{c_();const i=()=>{t(ka(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 c_(){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 l_(n){if(document.querySelector("obi-widget"))return;u_();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(r_),t.adoptedStyleSheets=[r],S1(g(s_,{sdk:n,shadowHost:e}),i),console.log("[obi-sdk] widget mounted")}function u_(){Rm("https://fonts.cdnfonts.com/css/satoshi"),Rm("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function Rm(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const Pm="49206C6F7665204F6269_session",Im="obi-url-params";class d_ extends Ia{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,c;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 l=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!l){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,l);break;case"stopSession":(c=(o=this.client)==null?void 0:o.stopSession)==null||c.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=oa.deserialise(i,e,"sdk",{apiBaseUrl:"https://staging.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),localStorage.removeItem("obi-client")}t||(t=new oa(e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",r=>{var s,a,o,c,l,u,d,h,f,m;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:((c=(o=this.client)==null?void 0:o.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((l=window==null?void 0:window.obiWidgetConfig)==null?void 0:l.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)||((m=(f=this.client)==null?void 0:f.product)==null?void 0:m.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",()=>{localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(r,s)=>{}),this.client.session&&(this.client.session.isPaused,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()})}))}_maybeActOnServerEngagement(){var o;const e=this.client;if(!e||e.state!=="ready")return;const t=e.product,i=(o=e.engagement)==null?void 0:o.style;if(!i||t&&ka(t.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],s=e.planIsCompleted||[],a=r.length>0&&s.filter(Boolean).length===r.length;if(!(r.length===0||a)){if(i==="modal"){const c=s.findIndex(u=>!u),l=c>=0?r[c]:null;l&&e.selectPlan(l)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{ii().track("engagement-prompt-shown",{style:i})}catch{}}}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");try{this._maybeActOnServerEngagement()}catch{}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");try{this._maybeActOnServerEngagement()}catch{}}).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");try{this._maybeActOnServerEngagement()}catch{}}).catch(s=>{console.error("[obi] error initialising client",s),this.emit("error",s)}),e!=null&&e.email&&ii().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()}),e.on("paused",()=>{this.save()}),e.on("unpaused",()=>{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(Im)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((s,a)=>{e[a]=s});const t=e[Pm];if(!t)return null;const i=new URL(window.location.href);i.searchParams.delete(Pm),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Im),this.passivePlanUuid=t}mountWidget(){l_(this)}showMessage(e,t){try{this.emit("showMessage",{text:e,autoCloseMs:t==null?void 0:t.autoCloseMs})}catch{}}async captureScreen(){try{await Dw(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await i_(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 RT(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 Om(n,e){let t;try{t=window}catch{console.warn("[obi] no window object found"),t={}}return h_({appToken:n,window:t,init:e})}async function h_({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 d_(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function Am(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Om(void 0,Am)}):Om(void 0,Am)})();
|