obi-sdk 0.19.57-beta.2 → 0.19.57-beta.4

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.
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const a=r.sdp.split(`
39
39
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
40
40
  `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:a}):r.sdp=a}return n.apply(this,arguments)}}function fh(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ph(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.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"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var p8=Object.freeze({__proto__:null,removeExtmapAllowMixed:qm,shimAddIceCandidateNullOrEmpty:fh,shimConnectionState:Fm,shimMaxMessageSize:dh,shimParameterlessSetLocalDescription:ph,shimRTCIceCandidate:uh,shimRTCIceCandidateRelayProtocol:zm,shimSendThrowTypeError:hh});function m8(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Ex,i=u8(t),r={browserDetails:i,commonShim:p8,extractVersion:vc,disableLog:l8,disableWarnings:c8,sdp:f8};switch(i.browser){case"chrome":if(!zx||!jm||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=zx,fh(t,i),ph(t),Mx(t,i),Dx(t),jm(t,i),Px(t),Bx(t,i),Lx(t),Ix(t),Ux(t,i),uh(t),zm(t),Fm(t),dh(t,i),hh(t),qm(t,i);break;case"firefox":if(!Jx||!Bm||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Jx,fh(t,i),ph(t),Fx(t,i),Bm(t,i),qx(t),Gx(t),Hx(t),Vx(t),Wx(t),Yx(t),Kx(t),Xx(t),$x(t),uh(t),Fm(t),dh(t,i),hh(t);break;case"safari":if(!sS||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=sS,fh(t,i),ph(t),iS(t),aS(t),eS(t),Qx(t),Zx(t),rS(t),tS(t),oS(t),uh(t),zm(t),dh(t,i),hh(t),qm(t,i);break;default:n("Unsupported browser!");break}return r}m8({window:typeof window>"u"?void 0:window});const g8=/version\/(\d+(\.?_?\d+)+)/i;let Hm;function ui(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof t>"u"&&typeof navigator>"u")return;const n=(t??navigator.userAgent).toLowerCase();if(Hm===void 0||e){const i=v8.find(r=>{let{test:a}=r;return a.test(n)});Hm=i==null?void 0:i.describe(n)}return Hm}const v8=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:mh(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Vm(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:mh(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Vm(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:mh(g8,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:Vm(t)}}}];function mh(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function Vm(t){return t.includes("mac os")?mh(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var b8="2.16.1";const y8=b8,_8=16;class Dr extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var kt;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout",t[t.WebSocket=6]="WebSocket"})(kt||(kt={}));class _e extends Dr{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=kt[n]}static notAllowed(e,n,i){return new _e(e,kt.NotAllowed,n,i)}static timeout(e){return new _e(e,kt.Timeout)}static leaveRequest(e,n){return new _e(e,kt.LeaveRequest,void 0,n)}static internal(e,n){return new _e(e,kt.InternalError,void 0,n)}static cancelled(e){return new _e(e,kt.Cancelled)}static serverUnreachable(e,n){return new _e(e,kt.ServerUnreachable,n)}static websocket(e,n,i){return new _e(e,kt.WebSocket,n,i)}}class Gm extends Dr{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class na extends Dr{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class x8 extends Dr{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class on extends Dr{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Wm extends Dr{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class uS extends Dr{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class dS extends Dr{constructor(e,n){super(15,e),this.name="SignalRequestError",this.reason=n,this.reasonName=typeof n=="string"?n:Dm[n]}}var Yn;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",t[t.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(Yn||(Yn={}));class Fi extends Dr{constructor(e,n){super(16,e),this.name="DataStreamError",this.reason=n,this.reasonName=Yn[n]}}class Us extends Dr{constructor(e){super(18,e),this.name="SignalReconnectError"}}var gh;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(gh||(gh={})),function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e}(gh||(gh={}));class wn{}wn.setTimeout=function(){return setTimeout(...arguments)},wn.setInterval=function(){return setInterval(...arguments)},wn.clearTimeout=function(){return clearTimeout(...arguments)},wn.clearInterval=function(){return clearInterval(...arguments)};var J;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(J||(J={}));var oe;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(oe||(oe={}));var re;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(re||(re={}));var ee;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(ee||(ee={}));function S8(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}class dt{constructor(e,n,i,r,a){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:a};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const k8=["vp8","h264"],T8=["vp8","h264","vp9","av1","h265"];function w8(t){return!!k8.find(e=>e===t)}const C8=w8;var hS;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(hS||(hS={}));var Ym;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(Ym||(Ym={}));const bc={h90:new dt(160,90,9e4,20),h180:new dt(320,180,16e4,20),h216:new dt(384,216,18e4,20),h360:new dt(640,360,45e4,20),h540:new dt(960,540,8e5,25),h720:new dt(1280,720,17e5,30),h1080:new dt(1920,1080,3e6,30),h1440:new dt(2560,1440,5e6,30),h2160:new dt(3840,2160,8e6,30)},Km={h120:new dt(160,120,7e4,20),h180:new dt(240,180,125e3,20),h240:new dt(320,240,14e4,20),h360:new dt(480,360,33e4,20),h480:new dt(640,480,5e5,20),h540:new dt(720,540,6e5,25),h720:new dt(960,720,13e5,30),h1080:new dt(1440,1080,23e5,30),h1440:new dt(1920,1440,38e5,30)},Xm={h360fps3:new dt(640,360,2e5,3,"medium"),h360fps15:new dt(640,360,4e5,15,"medium"),h720fps5:new dt(1280,720,8e5,5,"medium"),h720fps15:new dt(1280,720,15e5,15,"medium"),h720fps30:new dt(1280,720,2e6,30,"medium"),h1080fps15:new dt(1920,1080,25e5,15,"medium"),h1080fps30:new dt(1920,1080,5e6,30,"medium"),original:new dt(0,0,7e6,30,"medium")};function fS(t,e,n){var i,r,a,o;const{optionsWithoutProcessor:s,audioProcessor:l,videoProcessor:c}=gS(t??{}),u=e==null?void 0:e.processor,d=n==null?void 0:n.processor,h=s??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&($m(h.audio,e),(i=(a=h.audio).deviceId)!==null&&i!==void 0||(a.deviceId={ideal:"default"}),(l||u)&&(h.audio.processor=l??u)),h.video&&($m(h.video,n),(r=(o=h.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(c||d)&&(h.video.processor=c??d)),h}function $m(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function Jm(t){var e,n,i,r;const a={};if(t.video)if(typeof t.video=="object"){const o={},s=o,l=t.video;Object.keys(l).forEach(c=>{switch(c){case"resolution":$m(s,l.resolution);break;default:s[c]=l[c]}}),a.video=o,(e=(i=a.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else a.video=t.video?{deviceId:{ideal:"default"}}:!1;else a.video=!1;return t.audio?typeof t.audio=="object"?(a.audio=t.audio,(n=(r=a.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):a.audio={deviceId:{ideal:"default"}}:a.audio=!1,a}function pS(t){return E(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=mS();if(i){const r=i.createAnalyser();r.fftSize=2048;const a=r.frequencyBinCount,o=new Uint8Array(a);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Cn(n),r.getByteTimeDomainData(o);const l=o.some(c=>c!==128&&c!==0);return i.close(),!l}return!1}()})}function mS(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>E(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(a){console.warn("Error trying to auto-resume audio context",a)}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)}});n.addEventListener("statechange",()=>{var r;n.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return n}}function E8(t){return t==="audioinput"?H.Source.Microphone:t==="videoinput"?H.Source.Camera:H.Source.Unknown}function Qm(t){return t===H.Source.Microphone?"audioinput":t===H.Source.Camera?"videoinput":void 0}function R8(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,$o()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function yc(t){return t.split("/")[1].toLowerCase()}function A8(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new Rm({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function je(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?je(t.track):{})}}function N8(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function O8(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const a of i)t[a]!==e[a]&&(r[a]=(n=e[a])!==null&&n!==void 0?n:"");return r}function gS(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=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:n,videoProcessor:i,optionsWithoutProcessor:S8(e)}}function M8(t){switch(t){case Xt.CAMERA:return H.Source.Camera;case Xt.MICROPHONE:return H.Source.Microphone;case Xt.SCREEN_SHARE:return H.Source.ScreenShare;case Xt.SCREEN_SHARE_AUDIO:return H.Source.ScreenShareAudio;default:return H.Source.Unknown}}function vS(t,e){return t.width*t.height<e.width*e.height}function D8(t,e){var n;return(n=t.layers)===null||n===void 0?void 0:n.find(i=>i.quality===e)}const P8=5e3,_c=[];var wi;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(wi||(wi={}));class H extends Mr.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=H.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ee,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),P8):this.handleAppVisibilityChanged()},this.log=ea((r=i.loggerName)!==null&&r!==void 0?r:cr.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=H.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),je(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===H.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===H.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(_c.forEach(a=>{a.parentElement===null&&!e&&(e=a)}),e&&_c.splice(_c.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),zs(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(a=>a.kind==="audio");return e.play().then(()=>{this.emit(r?ee.AudioPlaybackStarted:ee.VideoPlaybackStarted)}).catch(a=>{a.name==="NotAllowedError"?this.emit(r?ee.AudioPlaybackFailed:ee.VideoPlaybackFailed,a):a.name==="AbortError"?Ee.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Ee.warn("could not playback ".concat(r?"audio":"video"),a),r&&e&&i.some(o=>o.kind==="video")&&a.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(ee.ElementAttached,e),e}detach(e){try{if(e){Fs(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(ee.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Fs(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(ee.ElementDetached,i)}),this.attachedElements=[],n}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=ea(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),_c.forEach(i=>{i.parentElement||(n=!1)}),n&&_c.push(e)}}handleAppVisibilityChanged(){return E(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===H.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){di()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){di()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function zs(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!$o()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,($o()||Xo())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Fs(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(c){switch(c){case e.Audio:return or.AUDIO;case e.Video:return or.VIDEO;default:return or.DATA}}t.kindToProto=r;function a(c){switch(c){case or.AUDIO:return e.Audio;case or.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=a;function o(c){switch(c){case n.Camera:return Xt.CAMERA;case n.Microphone:return Xt.MICROPHONE;case n.ScreenShare:return Xt.SCREEN_SHARE;case n.ScreenShareAudio:return Xt.SCREEN_SHARE_AUDIO;default:return Xt.UNKNOWN}}t.sourceToProto=o;function s(c){switch(c){case Xt.CAMERA:return n.Camera;case Xt.MICROPHONE:return n.Microphone;case Xt.SCREEN_SHARE:return n.ScreenShare;case Xt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=s;function l(c){switch(c){case Cm.ACTIVE:return i.Active;case Cm.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=l})(H||(H={}));const L8="|",bS="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function I8(t){const e=t.split(L8);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function Cn(t){return E(this,void 0,void 0,function*(){return new Promise(e=>wn.setTimeout(e,t))})}function Zm(){return"addTransceiver"in RTCPeerConnection.prototype}function eg(){return"addTrack"in RTCPeerConnection.prototype}function j8(){if(!("getCapabilities"in RTCRtpSender)||$o()||Xo())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function B8(){if(!("getCapabilities"in RTCRtpSender)||Xo())return!1;if($o()){const n=ui();if(n!=null&&n.version&&Lr(n.version,"16")<0||(n==null?void 0:n.os)==="iOS"&&(n!=null&&n.osVersion)&&Lr(n.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function ur(t){return t==="av1"||t==="vp9"}function tg(t){return!document||xc()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function U8(){return typeof RTCPeerConnection>"u"?!1:Zm()||eg()}function Xo(){var t;return((t=ui())===null||t===void 0?void 0:t.name)==="Firefox"}function yS(){const t=ui();return!!t&&t.name==="Chrome"&&t.os!=="iOS"}function $o(){var t;return((t=ui())===null||t===void 0?void 0:t.name)==="Safari"}function xc(){const t=ui();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function z8(){const t=ui();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Lr(t.osVersion,"17")>=0}function F8(t){return t||(t=ui()),(t==null?void 0:t.name)==="Safari"&&Lr(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Lr(t.osVersion,"18.3")>0}function _S(){var t,e;return di()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function q8(){const t=ui(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&Lr(t.osVersion,e)>=0?!0:t.name==="Safari"&&Lr(t.version,e)>=0}function di(){return typeof document<"u"}function Pr(){return navigator.product=="ReactNative"}function qs(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function ng(t){return qs(t)?t.hostname.split(".")[0]:null}function xS(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function SS(){if(!Pr())return;let t=xS();if(t)return t.platform}function kS(){if(di())return window.devicePixelRatio;if(Pr()){let t=xS();if(t)return t.devicePixelRatio}return 1}function Lr(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let a=0;a<r;++a){const o=parseInt(n[a],10),s=parseInt(i[a],10);if(o>s)return 1;if(o<s)return-1;if(a===r-1&&o===s)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function H8(t){for(const e of t)e.target.handleResize(e)}function V8(t){for(const e of t)e.target.handleVisibilityChanged(e)}let ig=null;const TS=()=>(ig||(ig=new ResizeObserver(H8)),ig);let rg=null;const wS=()=>(rg||(rg=new IntersectionObserver(V8,{root:null,rootMargin:"0px"})),rg);function G8(){var t;const e=new rx({sdk:ax.JS,protocol:_8,version:y8});return Pr()&&(e.os=(t=SS())!==null&&t!==void 0?t:""),e}function CS(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=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=t,r.height=e;const a=r.getContext("2d");a==null||a.fillRect(0,0,r.width,r.height),i&&a&&(a.beginPath(),a.arc(t/2,e/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle="grey",a.fill());const o=r.captureStream(),[s]=o.getTracks();if(!s)throw Error("Could not get empty media stream video track");return s.enabled=n,s}let Sc;function ag(){if(!Sc){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[Sc]=i.stream.getAudioTracks(),!Sc)throw Error("Could not get empty media stream audio track");Sc.enabled=!1}return Sc.clone()}class qi{get isResolved(){return this._isResolved}constructor(e,n){this._isResolved=!1,this.onFinally=n,this.promise=new Promise((i,r)=>E(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function W8(t){return T8.includes(t)}function Ha(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Y8(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function kc(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function K8(t,e){return t.segments.map(n=>{let{id:i,text:r,language:a,startTime:o,endTime:s,final:l}=n;var c;const u=(c=e.get(i))!==null&&c!==void 0?c:Date.now(),d=Date.now();return l?e.delete(i):e.set(i,u),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(s.toString()),final:l,language:a,firstReceivedTime:u,lastReceivedTime:d}})}function X8(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function ES(t){switch(t.reason){case kt.LeaveRequest:return t.context;case kt.Cancelled:return sr.CLIENT_INITIATED;case kt.NotAllowed:return sr.USER_REJECTED;case kt.ServerUnreachable:return sr.JOIN_FAILURE;default:return sr.UNKNOWN_REASON}}function vh(t){return t!==void 0?Number(t):void 0}function Jo(t){return t!==void 0?BigInt(t):void 0}function Hs(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Ir(t){return!!t&&t.kind==H.Kind.Audio}function Va(t){return!!t&&t.kind==H.Kind.Video}function Ga(t){return Hs(t)&&Va(t)}function ia(t){return Hs(t)&&Ir(t)}function og(t){return!!t&&!t.isLocal}function $8(t){return!!t&&!t.isLocal}function sg(t){return og(t)&&Va(t)}function J8(t){return t.isLocal}function Q8(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const a=i[r];if(a!==void 0&&(a&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function Z8(t){var e;const n=t.get("Cache-Control");if(n){const i=(e=n.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function eD(t,e){const n=new URL(Y8(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),AS(n,"rtc")}function tD(t){const e=new URL(kc(t));return AS(e,"validate")}function RS(t){return t.endsWith("/")?t:"".concat(t,"/")}function AS(t,e){return t.pathname="".concat(RS(t.pathname)).concat(e),t.toString()}function NS(t){if(typeof t=="string")return dx.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return dx.fromBinary(new Uint8Array(t));throw new Error("could not decode websocket message: ".concat(typeof t))}function nD(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(t instanceof AbortSignal))return e;const n=t.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:e;default:return"toString"in n?n.toString():e}}const iD=10,Tc="lk_e2ee",rD={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:iD,keyringSize:16};var Wa;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(Wa||(Wa={}));var OS;(function(t){t.KeyRatcheted="keyRatcheted"})(OS||(OS={}));var Ya;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(Ya||(Ya={}));var MS;(function(t){t.Error="cryptorError"})(MS||(MS={}));function aD(){return oD()||lg()}function lg(){return typeof window.RTCRtpScriptTransform<"u"}function oD(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function sD(t){var e,n,i,r,a;if(((e=t.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((n=t.value)===null||n===void 0?void 0:n.case)!=="metrics"&&((i=t.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((r=t.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((a=t.value)===null||a===void 0?void 0:a.case)!=="encryptedPacket")return new J_({value:t.value})}class xW extends Mr.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{Ee.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},rD),e),this.on(Wa.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(Wa.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(Wa.RatchetRequest,e,n)}}var DS;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(DS||(DS={}));class lD extends Mr.EventEmitter{constructor(e,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var r,a;const{kind:o,data:s}=i.data;switch(o){case"error":if(Ee.error(s.error.message),s.uuid){const u=this.decryptDataRequests.get(s.uuid);if(u!=null&&u.reject){u.reject(s.error);break}const d=this.encryptDataRequests.get(s.uuid);if(d!=null&&d.reject){d.reject(s.error);break}}this.emit(Ya.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(Ya.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const u=(a=this.room)===null||a===void 0?void 0:a.getParticipantByIdentity(s.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(Ya.ParticipantEncryptionStatusChanged,s.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(Wa.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const l=this.decryptDataRequests.get(s.uuid);l!=null&&l.resolve&&l.resolve(s);break;case"encryptDataResponse":const c=this.encryptDataRequests.get(s.uuid);c!=null&&c.resolve&&c.resolve(s);break}},this.onWorkerError=i=>{Ee.error("e2ee worker encountered an error:",{error:i.error}),this.emit(Ya.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=n}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!aD())throw new Gm("tried to setup end-to-end encryption on an unsupported browser");if(Ee.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:i8.getLevel()}};this.worker&&(Ee.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){Ee.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?Ee.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(re.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(J.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==an.NONE,r.identity)),e.on(J.ConnectionStateChanged,i=>{i===Xe.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{this.setParticipantCryptorEnabled(a.trackInfo.encryption!==an.NONE,r.identity)})})}).on(J.TrackUnsubscribed,(i,r,a)=>{var o;const s={kind:"removeTransform",data:{participantIdentity:a.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(s)}).on(J.TrackSubscribed,(i,r,a)=>{this.setupE2EEReceiver(i,a.identity,r.trackInfo)}).on(J.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(oe.LocalSenderCreated,(i,r)=>E(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(oe.LocalTrackPublished,i=>{if(!Va(i.track)||!xc())return;const r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:yc(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r)}),n.on(Wa.SetKey,i=>this.postKey(i)).on(Wa.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return E(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const n=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:n,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new qi;return r.onFinally=()=>{this.encryptDataRequests.delete(n)},this.encryptDataRequests.set(n,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,n,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const a=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:a,payload:e,iv:n,participantIdentity:i,keyIndex:r}},s=new qi;return s.onFinally=()=>{this.decryptDataRequests.delete(a)},this.decryptDataRequests.set(a,s),this.worker.postMessage(o),s.promise}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.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 n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,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,n,e.kind==="video"?yc(i.mimeType):void 0)}}setupE2EESender(e,n){if(!Hs(e)||!n){n||Ee.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return E(this,void 0,void 0,function*(){if(this.worker){if(lg()&&!yS()){const a={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(Tc in e&&r){const l={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(l);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const l=e.createEncodedStreams();e.writableStream=l.writable,a=l.writable,e.readableStream=l.readable,o=l.readable}const s={kind:"decode",data:{readableStream:o,writableStream:a,trackId:n,codec:r,participantIdentity:i,isReuse:Tc in e}};this.worker.postMessage(s,[o,a])}e[Tc]=!0}})}handleSender(e,n,i){var r;if(!(Tc 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(lg()&&!yS()){Ee.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{Ee.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[a.readable,a.writable])}e[Tc]=!0}}}const cD=500,uD=15e3;class Vs{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Vs),this._instance}addFailedConnectionAttempt(e){var n;const i=new URL(e),r=ng(i);if(!r)return;let a=(n=this.failedConnectionAttempts.get(r))!==null&&n!==void 0?n:0;this.failedConnectionAttempts.set(r,a+1),this.backOffPromises.set(r,Cn(Math.min(cD*Math.pow(2,a),uD)))}getBackOffPromise(e){const n=new URL(e),i=n&&ng(n);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const n=new URL(e),i=n&&ng(n);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Vs._instance=null;const cg="default";class hn{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new hn),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a;if(((a=hn.userMediaPromiseMap)===null||a===void 0?void 0:a.size)>0){Ee.debug("awaiting getUserMedia promise");try{n?yield hn.userMediaPromiseMap.get(n):yield Promise.all(hn.userMediaPromiseMap.values())}catch{Ee.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!($o()&&i.hasDeviceInUse(n))&&(o.filter(l=>l.kind===n).length===0||o.some(l=>{const c=l.label==="",u=n?l.kind===n:!0;return c&&u}))){const l={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(l);o=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=o,n&&(o=o.filter(s=>s.kind===n)),o}()})}normalizeDeviceId(e,n,i){return E(this,void 0,void 0,function*(){if(n!==cg)return n;const r=yield this.getDevices(e),a=r.find(s=>s.deviceId===cg);if(!a){Ee.warn("could not reliably determine default device");return}const o=r.find(s=>s.deviceId!==cg&&s.groupId===(i??a.groupId));if(!o){Ee.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?hn.userMediaPromiseMap.has(e):hn.userMediaPromiseMap.size>0}}hn.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],hn.userMediaPromiseMap=new Map;var wc;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(wc||(wc={}));class dD{constructor(){this.pendingTasks=new Map,this.taskMutex=new Gn,this.nextTaskIndex=0}run(e){return E(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:wc.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=wc.RUNNING,yield e()}finally{n.status=wc.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return E(this,void 0,void 0,function*(){return this.run(()=>E(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class hD{get readyState(){return this.ws.readyState}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r;if(!((i=n.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const a=new WebSocket(e,(r=n.protocols)!==null&&r!==void 0?r:[]);a.binaryType="arraybuffer",this.ws=a;const o=function(){let{closeCode:s,reason:l}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return a.close(s,l)};this.opened=new Promise((s,l)=>{a.onopen=()=>{s({readable:new ReadableStream({start(c){a.onmessage=u=>{let{data:d}=u;return c.enqueue(d)},a.onerror=u=>c.error(u)},cancel:o}),writable:new WritableStream({write(c){a.send(c)},abort(){a.close()},close:o}),protocol:a.protocol,extensions:a.extensions}),a.removeEventListener("error",l)},a.addEventListener("error",l)}),this.closed=new Promise((s,l)=>{const c=()=>E(this,void 0,void 0,function*(){const u=new Promise(h=>{a.readyState!==WebSocket.CLOSED&&a.addEventListener("close",p=>{h(p)},{once:!0})}),d=yield Promise.race([Cn(250),u]);d?s(d):l(new Error("Encountered unspecified websocket error without a timely close event"))});a.onclose=u=>{let{code:d,reason:h}=u;s({closeCode:d,reason:h}),a.removeEventListener("error",c)},a.addEventListener("error",c)}),n.signal&&(n.signal.onabort=()=>a.close()),this.close=o}}const fD=["syncState","trickle","offer","answer","simulate","leave"];function pD(t){const e=fD.indexOf(t.case)>=0;return Ee.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var mt;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(mt||(mt={}));const mD=250;class ug{get currentState(){return this.state}get isDisconnected(){return this.state===mt.DISCONNECTING||this.state===mt.DISCONNECTED}get isEstablishingConnection(){return this.state===mt.CONNECTING||this.state===mt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=mt.DISCONNECTED,this.log=Ee,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.onMediaSectionsRequirement=void 0},this.log=ea((i=n.loggerName)!==null&&i!==void 0?i:cr.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new dD,this.queuedRequests=[],this.closingLock=new Gn,this.connectionLock=new Gn,this.state=mt.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return E(this,void 0,void 0,function*(){return this.state=mt.CONNECTING,this.options=i,yield this.connect(e,n,i,r)})}reconnect(e,n,i,r){return E(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=mt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,n,i,r){return E(this,void 0,void 0,function*(){const a=yield this.connectionLock.lock();this.connectOptions=i;const o=G8(),s=i.singlePeerConnection?vD(n,o,i):gD(n,o,i),l=eD(e,s),c=tD(l);return new Promise((u,d)=>E(this,void 0,void 0,function*(){var h,p;try{let b=!1;const m=v=>E(this,void 0,void 0,function*(){if(b)return;b=!0;const k=v instanceof Event?v.currentTarget:v,T=nD(k,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(T)).catch(C=>{this.log.error(C),this.close()}):this.close(),S(),d(_e.cancelled(T))});r==null||r.addEventListener("abort",m);const S=()=>{clearTimeout(g),r==null||r.removeEventListener("abort",m)},g=setTimeout(()=>{m(_e.timeout("room connection has timed out (signal)"))},i.websocketTimeout),y=(v,k)=>{this.handleSignalConnected(v,g,k)},x=new URL(l);x.searchParams.has("access_token")&&x.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(x),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new hD(l);try{this.ws.closed.then(N=>{var O;this.isEstablishingConnection&&d(_e.internal("Websocket got closed during a (re)connection attempt: ".concat(N.reason))),N.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:N.reason,code:N.closeCode,wasClean:N.closeCode===1e3,state:this.state})),this.state===mt.CONNECTED&&this.handleOnClose((O=N.reason)!==null&&O!==void 0?O:"Unexpected WS error"))}).catch(N=>{this.isEstablishingConnection&&d(_e.internal("Websocket error during a (re)connection attempt: ".concat(N)))});const v=yield this.ws.opened.catch(N=>E(this,void 0,void 0,function*(){if(this.state!==mt.CONNECTED){this.state=mt.DISCONNECTED,clearTimeout(g);const O=yield this.handleConnectionError(N,c);d(O);return}this.handleWSError(N),d(N)}));if(clearTimeout(g),!v)return;const k=v.readable.getReader();this.streamWriter=v.writable.getWriter();const T=yield k.read();if(k.releaseLock(),!T.value)throw _e.internal("no message received as first message");const C=NS(T.value),R=this.validateFirstMessage(C,(h=i.reconnect)!==null&&h!==void 0?h:!1);if(!R.isValid){d(R.error);return}((p=C.message)===null||p===void 0?void 0:p.case)==="join"&&(this.pingTimeoutDuration=C.message.value.pingTimeout,this.pingIntervalDuration=C.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const A=R.shouldProcessFirstMessage?C:void 0;y(v,A),u(R.response)}catch(v){d(v)}finally{S()}}finally{a()}}))})}startReadingLoop(e,n){return E(this,void 0,void 0,function*(){for(n&&this.handleSignalResponse(n);;){this.signalLatency&&(yield Cn(this.signalLatency));const{done:i,value:r}=yield e.read();if(i)break;const a=NS(r);this.handleSignalResponse(a)}})}close(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return function*(){if([mt.DISCONNECTING||mt.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=mt.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const a=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([a,Cn(mD)])}}catch(a){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:a}))}finally{n&&(e.state=mt.DISCONNECTED),r()}}()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Gs(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Gs(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ih({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new rh({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const s=a.getNextRequestId();return yield a.sendRequest({case:"updateMetadata",value:new Nm({requestId:s,metadata:i,name:r,attributes:o})}),s}()})}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,n){return this.sendRequest({case:"updateLayers",value:new px({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new vx({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Nt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new _x({timestamp:Nt.parse(Date.now()),rtt:Nt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new Am({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new oh({reason:sr.CLIENT_INITIATED,action:js.DISCONNECT})})}sendRequest(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!pD(n)&&i.state===mt.RECONNECTING){i.queuedRequests.push(()=>E(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield Cn(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(n.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new RM({message:n});try{i.useJSON?yield i.streamWriter.write(o.toJsonString()):yield i.streamWriter.write(o.toBinary())}catch(s){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:s}))}}()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let a=!1;if(r.case==="answer"){const o=PS(r.value);this.onAnswer&&this.onAnswer(o,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const o=PS(r.value);this.onOffer&&this.onOffer(o,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):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(),a=!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)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(r.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));a||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return E(this,void 0,void 0,function*(){if(this.state===mt.DISCONNECTED)return;const n=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(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=wn.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&&wn.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=wn.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&wn.clearInterval(this.pingInterval)}handleSignalConnected(e,n,i){this.state=mt.CONNECTED,clearTimeout(n),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,n){var i,r,a,o,s;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===mt.RECONNECTING&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((a=e.message)===null||a===void 0?void 0:a.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:_e.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:n?{isValid:!1,error:_e.internal("Unexpected first message")}:{isValid:!1,error:_e.internal("did not receive join response, got ".concat((s=e.message)===null||s===void 0?void 0:s.case," instead"))}}handleConnectionError(e,n){return E(this,void 0,void 0,function*(){try{const i=yield fetch(n);if(i.status.toFixed(0).startsWith("4")){const r=yield i.text();return _e.notAllowed(r,i.status)}else return e instanceof _e?e:_e.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof _e?i:_e.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function PS(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function Gs(t,e){return new qa({sdp:t.sdp,type:t.type,id:e})}function gD(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",Pr()?"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),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}function vD(t,e,n){const i=new URLSearchParams;i.set("access_token",t);const r=new $M({clientInfo:e,connectionSettings:new xx({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0});n.reconnectReason&&(r.reconnectReason=n.reconnectReason);const a=new JM({joinRequest:r.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(a.toBinary()))),i}class LS{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class bD{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,a]of i.entries())n.push(e(a,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var dr={},dg={},hg={exports:{}},IS;function fg(){if(IS)return hg.exports;IS=1;var t=hg.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 n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{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 n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{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 n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),hg.exports}var jS;function yD(){return jS||(jS=1,function(t){var e=function(s){return String(Number(s))===s?Number(s):s},n=function(s,l,c,u){if(u&&!c)l[u]=e(s[1]);else for(var d=0;d<c.length;d+=1)s[d+1]!=null&&(l[c[d]]=e(s[d+1]))},i=function(s,l,c){var u=s.name&&s.names;s.push&&!l[s.push]?l[s.push]=[]:u&&!l[s.name]&&(l[s.name]={});var d=s.push?{}:u?l[s.name]:l;n(c.match(s.reg),d,s.names,s.name),s.push&&l[s.push].push(d)},r=fg(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(s){var l={},c=[],u=l;return s.split(/(\r\n|\r|\n)/).filter(a).forEach(function(d){var h=d[0],p=d.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var b=0;b<(r[h]||[]).length;b+=1){var m=r[h][b];if(m.reg.test(p))return i(m,u,p)}}),l.media=c,l};var o=function(s,l){var c=l.split(/=(.+)/,2);return c.length===2?s[c[0]]=e(c[1]):c.length===1&&l.length>1&&(s[c[0]]=void 0),s};t.parseParams=function(s){return s.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(s){return s.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(s){for(var l=[],c=s.split(" ").map(e),u=0;u<c.length;u+=3)l.push({component:c[u],ip:c[u+1],port:c[u+2]});return l},t.parseImageAttributes=function(s){return s.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(s){return s.split(";").map(function(l){return l.split(",").map(function(c){var u,d=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),d=!0),{scid:u,paused:d}})})}}(dg)),dg}var pg,BS;function _D(){if(BS)return pg;BS=1;var t=fg(),e=/%[sdv%]/g,n=function(o){var s=1,l=arguments,c=l.length;return o.replace(e,function(u){if(s>=c)return u;var d=l[s];switch(s+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(o,s,l){var c=s.format instanceof Function?s.format(s.push?l:l[s.name]):s.format,u=[o+"="+c];if(s.names)for(var d=0;d<s.names.length;d+=1){var h=s.names[d];s.name?u.push(l[s.name][h]):u.push(l[s.names[d]])}else u.push(l[s.name]);return n.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];return pg=function(o,s){s=s||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var l=s.outerOrder||r,c=s.innerOrder||a,u=[];return l.forEach(function(d){t[d].forEach(function(h){h.name in o&&o[h.name]!=null?u.push(i(d,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(p){u.push(i(d,h,p))})})}),o.media.forEach(function(d){u.push(i("m",t.m[0],d)),c.forEach(function(h){t[h].forEach(function(p){p.name in d&&d[p.name]!=null?u.push(i(h,p,d)):p.push in d&&d[p.push]!=null&&d[p.push].forEach(function(b){u.push(i(h,p,b))})})})}),u.join(`\r
41
41
  `)+`\r
42
- `},pg}var US;function xD(){if(US)return dr;US=1;var t=yD(),e=_D(),n=fg();return dr.grammar=n,dr.write=e,dr.parse=t.parse,dr.parseParams=t.parseParams,dr.parseFmtpConfig=t.parseFmtpConfig,dr.parsePayloads=t.parsePayloads,dr.parseRemoteCandidates=t.parseRemoteCandidates,dr.parseImageAttributes=t.parseImageAttributes,dr.parseSimulcastStreamList=t.parseSimulcastStreamList,dr}var Ka=xD();function mg(t,e,n){var i,r,a;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,s=(r=n.callback)!=null&&r,l=n.maxWait,c=Date.now(),u=[];function d(){if(l!==void 0){var p=Date.now()-c;if(p+e>=l)return l-p}return e}var h=function(){var p=[].slice.call(arguments),b=this;return new Promise(function(m,S){var g=o&&a===void 0;if(a!==void 0&&clearTimeout(a),a=setTimeout(function(){if(a=void 0,c=Date.now(),!o){var x=t.apply(b,p);s&&s(x),u.forEach(function(v){return(0,v.resolve)(x)}),u=[]}},d()),g){var y=t.apply(b,p);return s&&s(y),m(y)}u.push({resolve:m,reject:S})})};return h.cancel=function(p){a!==void 0&&clearTimeout(a),u.forEach(function(b){return(0,b.reject)(p)}),u=[]},h}const SD=.7,kD=20,Ws={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class zS extends Mr.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Ee,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=mg(r=>E(this,void 0,void 0,function*(){this.emit(Ws.NegotiationStarted);try{yield this.createAndSendOffer()}catch(a){if(r)r(a);else throw a}}),kD),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=ea((i=n.loggerName)!==null&&i!==void 0?i:cr.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new Gn}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return E(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return E(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:a,nackMids:o}=TD(e);this.remoteStereoMids=a,this.remoteNackMids=o}else if(e.type==="answer"){const a=Ka.parse((i=e.sdp)!==null&&i!==void 0?i:"");a.media.forEach(o=>{const s=gg(o.mid);o.type==="audio"&&this.trackBitrates.some(l=>{if(!l.transceiver||s!=l.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===l.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let u=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),l.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(l.maxbr*1e3)),u=!0;break}return u||l.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(l.maxbr*1e3)}),!0})}),r=Ka.write(a)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Ws.NegotiationComplete),e.sdp&&Ka.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Ws.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{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 r=this.latestOfferId+1;this.latestOfferId=r;const a=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:a.sdp},this.logContext));const o=Ka.parse((n=a.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(s=>{qS(s),s.type==="audio"?FS(s,["all"],[]):s.type==="video"&&this.trackBitrates.some(l=>{if(!s.msid||!l.cid||!s.msid.includes(l.cid))return!1;let c=0;if(s.rtp.some(d=>d.codec.toUpperCase()===l.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(ur(l.codec)&&!$o()&&this.ensureVideoDDExtensionForSVC(s,o),!ur(l.codec)))return!0;const u=Math.round(l.maxbr*SD);for(const d of s.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(u));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(a,Ka.write(o)),this.onOffer(a,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return E(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=Ka.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{qS(r),r.type==="audio"&&FS(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Ka.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTransceiverOfKind(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new on("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new on("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}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 E(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(s=>{switch(s.type){case"transport":n=s.selectedCandidatePairId;break;case"candidate-pair":n===""&&s.selected&&(n=s.id),i.set(s.id,s);break;case"remote-candidate":r.set(s.id,"".concat(s.address,":").concat(s.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return E(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;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(a){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:a,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let a="unknown error";r instanceof Error?a=r.message:typeof r=="string"&&(a=r);const o={error:a,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Wm(a)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===bS))){if(this.ddExtID===0){let o=0;n.media.forEach(s=>{var l;s.type==="video"&&((l=s.ext)===null||l===void 0||l.forEach(c=>{c.value>o&&(o=c.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:bS})}}}function FS(t,e,n){const i=gg(t.mid);let r=0;t.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),r>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(i)&&!t.rtcpFb.some(a=>a.payload===r&&a.type==="nack")&&t.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&t.fmtp.some(a=>a.payload===r?(a.config.includes("stereo=1")||(a.config+=";stereo=1"),!0):!1))}function TD(t){var e;const n=[],i=[],r=Ka.parse((e=t.sdp)!==null&&e!==void 0?e:"");let a=0;return r.media.forEach(o=>{var s;const l=gg(o.mid);o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(a=c.payload,!0):!1),!((s=o.rtcpFb)===null||s===void 0)&&s.some(c=>c.payload===a&&c.type==="nack")&&i.push(l),o.fmtp.some(c=>c.payload===a?(c.config.includes("sprop-stereo=1")&&n.push(l),!0):!1))}),{stereoMids:n,nackMids:i}}function qS(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}function gg(t){return typeof t=="number"?t.toFixed(0):t}const vg="vp8",wD={audioPreset:Ym.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xm.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:vg,backupCodec:!0,preConnectBuffer:!1},HS={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},VS={deviceId:{ideal:"default"},resolution:bc.h720.resolution},CD={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new a8,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},bg={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Lt;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Lt||(Lt={}));class ED{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=bg.peerConnectionTimeout,this.log=Ee,this.updateState=()=>{var a,o;const s=this.state,l=this.requiredTransports.map(c=>c.getConnectionState());l.every(c=>c==="connected")?this.state=Lt.CONNECTED:l.some(c=>c==="failed")?this.state=Lt.FAILED:l.some(c=>c==="connecting")?this.state=Lt.CONNECTING:l.every(c=>c==="closed")?this.state=Lt.CLOSED:l.some(c=>c==="closed")?this.state=Lt.CLOSING:l.every(c=>c==="new")&&(this.state=Lt.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Lt[s]," to ").concat(Lt[this.state]),this.logContext),(a=this.onStateChange)===null||a===void 0||a.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=ea((r=i.loggerName)!==null&&r!==void 0?r:cr.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=n!=="subscriber-primary",this.isSubscriberConnectionRequired=n==="subscriber-primary",this.publisher=new zS(e,i),n!=="publisher-only"&&(this.subscriber=new zS(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=a=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,a,lr.SUBSCRIBER)},this.subscriber.onDataChannel=a=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,a)},this.subscriber.onTrack=a=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,a)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=a=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,a,lr.PUBLISHER)},this.publisher.onTrack=a=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,a)},this.publisher.onOffer=(a,o)=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,a,o)},this.state=Lt.NEW,this.connectionLock=new Gn,this.remoteOfferLock=new Gn}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return E(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const n=this.publisher;for(const i of n.getSenders())try{n.canRemoveTrack()&&n.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return E(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return E(this,void 0,void 0,function*(){var i;n===lr.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return E(this,void 0,void 0,function*(){var i,r,a;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,n))?yield(a=this.subscriber)===null||a===void 0?void 0:a.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,n){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return E(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(a=>this.ensureTransportConnected(a,e,n)))}finally{r()}})}negotiate(e){return E(this,void 0,void 0,function*(){return new Promise((n,i)=>E(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),a=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",a),this.publisher.once(Ws.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Ws.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTransceiverOfKind(e,n){return this.publisher.addTransceiverOfKind(e,n)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return i==null?void 0:i.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===lr.PUBLISHER?this.publisher.getConnectedAddress():e===lr.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((l,c)=>E(a,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),wn.clearTimeout(d),c(_e.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=wn.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(_e.internal("could not establish pc connection"))},o);for(;this.state!==Lt.CONNECTED;)if(yield Cn(50),r!=null&&r.signal.aborted){c(_e.cancelled("room connection has been cancelled"));return}wn.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}const GS=5e3,RD=3e4;class Ke{static fetchRegionSettings(e,n,i){return E(this,void 0,void 0,function*(){const r=yield Ke.fetchLock.lock();try{const a=yield fetch("".concat(AD(e),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(a.ok){const o=Z8(a.headers),s=o?o*1e3:GS;return{regionSettings:yield a.json(),updatedAtInMs:Date.now(),maxAgeInMs:s}}else throw a.status===401?_e.notAllowed("Could not fetch region settings: ".concat(a.statusText),a.status):_e.internal("Could not fetch region settings: ".concat(a.statusText))}catch(a){throw a instanceof _e?a:i!=null&&i.aborted?_e.cancelled("Region fetching was aborted"):_e.serverUnreachable("Could not fetch region settings, ".concat(a instanceof Error?"".concat(a.name,": ").concat(a.message):a))}finally{r()}})}static scheduleRefetch(e,n,i){return E(this,void 0,void 0,function*(){const r=Ke.settingsTimeouts.get(e.hostname);clearTimeout(r),Ke.settingsTimeouts.set(e.hostname,setTimeout(()=>E(this,void 0,void 0,function*(){try{const a=yield Ke.fetchRegionSettings(e,n);Ke.updateCachedRegionSettings(e,n,a)}catch(a){if(a instanceof _e&&a.reason===kt.NotAllowed){Ee.debug("token is not valid, cancelling auto region refresh");return}Ee.debug("auto refetching of region settings failed",{error:a}),Ke.scheduleRefetch(e,n,i)}}),i))})}static updateCachedRegionSettings(e,n,i){Ke.cache.set(e.hostname,i),Ke.scheduleRefetch(e,n,i.maxAgeInMs)}static stopRefetch(e){const n=Ke.settingsTimeouts.get(e);n&&(clearTimeout(n),Ke.settingsTimeouts.delete(e))}static scheduleCleanup(e){let n=Ke.connectionTrackers.get(e);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{const i=Ke.connectionTrackers.get(e);i&&i.connectionCount===0&&(Ee.debug("stopping region refetch after disconnect delay",{hostname:e}),Ke.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},RD))}static cancelCleanup(e){const n=Ke.connectionTrackers.get(e);n!=null&&n.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let n=Ke.connectionTrackers.get(e);n||(n={connectionCount:0},Ke.connectionTrackers.set(e,n)),n.connectionCount++,Ke.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,n=Ke.connectionTrackers.get(e);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&Ke.scheduleCleanup(e))}constructor(e,n){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return qs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return E(this,void 0,void 0,function*(){return Ke.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return E(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let n=Ke.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(e),Ke.updateCachedRegionSettings(this.serverUrl,this.token,n));const i=n.regionSettings.regions.filter(r=>!this.attemptedRegions.find(a=>a.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),Ee.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ke.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ke.cache=new Map,Ke.settingsTimeouts=new Map,Ke.connectionTrackers=new Map,Ke.fetchLock=new Gn;function AD(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class It extends Error{constructor(e,n,i){super(n),this.code=e,this.message=YS(n,It.MAX_MESSAGE_BYTES),this.data=i?YS(i,It.MAX_DATA_BYTES):void 0}static fromProto(e){return new It(e.code,e.message,e.data)}toProto(){return new ex({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new It(It.ErrorCode[e],It.ErrorMessage[e],n)}}It.MAX_MESSAGE_BYTES=256,It.MAX_DATA_BYTES=15360,It.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},It.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 WS=15360;function yg(t){return new TextEncoder().encode(t).length}function YS(t,e){if(yg(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const a=Math.floor((n+i+1)/2);r.encode(t.slice(0,a)).length<=e?n=a:i=a-1}return t.slice(0,n)}const _g=2e3;function bh(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const xg=typeof MediaRecorder<"u";class ND{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const OD=xg?MediaRecorder:ND;class MD extends OD{constructor(e,n){if(!xg)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const a=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),r==null||r.close(),r=void 0},s=l=>{r==null||r.error(l),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),r=void 0};this.byteStream=new ReadableStream({start:l=>{r=l,i=c=>E(this,void 0,void 0,function*(){let u;if(c.data.arrayBuffer){const d=yield c.data.arrayBuffer();u=new Uint8Array(d)}else if(c.data.byteArray)u=c.data.byteArray;else throw new Error("no data available!");a()||l.enqueue(u)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",s)}}function DD(){return xg}const PD=1e3,LD=1e4;class KS extends H{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,a=arguments.length>4?arguments[4]:void 0;super(e,n,a),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=mg(()=>E(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>E(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(ee.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Gn,this.pauseUpstreamLock=new Gn,this.trackChangeLock=new Gn,this.trackChangeLock.lock().then(o=>E(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==H.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return E(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Fs(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(zs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}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(a=>{zs(r??e,a)}))})}waitForDimensions(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:PD;return function*(){var i;if(e.kind===H.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ui())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Cn(10));const r=Date.now();for(;Date.now()-r<n;){const a=e.dimensions;if(a)return a;yield Cn(50)}throw new na("unable to get track dimensions after timeout")}()})}setDeviceId(e){return E(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ha(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ha(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===H.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),a=e.kind===H.Kind.Audio?"audioinput":"videoinput";return n?hn.getInstance().normalizeDeviceId(a,i,r):i}()})}mute(){return E(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return E(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return E(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new na("unable to replace an unpublished track");let r,a;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,a=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),a&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return E(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,a=o8(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===H.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?Object.assign({deviceId:i},a):!0,this.attachedElements.forEach(c=>{Fs(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===H.Kind.Video&&(yield l.applyConstraints(a)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l),this._constraints=e,this.emit(ee.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}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?ee.Muted:ee.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 E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),_S()&&(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 E(this,void 0,void 0,function*(){var e;const n=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(ee.UpstreamPaused,this);const i=ui();if((i==null?void 0:i.name)==="Safari"&&Lr(i.version,"12.0")<0)throw new Gm("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{n()}})}resumeUpstream(){return E(this,void 0,void 0,function*(){var e;const n=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(ee.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return E(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 E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const s=document.createElement(i.kind),l={kind:i.kind,track:i._mediaStreamTrack,element:s,audioContext:i.audioContext};if(yield n.init(l),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(zs(i._mediaStreamTrack,s),s.muted=!0,s.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{s.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))}),i.processor=n,i.processorElement=s,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Fs(i._mediaStreamTrack,c),zs(i.processor.processedTrack,c));yield(a=i.sender)===null||a===void 0?void 0:a.replaceTrack(i.processor.processedTrack)}i.emit(ee.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}}()})}internalStopProcessor(){return E(this,arguments,void 0,function(){var e=this;let n=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,n||((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(ee.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!DD()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new MD(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},LD)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class yh extends KS{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(e,H.Kind.Audio,n,i,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>E(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(s){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:s}));return}o&&this.prevStats&&(this._currentBitrate=bh(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ee.AudioTrackFeatureUpdate,this,dn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ee.AudioTrackFeatureUpdate,this,dn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===H.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return E(this,void 0,void 0,function*(){const n=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!==Ha(this._constraints.deviceId);return this.source===H.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{n()}})}restartTrack(e){return E(this,void 0,void 0,function*(){let n;if(e){const i=Jm({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return E(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){di()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},_g)))}setProcessor(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Pr()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());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(n=this.sender)===null||n===void 0?void 0:n.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(ee.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return E(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.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 E(this,void 0,void 0,function*(){const e=yield pS(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ee.AudioSilenceDetected)),e})}}function ID(t,e,n){switch(t.kind){case"audio":return new yh(t,e,!1,void 0,n);case"video":return new _h(t,e,!1,n);default:throw new na("unsupported track type: ".concat(t.kind))}}const jD=Object.values(bc),BD=Object.values(Km),UD=Object.values(Xm),zD=[bc.h180,bc.h360],FD=[Km.h180,Km.h360],qD=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new dt(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Sg=["q","h","f"];function kg(t,e,n,i){var r,a;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const s=i==null?void 0:i.simulcast,l=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!o&&!s&&!l||!e||!n)return[{}];o||(o=VD(t,e,n,c),Ee.debug("using video encoding",o));const u=o.maxFramerate,d=new dt(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(l&&ur(c)){const b=new JS(l),m=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const S=ui();if(xc()||Pr()||(S==null?void 0:S.name)==="Chrome"&&Lr(S==null?void 0:S.version,"113")<0){const g=b.suffix=="h"?2:3,y=F8(S);for(let x=0;x<b.spatial;x+=1)m.push({rid:Sg[2-x],maxBitrate:o.maxBitrate/Math.pow(g,x),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,x):void 0});m[0].scalabilityMode=l}else m.push({maxBitrate:o.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:l});return d.encoding.priority&&(m[0].priority=d.encoding.priority,m[0].networkPriority=d.encoding.priority),Ee.debug("using svc encoding",{encodings:m}),m}if(!s)return[o];let h=[];t?h=(r=$S(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:XS(t,d):h=(a=$S(i==null?void 0:i.videoSimulcastLayers))!==null&&a!==void 0?a:XS(t,d);let p;if(h.length>0){const b=h[0];h.length>1&&([,p]=h);const m=Math.max(e,n);if(m>=960&&p)return Tg(e,n,[b,p,d],u);if(m>=480)return Tg(e,n,[b,d],u)}return Tg(e,n,[d])}function HD(t,e,n){var i,r,a,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Ee.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const s=t.mediaStreamTrack.getSettings(),l=(i=s.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,c=(a=s.height)!==null&&a!==void 0?a:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===H.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),kg(t.source===H.Source.ScreenShare,l,c,n)}function VD(t,e,n,i){const r=GD(t,e,n);let{encoding:a}=r[0];const o=Math.max(e,n);for(let s=0;s<r.length;s+=1){const l=r[s];if(a=l.encoding,l.width>=o)break}if(i)switch(i){case"av1":case"h265":a=Object.assign({},a),a.maxBitrate=a.maxBitrate*.7;break;case"vp9":a=Object.assign({},a),a.maxBitrate=a.maxBitrate*.85;break}return a}function GD(t,e,n){if(t)return UD;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?jD:BD}function XS(t,e){if(t)return qD(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?zD:FD}function Tg(t,e,n,i){const r=[];if(n.forEach((a,o)=>{if(o>=Sg.length)return;const s=Math.min(t,e),c={rid:Sg[o],scaleResolutionDownBy:Math.max(1,s/Math.min(a.width,a.height)),maxBitrate:a.encoding.maxBitrate},u=i&&a.encoding.maxFramerate?Math.min(i,a.encoding.maxFramerate):a.encoding.maxFramerate;u&&(c.maxFramerate=u);const d=Xo()||o===0;a.encoding.priority&&d&&(c.priority=a.encoding.priority,c.networkPriority=a.encoding.priority),r.push(c)}),Pr()&&SS()==="ios"){let a;r.forEach(s=>{a?s.maxFramerate&&s.maxFramerate>a&&(a=s.maxFramerate):a=s.maxFramerate});let o=!0;r.forEach(s=>{var l;s.maxFramerate!=a&&(o&&(o=!1,Ee.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ee.info('Setting framerate of encoding "'.concat((l=s.rid)!==null&&l!==void 0?l:"",'" to ').concat(a)),s.maxFramerate=a)})}return r}function $S(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;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 JS{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function WD(t){return t.source===H.Source.ScreenShare||t.constraints.height&&Ha(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const YD=5e3;class _h extends KS{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,H.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>E(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(l){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:l}));return}const o=new Map(a.map(l=>[l.rid,l])),s=a.some(l=>l.qualityLimitationReason==="cpu");if(s!==this.isCpuConstrained&&(this.isCpuConstrained=s,this.isCpuConstrained&&this.emit(ee.CpuConstrained)),this.prevStats){let l=0;o.forEach((c,u)=>{var d;const h=(d=this.prevStats)===null||d===void 0?void 0:d.get(u);l+=bh(c,h)}),this._currentBitrate=l}this.prevStats=o}),this.senderLock=new Gn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!di())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},_g))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return E(this,void 0,void 0,function*(){var n,i,r,a,o;yield e.pauseUpstream.call(this);try{for(var s=!0,l=ta(this.simulcastCodecs.values()),c;c=yield l.next(),n=c.done,!n;s=!0)a=c.value,s=!1,yield(o=a.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(u){i={error:u}}finally{try{!s&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return E(this,void 0,void 0,function*(){var n,i,r,a,o;yield e.resumeUpstream.call(this);try{for(var s=!0,l=ta(this.simulcastCodecs.values()),c;c=yield l.next(),n=c.done,!n;s=!0){a=c.value,s=!1;const u=a;yield(o=u.sender)===null||o===void 0?void 0:o.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!s&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===H.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===H.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{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return E(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var a;if(r.type==="outbound-rtp"){const o={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:(a=r.rid)!==null&&a!==void 0?a:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},s=i.get(r.remoteId);s&&(o.jitter=s.jitter,o.packetsLost=s.packetsLost,o.roundTripTime=s.roundTripTime),n.push(o)}}),n.sort((r,a)=>{var o,s;return((o=a.frameWidth)!==null&&o!==void 0?o:0)-((s=r.frameWidth)!==null&&s!==void 0?s:0)}),n})}setPublishingQuality(e){const n=[];for(let i=wi.LOW;i<=wi.HIGH;i+=1)n.push(new Om({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ur(this.codec),n)}restartTrack(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o;let s;if(e){const d=Jm({video:e});typeof d.video!="boolean"&&(s=d.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var l=!0,c=ta(this.simulcastCodecs.values()),u;u=yield c.next(),n=u.done,!n;l=!0){a=u.value,l=!1;const d=a;d.sender&&((o=d.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!l&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return E(this,arguments,void 0,function(i){var r=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,s,l,c,u,d;if(yield n.setProcessor.call(r,i,a),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,p=ta(r.simulcastCodecs.values()),b;b=yield p.next(),o=b.done,!o;h=!0)c=b.value,h=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){s={error:m}}finally{try{!h&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return E(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){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:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},YD))}setPublishingCodecs(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o,s,l;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(ur(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(n=!0,i=ta(e);r=yield i.next(),a=r.done,!a;n=!0){l=r.value,n=!1;const u=l;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(ur(u.codec),u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){c.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield QS(d.sender,d.encodings,u.qualities,this.senderLock,ur(u.codec),this.log,this.logContext))}}}catch(u){o={error:u}}finally{try{!n&&!a&&(s=i.return)&&(yield s.call(i))}finally{if(o)throw o.error}}return c})}setPublishingLayers(e,n){return E(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield QS(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return E(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var a;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((a=this.mediaStreamTrack.getSettings().height)!==null&&a!==void 0?a:360)/360)),scalabilityMode:r===0&&ur(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),_S()&&this.isInBackground&&this.source===H.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function QS(t,e,n,i,r,a,o){return E(this,void 0,void 0,function*(){const s=yield i.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const l=t.getParameters(),{encodings:c}=l;if(!c)return;if(c.length!==e.length){a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:c,senderEncodings:e}));return}let u=!1;!1&&c[0].scalabilityMode||(r&&n.some(p=>p.enabled)&&n.forEach(p=>p.enabled=!0),c.forEach((h,p)=>{var b;let m=(b=h.rid)!==null&&b!==void 0?b:"";m===""&&(m="q");const S=ZS(m),g=n.find(y=>y.quality===S);g&&h.active!==g.enabled&&(u=!0,h.active=g.enabled,a.debug("setting layer ".concat(g.quality," to ").concat(h.active?"enabled":"disabled"),o),Xo()&&(g.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),u&&(l.encodings=c,a.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:l.encodings})),yield t.setParameters(l))}finally{s()}})}function ZS(t){switch(t){case"f":return wi.HIGH;case"h":return wi.MEDIUM;case"q":return wi.LOW;default:return wi.HIGH}}function ek(t,e,n,i){if(!n)return[new Fa({quality:wi.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,a=new JS(r),o=[],s=a.suffix=="h"?1.5:2,l=a.suffix=="h"?2:3;for(let c=0;c<a.spatial;c+=1)o.push(new Fa({quality:Math.min(wi.HIGH,a.spatial-1)-c,width:Math.ceil(t/Math.pow(s,c)),height:Math.ceil(e/Math.pow(s,c)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(l,c)):0,ssrc:0}));return o}return n.map(r=>{var a,o,s;const l=(a=r.scaleResolutionDownBy)!==null&&a!==void 0?a:1;let c=ZS((o=r.rid)!==null&&o!==void 0?o:"");return new Fa({quality:c,width:Math.ceil(t/l),height:Math.ceil(e/l),bitrate:(s=r.maxBitrate)!==null&&s!==void 0?s:0,ssrc:0})})}const tk="_lossy",nk="_reliable",KD=2*1e3,wg="leave-reconnect",XD=3e4,$D=8*1024,JD=256*1024;var Hi;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(Hi||(Hi={}));class QD extends Mr.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=bg.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Hi.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=Ee,this.reliableDataSequence=1,this.reliableMessageBuffer=new LS,this.reliableReceivedState=new bD(XD),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>E(this,[i],void 0,function(r){var a=this;let{channel:o}=r;return function*(){if(o){if(o.label===nk)a.reliableDCSub=o;else if(o.label===tk)a.lossyDCSub=o;else return;a.log.debug("on data channel ".concat(o.id,", ").concat(o.label),a.logContext),o.onmessage=a.handleDataMessage}}()}),this.handleDataMessage=i=>E(this,void 0,void 0,function*(){var r,a,o,s,l;const c=yield this.dataProcessLock.lock();try{let u;if(i.data instanceof ArrayBuffer)u=i.data;else if(i.data instanceof Blob)u=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const d=Wn.fromBinary(new Uint8Array(u));if(d.sequence>0&&d.participantSid!==""){const h=this.reliableReceivedState.get(d.participantSid);if(h&&d.sequence<=h)return;this.reliableReceivedState.set(d.participantSid,d.sequence)}if(((r=d.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(re.ActiveSpeakersUpdate,d.value.value.speakers);else if(((a=d.value)===null||a===void 0?void 0:a.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(d.value.value.encryptedValue,d.value.value.iv,d.participantIdentity,d.value.value.keyIndex),p=J_.fromBinary(h.payload),b=new Wn({value:p.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((s=b.value)===null||s===void 0?void 0:s.case)==="user"&&ik(b,b.value.value),this.emit(re.DataPacketReceived,b,d.value.value.encryptionType)}else((l=d.value)===null||l===void 0?void 0:l.case)==="user"&&ik(d,d.value.value),this.emit(re.DataPacketReceived,d,an.NONE)}finally{c()}}),this.handleDataError=i=>{const a=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(a,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(a),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const a=i.currentTarget.maxRetransmits===0?Oe.LOSSY:Oe.RELIABLE;this.updateAndEmitDCBufferStatus(a)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const a=l=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(l,"ms. giving up"),this.logContext),this.emit(re.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){a(o);return}i===wg&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=wn.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Hi.Connected&&i();const a=()=>{this.off(re.Disconnected,o),i()},o=()=>{this.off(re.Restarted,a),r()};this.once(re.Restarted,a),this.once(re.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Oe.RELIABLE){const a=this.dataChannelForKind(i);a&&this.reliableMessageBuffer.alignBufferedAmount(a.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(re.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>E(this,void 0,void 0,function*(){!this.url||!(yield fetch(kc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===mt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===mt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Wo.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>E(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(kc(this.url),{method:"HEAD"}),Cn(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ea((n=e.loggerName)!==null&&n!==void 0?n:cr.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ug(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Gn,this.dataProcessLock=new Gn,this.dcBufferStatus=new Map([[Oe.LOSSY,!0],[Oe.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(re.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(re.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(re.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(re.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(re.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(re.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(re.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(re.SignalRequestResponse,i)}get logContext(){var e,n,i,r,a,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(a=this.latestJoinResponse)===null||a===void 0?void 0:a.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return E(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const a=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=a,this.subscriberPrimary=a.subscriberPrimary,this.pcManager||(yield this.configure(a)),(!this.subscriberPrimary||a.fastPublish)&&this.negotiate().catch(o=>{Ee.error(o,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=a.clientConfiguration,this.emit(re.SignalConnected,a),a}catch(a){if(a instanceof _e&&a.reason===kt.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,n,i,r);throw a}})}close(){return E(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(re.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return E(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 n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new LS,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return E(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new na("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(_e.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:a=>{clearTimeout(r),n(a)},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:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return E(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 E(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Lt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ED(r,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(re.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,s)=>E(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===Lt.CONNECTED){const u=this.pcState===Hi.New;this.pcState=Hi.Connected,u&&this.emit(re.Connected,e)}else a===Lt.FAILED&&(this.pcState===Hi.Connected||this.pcState===Hi.Reconnecting)&&(this.pcState=Hi.Disconnected,this.handleDisconnect("peerconnection failed",s==="failed"?Wo.RR_SUBSCRIBER_FAILED:Wo.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===mt.RECONNECTING,c=[Lt.FAILED,Lt.CLOSING,Lt.CLOSED].includes(a);l&&c&&!this._isClosed&&this.emit(re.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(re.MediaTrackAdded,a.track,a.streams[0],a.receiver)},ZD((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n,i)=>E(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n,i)=>E(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);r&&this.client.sendAnswer(r,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.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(re.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(re.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var n;this.token=e,(n=this.regionUrlProvider)===null||n===void 0||n.updateToken(e)},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(re.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(re.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(re.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var n,i;const r={direction:"recvonly"};for(let a=0;a<e.numAudios;a++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",r);for(let a=0;a<e.numVideos;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",r);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Wo.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({updatedAtInMs:Date.now(),maxAgeInMs:GS,regionSettings:e.regions})),e.action){case js.DISCONNECT:this.emit(re.Disconnected,e==null?void 0:e.reason),this.close();break;case js.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wg);break;case js.RESUME:this.handleDisconnect(wg)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.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(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===fc.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(tk,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(nk,{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,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Oe.LOSSY);if(e){const n=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(n,$D),JD)}},1e3))}createSender(e,n,i){return E(this,void 0,void 0,function*(){if(Zm())return yield this.createTransceiverRTCRtpSender(e,n,i);if(eg())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new on("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(Zm())return this.createSimulcastTransceiverSender(e,n,i,r);if(eg())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new on("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Va(e)&&(e.codec=n.videoCodec);const a={direction:"sendonly",streams:r};return i&&(a.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,a)).sender})}createSimulcastTransceiverSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("publisher is closed");const a={direction:"sendonly"};r&&(a.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,a);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return E(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Ee.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===fc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Lt.NEW)===Lt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(a){this.reconnectAttempts+=1;let o=!0;a instanceof on?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:a})),o=!1):a instanceof Us||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Wo.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(re.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return E(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new on("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(re.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let a;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Us;a=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof _e&&o.reason===kt.NotAllowed?new on("could not reconnect, token might be expired"):new Us}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(re.SignalRestarted,a),yield this.waitForPCReconnected(),this.client.currentState!==mt.CONNECTED)throw new Us("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(re.Restarted)}catch(a){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),a}})}resumeConnection(e){return E(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new on("could not reconnect, url or token not saved");if(!this.pcManager)throw new on("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(re.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let a="";throw r instanceof Error&&(a=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof _e&&r.reason===kt.NotAllowed?new on("could not reconnect, token might be expired"):r instanceof _e&&r.reason===kt.LeaveRequest?r:new Us(a)}if(this.emit(re.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}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!==mt.CONNECTED)throw new Us("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(re.Resumed)})}waitForPCInitialConnection(e,n){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return E(this,void 0,void 0,function*(){this.pcState=Hi.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Cn(KD),!this.pcManager)throw new on("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Hi.Connected}catch(e){throw this.pcState=Hi.Disconnected,_e.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,n,i,r){return E(this,void 0,void 0,function*(){const a=new Wn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcResponse",value:new Tm({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(a,Oe.RELIABLE)})}publishRpcAck(e,n){return E(this,void 0,void 0,function*(){const i=new Wn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcAck",value:new km({requestId:n})}});yield this.sendDataPacket(i,Oe.RELIABLE)})}sendDataPacket(e,n){return E(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(n),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const a=sD(e);if(a){const o=yield this.e2eeManager.encryptData(a.toBinary());e.value={case:"encryptedPacket",value:new $_({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}n===Oe.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===Oe.RELIABLE)yield this.waitForBufferStatusLow(n),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(n)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return E(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Oe.RELIABLE);const n=this.dataChannelForKind(Oe.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(Oe.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>E(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(re.Closing,r);!this.dcBufferStatus.get(e);)yield Cn(10);this.off(re.Closing,r),n()}}))}ensureDataTransportConnected(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var a;if(!i.pcManager)throw new on("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,s=r?"Subscriber":"Publisher";if(!o)throw _e.internal("".concat(s," connection not set"));let l=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),l=!0),!l&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(l=!0),l&&i.negotiate().catch(d=>{Ee.error(d,i.logContext)});const c=i.dataChannelForKind(n,r);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(o.isICEConnected&&((a=i.dataChannelForKind(n,r))===null||a===void 0?void 0:a.readyState)==="open")return;yield Cn(50)}throw _e.internal("could not establish ".concat(s," connection, state: ").concat(o.getICEConnectionState()))}()})}ensurePublisherConnected(e){return E(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Lt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return E(this,void 0,void 0,function*(){return new Promise((e,n)=>E(this,void 0,void 0,function*(){if(!this.pcManager){n(new Wm("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&&n("cannot negotiate on closed engine"),this.on(re.Closing,r),this.pcManager.publisher.once(Ws.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(s=>{const l=s.codec.toLowerCase();W8(l)&&o.set(s.payload,l)}),this.emit(re.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(a){a instanceof Wm&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Wo.RR_UNKNOWN),n(a)}finally{this.off(re.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===Oe.LOSSY)return this.lossyDCSub;if(e===Oe.RELIABLE)return this.reliableDCSub}else{if(e===Oe.LOSSY)return this.lossyDC;if(e===Oe.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.publisher.getLocalDescription(),l=this.pcManager.publisher.getRemoteDescription(),c=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),u=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getLocalDescription(),d=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,p=new Array;e.forEach(b=>{b.isDesired!==d&&h.push(b.trackSid),b.isEnabled||p.push(b.trackSid)}),this.client.sendSyncState(new Mm({answer:this.options.singlePeerConnection?l?Gs({sdp:l.sdp,type:l.type}):void 0:u?Gs({sdp:u.sdp,type:u.type}):void 0,offer:this.options.singlePeerConnection?s?Gs({sdp:s.sdp,type:s.type}):void 0:c?Gs({sdp:c.sdp,type:c.type}):void 0,subscription:new ah({trackSids:h,subscribe:!d,participantTracks:[]}),publishTracks:A8(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((b,m)=>new bx({publisherSid:m,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new yx({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Oe.LOSSY),lr.PUBLISHER),n(this.dataChannelForKind(Oe.RELIABLE),lr.PUBLISHER),n(this.dataChannelForKind(Oe.LOSSY,!0),lr.SUBSCRIBER),n(this.dataChannelForKind(Oe.RELIABLE,!0),lr.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&wn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){di()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){di()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var n;const i=(n=this.pcManager)===null||n===void 0?void 0:n.getMidForReceiver(e);if(i){const r=Object.entries(this.midToTrackId).find(a=>{let[o]=a;return o===i});if(r)return r[1]}}}function ZD(t){return t!==void 0&&t>13}function ik(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class rk{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Fi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Yn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Fi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Yn.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class eP extends rk{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new qi,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var s;(s=n.reject)===null||s===void 0||s.call(n,o.reason)},o.addEventListener("abort",r),i=o}const a=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>E(this,void 0,void 0,function*(){var o,s;try{const{done:l,value:c}=yield Promise.race([e.read(),n.promise,(s=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&s!==void 0?s:new Promise(()=>{})]);return l?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(c),{done:!1,value:c.content})}catch(l){throw a(),l}}),return(){return E(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,a,o;let s=new Set;const l=n.signal?e.withAbortSignal(n.signal):e;try{for(var c=!0,u=ta(l),d;d=yield u.next(),i=d.done,!i;c=!0){o=d.value,c=!1;const h=o;s.add(h)}}catch(h){r={error:h}}finally{try{!c&&!i&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}return Array.from(s)}()})}}class tP extends rk{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=vh(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const a=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,a)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new qi,r=null,a=null;if(this.signal){const s=this.signal;a=()=>{var l;(l=i.reject)===null||l===void 0||l.call(i,s.reason)},s.addEventListener("abort",a),r=s}const o=()=>{e.releaseLock(),r&&a&&r.removeEventListener("abort",a),this.signal=void 0};return{next:()=>E(this,void 0,void 0,function*(){var s,l;try{const{done:c,value:u}=yield Promise.race([e.read(),i.promise,(l=(s=this.outOfBandFailureRejectingFuture)===null||s===void 0?void 0:s.promise)!==null&&l!==void 0?l:new Promise(()=>{})]);if(c)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(u);let d;try{d=n.decode(u.content)}catch(h){throw new Fi("Cannot decode datastream chunk ".concat(u.chunkIndex," as text: ").concat(h),Yn.DecodeFailed)}return{done:!1,value:d}}}catch(c){throw o(),c}}),return(){return E(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,a,o;let s="";const l=n.signal?e.withAbortSignal(n.signal):e;try{for(var c=!0,u=ta(l),d;d=yield u.next(),i=d.done,!i;c=!0)o=d.value,c=!1,s+=o}catch(h){r={error:h}}finally{try{!c&&!i&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}return s}()})}}class nP{constructor(){this.log=Ee,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new Fi('A text stream handler for topic "'.concat(e,'" has already been set.'),Yn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new Fi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Yn.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,a;const o=Array.from(this.textStreamControllers.entries()).filter(l=>l[1].sendingParticipantIdentity===e),s=Array.from(this.byteStreamControllers.entries()).filter(l=>l[1].sendingParticipantIdentity===e);if(o.length>0||s.length>0){const l=new Fi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Yn.AbnormalEnd);for(const[c,u]of s)(i=(n=u.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,l),this.byteStreamControllers.delete(c);for(const[c,u]of o)(a=(r=u.outOfBandFailureRejectingFuture).reject)===null||a===void 0||a.call(r,l),this.textStreamControllers.delete(c)}}handleDataStreamPacket(e,n){return E(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,n);case"streamChunk":return this.handleStreamChunk(e.value.value,n);case"streamTrailer":return this.handleStreamTrailer(e.value.value,n);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n,i){return E(this,void 0,void 0,function*(){var r;if(e.contentHeader.case==="byteHeader"){const a=this.byteStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const s=new qi;s.promise.catch(u=>{this.log.error(u)});const l={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:vh(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new Fi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Yn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new eP(l,c,vh(e.totalLength),s),{identity:n})}else if(e.contentHeader.case==="textHeader"){const a=this.textStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const s=new qi;s.promise.catch(u=>{this.log.error(u)});const l={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new Fi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Yn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new tP(l,c,vh(e.totalLength),s),{identity:n})}})}handleStreamChunk(e,n){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Yn.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Yn.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,n){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Yn.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Yn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class ak{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return E(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 iP extends ak{}class rP extends ak{}const ok=15e3;class aP{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return E(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,s=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),l=new Array(s?s.length+1:1).fill(0),c=(d,h)=>{var p;l[h]=d;const b=l.reduce((m,S)=>m+S,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,b)},u=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:s,attributes:n==null?void 0:n.attributes});return yield u.write(e),c(1,0),yield u.close(),n!=null&&n.attachments&&s&&(yield Promise.all(n.attachments.map((d,h)=>E(this,void 0,void 0,function*(){return this._sendFile(s[h],d,{topic:n.topic,mimeType:d.type,onProgress:p=>{c(p,h+1)}})})))),u.info})}streamText(e){return E(this,void 0,void 0,function*(){var n,i,r;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),o={id:a,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,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?an.GCM:an.NONE},s=new eh({streamId:a,mimeType:o.mimeType,topic:o.topic,timestamp:Jo(o.timestamp),totalLength:Jo(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new cx({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"?wm.UPDATE:wm.CREATE})}}),l=e==null?void 0:e.destinationIdentities,c=new Wn({destinationIdentities:l,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,Oe.RELIABLE);let u=0;const d=this.engine,h=new WritableStream({write(m){return E(this,void 0,void 0,function*(){for(const S of Q8(m,ok)){const g=new th({content:S,streamId:a,chunkIndex:Jo(u)}),y=new Wn({destinationIdentities:l,value:{case:"streamChunk",value:g}});yield d.sendDataPacket(y,Oe.RELIABLE),u+=1}})},close(){return E(this,void 0,void 0,function*(){const m=new nh({streamId:a}),S=new Wn({destinationIdentities:l,value:{case:"streamTrailer",value:m}});yield d.sendDataPacket(S,Oe.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let p=()=>E(this,void 0,void 0,function*(){yield b.close()});d.once(re.Closing,p);const b=new iP(h,o,()=>this.engine.off(re.Closing,p));return b})}sendFile(e,n){return E(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return E(this,void 0,void 0,function*(){var r;const a=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:s,value:l}=yield o.read();if(s)break;yield a.write(l)}return yield a.close(),a.info})}streamBytes(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o,s;const l=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,u={id:l,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:(a=e==null?void 0:e.name)!==null&&a!==void 0?a:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?an.GCM:an.NONE},d=new eh({totalLength:Jo((s=u.size)!==null&&s!==void 0?s:0),mimeType:u.mimeType,streamId:l,topic:u.topic,timestamp:Jo(Date.now()),attributes:u.attributes,contentHeader:{case:"byteHeader",value:new ux({name:u.name})}}),h=new Wn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(h,Oe.RELIABLE);let p=0;const b=new Gn,m=this.engine,S=this.log,g=new WritableStream({write(x){return E(this,void 0,void 0,function*(){const v=yield b.lock();let k=0;try{for(;k<x.byteLength;){const T=x.slice(k,k+ok),C=new Wn({destinationIdentities:c,value:{case:"streamChunk",value:new th({content:T,streamId:l,chunkIndex:Jo(p)})}});yield m.sendDataPacket(C,Oe.RELIABLE),p+=1,k+=T.byteLength}}finally{v()}})},close(){return E(this,void 0,void 0,function*(){const x=new nh({streamId:l}),v=new Wn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield m.sendDataPacket(v,Oe.RELIABLE)})},abort(x){S.error("Sink error:",x)}});return new rP(g,u)})}}class sk extends H{constructor(e,n,i,r,a){super(e,i,a),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ee.Muted:ee.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ee.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return E(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(),_g)),N8()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:a}=i;a&&this.rtpTimestamp!==a&&(this.emit(ee.TimeSyncUpdate,{timestamp:r,rtpTimestamp:a}),this.rtpTimestamp=a)}};e()}}class oP extends sk{constructor(e,n,i,r,a,o){super(e,n,H.Kind.Audio,i,o),this.monitorReceiver=()=>E(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=bh(s,this.prevStats)),this.prevStats=s}),this.audioContext=r,this.webAudioPluginNodes=[],a&&(this.sinkId=a.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;Pr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Pr())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return E(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(tg(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&tg(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(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 n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}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,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.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(ee.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(ee.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return E(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={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})}),n})}}const Cg=100;class sP extends sk{constructor(e,n,i,r,a){super(e,n,H.Kind.Video,i,a),this.elementInfos=[],this.monitorReceiver=()=>E(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=bh(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=mg(()=>{this.updateDimensions()},Cg),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===H.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Fs(this._mediaStreamTrack,n):zs(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new lP(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===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 n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return E(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(a=>{a.type==="inbound-rtp"?(i=a.codecId,n={type:"video",streamId:a.id,framesDecoded:a.framesDecoded,framesDropped:a.framesDropped,framesReceived:a.framesReceived,packetsReceived:a.packetsReceived,packetsLost:a.packetsLost,frameWidth:a.frameWidth,frameHeight:a.frameHeight,pliCount:a.pliCount,firCount:a.firCount,nackCount:a.nackCount,jitter:a.jitter,timestamp:a.timestamp,bytesReceived:a.bytesReceived,decoderImplementation:a.decoderImplementation}):a.type==="codec"&&r.set(a.id,a)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var n,i;const r=this.elementInfos.reduce((l,c)=>Math.max(l,c.visibilityChangedAt||0),0),a=!((i=(n=this.adaptiveStreamSettings)===null||n===void 0?void 0:n.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(l=>l.pictureInPicture),s=this.elementInfos.some(l=>l.visible)&&!a||o;if(!(this.lastVisible===s&&!e)){if(!s&&Date.now()-r<Cg){wn.setTimeout(()=>{this.updateVisibility()},Cg);return}this.lastVisible=s,this.emit(ee.VisibilityChanged,s,this)}}updateDimensions(){var e,n;let i=0,r=0;const a=this.getPixelDensity();for(const o of this.elementInfos){const s=o.width()*a,l=o.height()*a;s+l>i+r&&(i=s,r=l)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(ee.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?kS():n||(kS()>2?2:1)}}class lP{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:a,isIntersecting:o}=i;a===this.element&&(this.isIntersecting=o,this.isPiP=Cc(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,a;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Cc(this.element),(a=this.handleVisibilityChanged)===null||a===void 0||a.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Cc(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??Eg(e),this.isPiP=di()&&Cc(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=Eg(this.element),this.isPiP=Cc(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,wS().observe(this.element),TS().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=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,a;(e=wS())===null||e===void 0||e.unobserve(this.element),(n=TS())===null||n===void 0||n.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),(a=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||a===void 0||a.removeEventListener("pagehide",this.onLeavePiP)}}function Cc(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Eg(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function Eg(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const a=t.offsetWidth,o=t.offsetHeight,{hidden:s}=t,{display:l}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+a>n.pageXOffset&&!s&&l!=="none"}class ra extends Mr.EventEmitter{constructor(e,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=an.NONE,this.log=Ee,this.handleMuted=()=>{this.emit(ee.Muted)},this.handleUnmuted=()=>{this.emit(ee.Unmuted)},this.log=ea((a=r==null?void 0:r.loggerName)!==null&&a!==void 0?a:cr.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=H.Source.Unknown}setTrack(e){this.track&&(this.track.off(ee.Muted,this.handleMuted),this.track.off(ee.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ee.Muted,this.handleMuted),e.on(ee.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),je(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==an.NONE}get audioTrack(){if(Ir(this.track))return this.track}get videoTrack(){if(Va(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=H.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===H.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(ra||(ra={}));class Rg extends ra{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ee.Ended)},this.handleCpuConstrained=()=>{this.track&&Va(this.track)&&this.emit(ee.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ee.Ended,this.handleTrackEnded),this.track.off(ee.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ee.Ended,this.handleTrackEnded),e.on(ee.CpuConstrained,this.handleCpuConstrained))}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 E(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return E(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return E(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return E(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ir(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(dn.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(dn.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(dn.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(dn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(dn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(dn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function xh(t,e){return E(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:a}=gS(t);let o=a.audio,s=a.video;if(i&&typeof a.audio=="object"&&(a.audio.processor=i),r&&typeof a.video=="object"&&(a.video.processor=r),t.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const d=a.audio.deviceId;a.audio.deviceId={exact:d},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:d}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const d=a.video.deviceId;a.video.deviceId={exact:d},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:d}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const l=fS(a,HS,VS),c=Jm(l),u=navigator.mediaDevices.getUserMedia(c);a.audio&&(hn.userMediaPromiseMap.set("audioinput",u),u.catch(()=>hn.userMediaPromiseMap.delete("audioinput"))),a.video&&(hn.userMediaPromiseMap.set("videoinput",u),u.catch(()=>hn.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>E(this,void 0,void 0,function*(){const p=h.kind==="audio";let b=p?l.audio:l.video;(typeof b=="boolean"||!b)&&(b={});let m;const S=p?c.audio:c.video;typeof S!="boolean"&&(m=S);const g=h.getSettings().deviceId;m!=null&&m.deviceId&&Ha(m.deviceId)!==g?m.deviceId=g:m||(m={deviceId:g});const y=ID(h,m,e);return y.kind===H.Kind.Video?y.source=H.Source.Camera:y.kind===H.Kind.Audio&&(y.source=H.Source.Microphone),y.mediaStream=d,Ir(y)&&i?yield y.setProcessor(i):Va(y)&&r&&(yield y.setProcessor(r)),y})))}catch(d){if(!n)throw d;return xh(Object.assign(Object.assign({},t),{audio:o,video:s}),e)}})}function cP(t){return E(this,void 0,void 0,function*(){return(yield xh({audio:!1,video:t??!0}))[0]})}function uP(t){return E(this,void 0,void 0,function*(){return(yield xh({audio:t??!0,video:!1}))[0]})}var Xa;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(Xa||(Xa={}));function dP(t){switch(t){case hc.EXCELLENT:return Xa.Excellent;case hc.GOOD:return Xa.Good;case hc.POOR:return Xa.Poor;case hc.LOST:return Xa.Lost;default:return Xa.Unknown}}class lk extends Mr.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.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===pc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ls.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,a,o){let s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:pc.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Xa.Unknown,this.log=Ee,this.log=ea((l=o==null?void 0:o.loggerName)!==null&&l!==void 0?l:cr.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=s,this._attributes=a??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new qi,this.once(oe.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(H.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(H.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(H.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 n;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===Ls.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Ls.ACTIVE&&this.emit(oe.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(oe.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(oe.ParticipantNameChanged,e)}_setAttributes(e){const n=O8(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(oe.AttributesChanged,n)}setPermissions(e){var n,i,r,a,o,s;const l=this.permissions,c=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.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!==((a=this.permissions)===null||a===void 0?void 0:a.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.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!==((s=this.permissions)===null||s===void 0?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(oe.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(oe.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=dP(e),n!==this._connectionQuality&&this.emit(oe.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Ir(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(ee.Muted,()=>{this.emit(oe.TrackMuted,e)}),e.on(ee.Unmuted,()=>{this.emit(oe.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case H.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case H.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function hP(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new gx({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class fP extends lk{constructor(e,n,i,r,a,o){super(e,n,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=an.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new qi)},this.handleReconnected=()=>{var s,l;(l=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||l===void 0||l.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var s,l,c,u,d,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(p=>this.log.warn(p.message,this.logContext)),(l=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||l===void 0||l.call(s,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(c=this.signalConnectedFuture).reject)===null||u===void 0||u.call(c,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(d=this.activeAgentFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=s=>{var l,c;s.participant&&this.updateInfo(s.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new qi),(c=(l=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(l)},this.handleSignalRequestResponse=s=>{const{requestId:l,reason:c,message:u}=s,d=this.pendingSignalRequests.get(l);d&&(c!==Dm.OK&&d.reject(new dS(u,c)),this.pendingSignalRequests.delete(l))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let l=s.value.value,c=null,u=null;l.value.case==="payload"?c=l.value.value:l.value.case==="error"&&(u=It.fromProto(l.value.value)),this.handleIncomingRpcResponse(l.requestId,c,u);break;case"rpcAck":let d=s.value.value;this.handleIncomingRpcAck(d.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>hP(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,l)=>{if(l===void 0&&(l=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),je(s)));return}this.engine.updateMuteStatus(s.sid,l)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),je(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),je(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const l=this.audioTrackPublications.get(s.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(s,l)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),je(l))),this.emit(oe.LocalTrackCpuConstrained,s,l)},this.handleSubscribedQualityUpdate=s=>E(this,void 0,void 0,function*(){var l,c,u,d,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const p=this.videoTrackPublications.get(s.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(!p.videoTrack)return;const b=yield p.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var m=!0,S=ta(b),g;g=yield S.next(),l=g.done,!l;m=!0){d=g.value,m=!1;const y=d;C8(y)&&(this.log.debug("publish ".concat(y," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),je(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,y,p.options))}}catch(y){c={error:y}}finally{try{!m&&!l&&(u=S.return)&&(yield u.call(S))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=s=>{const l=this.trackPublications.get(s.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(l.track)},this.handleTrackEnded=s=>E(this,void 0,void 0,function*(){if(s.source===H.Source.ScreenShare||s.source===H.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),je(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(ia(s)||Ga(s))try{if(di())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:s.source===H.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),je(s))),l.onchange=()=>{l.state!=="denied"&&(s.isMuted||s.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),je(s))),ia(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),je(s))),yield s.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=a,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==an.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(re.RemoteMute,(i,r)=>{const a=this.trackPublications.get(i);!a||!a.track||(r?a.mute():a.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(re.Connected,this.handleReconnected).on(re.SignalConnected,this.handleSignalConnected).on(re.SignalRestarted,this.handleReconnected).on(re.SignalResumed,this.handleReconnected).on(re.Restarting,this.handleReconnecting).on(re.Resuming,this.handleReconnecting).on(re.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(re.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(re.Closing,this.handleClosing).on(re.SignalRequestResponse,this.handleSignalRequestResponse).on(re.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return E(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:a,attributes:o}=n;return function*(){return new Promise((s,l)=>E(i,void 0,void 0,function*(){var c,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(u=a??this.name)!==null&&u!==void 0?u:"",o),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:s,reject:b=>{l(b),d=!0},values:{name:a,metadata:r,attributes:o}});performance.now()-p<5e3&&!d;){if((!a||this.name===a)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(b=>{let[m,S]=b;return this.attributes[m]===S||S===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),s();return}yield Cn(50)}l(new dS("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(H.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(H.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(H.Source.ScreenShare,e,n,i)}setE2EEEnabled(e){return E(this,void 0,void 0,function*(){this.encryptionType=e?an.GCM:an.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return E(this,void 0,void 0,function*(){var a,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let s=this.getTrackPublication(e);if(n)if(s)yield s.unmute();else{let l;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case H.Source.Camera:l=yield this.createTracks({video:(a=i)!==null&&a!==void 0?a:!0});break;case H.Source.Microphone:l=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case H.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new na(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(oe.MediaDevicesError,c,Qm(e)),this.pendingPublishing.delete(e),c}for(const c of l){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===H.Source.Microphone&&Ir(c)&&u.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),c.startPreConnectBuffer())}try{const c=[];for(const d of l)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),je(d))),c.push(this.publishTrack(d,r));[s]=yield Promise.all(c)}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(s!=null&&s.track)&&this.pendingPublishing.has(e)&&(s=yield this.waitForPendingPublicationOfSource(e),s||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),s&&s.track)if(e===H.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const l=this.getTrackPublication(H.Source.ScreenShareAudio);l&&l.track&&this.unpublishTrack(l.track)}else yield s.mute();return s})}enableCameraAndMicrophone(){return E(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(H.Source.Camera)||this.pendingPublishing.has(H.Source.Microphone))){this.pendingPublishing.add(H.Source.Camera),this.pendingPublishing.add(H.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(H.Source.Camera),this.pendingPublishing.delete(H.Source.Microphone)}}})}createTracks(e){return E(this,void 0,void 0,function*(){var n,i;e??(e={});const r=fS(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield xh(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(Ir(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=H.Source.Microphone,this.emit(oe.AudioStreamAcquired)),Va(s)&&(this.cameraError=void 0,s.source=H.Source.Camera),s))}catch(a){throw a instanceof Error&&(e.audio&&(this.microphoneError=a),e.video&&(this.cameraError=a)),a}})}createScreenTracks(e){return E(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Gm("getDisplayMedia not supported");e.resolution===void 0&&!z8()&&(e.resolution=Xm.h1080fps30.resolution);const n=R8(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new na("no video track found");const a=new _h(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=H.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);const o=[a];if(i.getAudioTracks().length>0){this.emit(oe.AudioStreamAcquired);const s=new yh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=H.Source.ScreenShareAudio,o.push(s)}return o})}publishTrack(e,n){return E(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var s,l,c,u;ia(i)&&i.setAudioContext(a.audioContext),yield(s=a.reconnectFuture)===null||s===void 0?void 0:s.promise,a.republishPromise&&!o&&(yield a.republishPromise),Hs(i)&&a.pendingPublishPromises.has(i)&&(yield a.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let g;switch(i.source){case H.Source.Microphone:g="audioinput";break;case H.Source.Camera:g="videoinput"}g&&a.activeDeviceMap.has(g)&&(d=Object.assign(Object.assign({},d),{deviceId:a.activeDeviceMap.get(g)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new yh(i,d,!0,a.audioContext,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;case"video":i=new _h(i,d,!0,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;default:throw new na("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});let h;if(a.trackPublications.forEach(g=>{g.track&&g.track===i&&(h=g)}),h)return a.log.warn("track has already been published, skipping",Object.assign(Object.assign({},a.logContext),je(h))),h;const p=Object.assign(Object.assign({},a.roomOptions.publishDefaults),r),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(l=p.forceStereo)!==null&&l!==void 0?l:b;m&&(p.dtx===void 0&&a.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},a.logContext),je(i))),p.red===void 0&&a.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=p.dtx)!==null&&c!==void 0||(p.dtx=!1),(u=p.red)!==null&&u!==void 0||(p.red=!1)),!q8()&&a.roomOptions.e2ee&&(a.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},a.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const S=new Promise((g,y)=>E(a,void 0,void 0,function*(){try{if(this.engine.client.currentState!==mt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:je(i)}));let x=!1;const v=setTimeout(()=>{x=!0,i.stop(),y(new uS("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(v),x)return;const k=yield this.publish(i,p,m);g(k)}else try{const x=yield this.publish(i,p,m);g(x)}catch(x){y(x)}}catch(x){y(x)}}));a.pendingPublishPromises.set(i,S);try{return yield S}catch(g){throw g}finally{a.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new qi),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),je(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>M8(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),je(e))),!1)}publish(e,n,i){return E(this,void 0,void 0,function*(){var r,a,o,s,l,c,u,d,h,p;if(!this.hasPermissionsToPublish(e))throw new uS("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Hs(e)&&A.source===e.source)&&e.source!==H.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),je(e))),n.stopMicTrackOnMute&&Ir(e)&&(e.stopOnMute=!0),e.source===H.Source.ScreenShare&&Xo()&&(n.simulcast=!1),n.videoCodec==="av1"&&!j8()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!B8()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=vg),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>n.videoCodec===yc(A.mime))||(n.videoCodec=yc(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;e.on(ee.Muted,this.onTrackMuted),e.on(ee.Unmuted,this.onTrackUnmuted),e.on(ee.Ended,this.handleTrackEnded),e.on(ee.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ee.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ee.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],g=!(!((r=n.dtx)!==null&&r!==void 0)||r),y=e.getSourceTrackSettings();y.autoGainControl&&S.push(dn.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&S.push(dn.TF_ECHO_CANCELLATION),y.noiseSuppression&&S.push(dn.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&S.push(dn.TF_STEREO),g&&S.push(dn.TF_NO_DTX),ia(e)&&e.hasPreConnectBuffer&&S.push(dn.TF_PRECONNECT_BUFFER);const x=new mc({cid:e.mediaStreamTrack.id,name:n.name,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((a=n.red)!==null&&a!==void 0)||a),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:S});let v;if(e.kind===H.Kind.Video){let A={width:0,height:0};try{A=yield e.waitForDimensions()}catch{const O=(s=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&s!==void 0?s:bc.h720.resolution;A={width:O.width,height:O.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{dims:A}))}x.width=A.width,x.height=A.height,Ga(e)&&(ur(m)&&(e.source===H.Source.ScreenShare&&(n.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),je(e))))),n.scalabilityMode=(l=n.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),x.simulcastCodecs=[new Em({codec:m,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:vg}),n.backupCodec&&m!==n.backupCodec.codec&&x.encryption===an.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Em({codec:n.backupCodec.codec,cid:""})))),v=kg(e.source===H.Source.ScreenShare,x.width,x.height,n),x.layers=ek(x.width,x.height,v,ur(n.videoCodec))}else e.kind===H.Kind.Audio&&(v=[{maxBitrate:(c=n.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(u=n.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(p=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new on("cannot publish track when not connected");const k=()=>E(this,void 0,void 0,function*(){var A,N,O;if(!this.engine.pcManager)throw new on("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,v),this.emit(oe.LocalSenderCreated,e.sender,e),Ga(e)&&((A=n.degradationPreference)!==null&&A!==void 0||(n.degradationPreference=WD(e)),e.setDegradationPreference(n.degradationPreference)),v)if(Xo()&&e.kind===H.Kind.Audio){let B;for(const W of this.engine.pcManager.publisher.getTransceivers())if(W.sender===e.sender){B=W;break}B&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:B,codec:"opus",maxbr:!((N=v[0])===null||N===void 0)&&N.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&ur(e.codec)&&(!((O=v[0])===null||O===void 0)&&O.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const C=new Promise((A,N)=>E(this,void 0,void 0,function*(){var O;try{T=yield this.engine.addTrack(x),A(T)}catch(B){e.sender&&(!((O=this.engine.pcManager)===null||O===void 0)&&O.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(W=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{error:W}))})),N(B)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([C,k()]))[0];else{T=yield C;let A;if(T.codecs.forEach(N=>{A===void 0&&(A=N.mimeType)}),A&&e.kind===H.Kind.Video){const N=yc(A);N!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{codec:N})),n.videoCodec=N,v=kg(e.source===H.Source.ScreenShare,x.width,x.height,n))}yield k()}const R=new Rg(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(R.on(ee.CpuConstrained,A=>this.onTrackCpuConstrained(A,R)),R.options=n,e.sid=T.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:T})),Ga(e)?e.startMonitor(this.engine.client):ia(e)&&e.startMonitor(),this.addTrackPublication(R),this.emit(oe.LocalTrackPublished,R),ia(e)&&T.audioFeatures.includes(dn.TF_PRECONNECT_BUFFER)){const A=e.getPreConnectBuffer(),N=e.getPreConnectBufferMimeType();this.on(oe.LocalTrackSubscribed,O=>{if(O.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),je(e))),e.stopPreConnectBuffer()}}),A&&new Promise((B,W)=>E(this,void 0,void 0,function*(){var L,K,P,V,X,te;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),je(e)));const Q=setTimeout(()=>{W(new Error("agent not active within 10 seconds"))},1e4),ce=yield this.waitUntilActiveAgentPresent();clearTimeout(Q),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),je(e)));const j=yield this.streamBytes({name:"preconnect-buffer",mimeType:N,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ce.identity],attributes:{trackId:R.trackSid,sampleRate:String((X=y.sampleRate)!==null&&X!==void 0?X:"48000"),channels:String((te=y.channelCount)!==null&&te!==void 0?te:"1")}});try{for(var $=!0,z=ta(A),Z;Z=yield z.next(),L=Z.done,!L;$=!0){V=Z.value,$=!1;const ge=V;yield j.write(ge)}}catch(ge){K={error:ge}}finally{try{!$&&!L&&(P=z.return)&&(yield P.call(z))}finally{if(K)throw K.error}}yield j.close(),B()}catch(Q){W(Q)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),je(e)))}).catch(B=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{error:B}))})}return R})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return E(this,void 0,void 0,function*(){var r;if(this.encryptionType!==an.NONE)return;let a;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(a=p)}),!a)throw new na("track is not published");if(!Ga(e))throw new na("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),s=HD(e,n,o);if(!s){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),je(e)));return}const l=e.addSimulcastTrack(n,s);if(!l)return;const c=new mc({cid:l.mediaStreamTrack.id,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=ek(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new on("cannot publish track when not connected");const u=()=>E(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,l,o,s),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:h}))})}unpublishTrack(e,n){return E(this,void 0,void 0,function*(){var i,r;if(Hs(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),je(e))),yield c)}const a=this.getPublicationForTrack(e),o=a?je(a):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!a||!a.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=a.track,e.off(ee.Muted,this.onTrackMuted),e.off(ee.Unmuted,this.onTrackUnmuted),e.off(ee.Ended,this.handleTrackEnded),e.off(ee.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ee.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ee.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let s=!1;const l=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Lt.FAILED&&l)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===l&&(c.direction="inactive",s=!0);if(this.engine.removeTrack(l)&&(s=!0),Ga(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(s=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:c}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case H.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case H.Kind.Video:this.videoTrackPublications.delete(a.trackSid);break}return this.emit(oe.LocalTrackUnpublished,a),a.setTrack(void 0),s&&(yield this.engine.negotiate()),a})}unpublishTracks(e){return E(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return E(this,arguments,void 0,function(n){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((a,o)=>E(i,void 0,void 0,function*(){try{const s=[];this.trackPublications.forEach(l=>{l.track&&(n&&(l.options=Object.assign(Object.assign({},l.options),n)),s.push(l))}),yield Promise.all(s.map(l=>E(this,void 0,void 0,function*(){const c=l.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==H.Source.ScreenShare&&c.source!==H.Source.ScreenShareAudio&&(ia(c)||Ga(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:l.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,l.options,!0)}))),a()}catch(s){o(s)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const a=r.reliable?Oe.RELIABLE:Oe.LOSSY,o=r.destinationIdentities,s=r.topic;let l=new xm({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:s});const c=new Wn({kind:a,value:{case:"user",value:l}});yield i.engine.sendDataPacket(c,a)}()})}publishDtmf(e,n){return E(this,void 0,void 0,function*(){const i=new Wn({kind:Oe.RELIABLE,value:{case:"sipDtmf",value:new Z_({code:e,digit:n})}});yield this.engine.sendDataPacket(i,Oe.RELIABLE)})}sendChatMessage(e,n){return E(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new Wn({value:{case:"chatMessage",value:new Zd(Object.assign(Object.assign({},i),{timestamp:Nt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(oe.ChatMessage,i),i})}editChatMessage(e,n){return E(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new Wn({value:{case:"chatMessage",value:new Zd(Object.assign(Object.assign({},i),{timestamp:Nt.parse(i.timestamp),editTimestamp:Nt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(oe.ChatMessage,i),i})}sendText(e,n){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return E(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:a,payload:o,responseTimeout:s=15e3}=n;return function*(){return new Promise((u,d)=>E(i,void 0,void 0,function*(){var h,p,b,m;if(yg(o)>WS){d(It.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((p=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||p===void 0)&&p.version&&Lr((m=(b=this.engine.latestJoinResponse)===null||b===void 0?void 0:b.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){d(It.builtIn("UNSUPPORTED_SERVER"));return}const S=Math.max(s,8e3),g=crypto.randomUUID();yield this.publishRpcRequest(r,g,a,o,S);const y=setTimeout(()=>{this.pendingAcks.delete(g),d(It.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(x)},7e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(y)},participantIdentity:r});const x=setTimeout(()=>{this.pendingResponses.delete(g),d(It.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(g,{resolve:(v,k)=>{clearTimeout(x),this.pendingAcks.has(g)&&(this.log.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(y)),k?d(k):u(v??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,n){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,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,a){return E(this,void 0,void 0,function*(){const o=new Wn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcRequest",value:new Sm({id:n,method:i,payload:r,responseTimeoutMs:a,version:1})}});yield this.engine.sendDataPacket(o,Oe.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,It.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const a=this.trackPublications.get(n.sid);if(a){const o=a.isMuted||((r=(i=a.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),je(a)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,a;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(a=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||a===void 0||a.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new qi),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(ia(r)||Ga(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return E(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(a=>{let[o]=a;return o.source===e});if(r)return r[1];yield Cn(20)}})}}class pP extends ra{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=a=>{this.setTrack(void 0),this.emit(ee.Ended,a)},this.handleVisibilityChange=a=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(a),this.logContext),this.visible=a,this.emitTrackUpdate()},this.handleVideoDimensionsChange=a=>{this.log.debug("adaptivestream video dimensions ".concat(a.width,"x").concat(a.height),this.logContext),this.videoDimensionsAdaptiveStream=a,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new ah({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tx({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ee.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?ra.SubscriptionStatus.Unsubscribed:super.isSubscribed?ra.SubscriptionStatus.Subscribed:ra.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ra.PermissionStatus.Allowed:ra.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(sg(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&sg(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:wi.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(ee.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(ee.VisibilityChanged,this.handleVisibilityChange),r.off(ee.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(ee.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ee.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ee.VisibilityChanged,this.handleVisibilityChange),e.on(ee.Ended,this.handleEnded),this.emit(ee.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(ee.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?ee.Muted:ee.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(ee.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ee.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sg(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new hx({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===H.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)vS(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=D8(this.trackInfo,this.requestedMaxQuality);i&&vS(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:wi.HIGH})),e.quality=wi.HIGH)}this.emit(ee.UpdateSettings,e)}}class Sh extends lk{static fromParticipantInfo(e,n,i){return new Sh(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,a,o,s){let l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:pc.STANDARD;super(n,i||"",r,a,o,s,l),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ee.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(ee.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(ee.SubscriptionPermissionChanged,n=>{this.emit(oe.TrackSubscriptionPermissionChanged,e,n)}),e.on(ee.SubscriptionStatusChanged,n=>{this.emit(oe.TrackSubscriptionStatusChanged,e,n)}),e.on(ee.Subscribed,n=>{this.emit(oe.TrackSubscribed,n,e)}),e.on(ee.Unsubscribed,n=>{this.emit(oe.TrackUnsubscribed,n,e)}),e.on(ee.SubscriptionFailed,n=>{this.emit(oe.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:H.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:H.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,a,o){let s=this.getTrackPublicationBySid(n);if(s||n.startsWith("TR")||this.trackPublications.forEach(u=>{!s&&e.kind===u.kind.toString()&&(s=u)}),!s){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(oe.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,a,o-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),je(s))),this.emit(oe.TrackSubscriptionFailed,n);return}const l=e.kind==="video";let c;return l?c=new sP(e,n,r,a):c=new oP(e,n,r,this.audioContext,this.audioOutput),c.source=s.source,c.isMuted=s.isMuted,c.setMediaStream(i),c.start(),s.setTrack(c),this.volumeMap.has(s.source)&&og(c)&&Ir(c)&&c.setVolume(this.volumeMap.get(s.source)),s}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var a,o;let s=this.getTrackPublicationBySid(r.sid);if(s)s.updateInfo(r);else{const l=H.kindFromProto(r.type);if(!l)return;s=new pP(l,r,(a=this.signalClient.connectOptions)===null||a===void 0?void 0:a.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),s.updateInfo(r),i.set(r.sid,s);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(s==null?void 0:s.source));c&&s.source!==H.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:je(c),newTrack:je(s)})),this.addTrackPublication(s)}n.set(r.sid,s)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),je(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(oe.TrackPublished,r)}),!0}unpublishTrack(e,n){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 H.Kind.Audio:this.audioTrackPublications.delete(e);break;case H.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(oe.TrackUnpublished,i)}setAudioOutput(e){return E(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Ir(i.track)&&og(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;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 Xe;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(Xe||(Xe={}));const mP=4*1e3;class Ys extends Mr.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var n,i,r,a;if(super(),n=this,this.state=Xe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ee,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,s,l)=>E(this,void 0,void 0,function*(){var c;if(!U8())throw Pr()?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===Xe.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(Xe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==RS(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),qs(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ke(o,s):this.regionUrlProvider.updateToken(s),this.regionUrlProvider.fetchRegionSettings().then(p=>{var b;(b=this.regionUrlProvider)===null||b===void 0||b.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const d=(p,b,m)=>E(this,void 0,void 0,function*(){var S,g;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{if(yield Vs.getInstance().getBackOffPromise(o),y.signal.aborted)throw _e.cancelled("Connection attempt aborted");yield this.attemptConnection(m??o,s,l,y),this.abortController=void 0,p()}catch(x){if(this.regionUrlProvider&&x instanceof _e&&x.reason!==kt.Cancelled&&x.reason!==kt.NotAllowed){let v=null;try{this.log.debug("Fetching next region"),v=yield this.regionUrlProvider.getNextBestRegionUrl((S=this.abortController)===null||S===void 0?void 0:S.signal)}catch(k){if(k instanceof _e&&(k.status===401||k.reason===kt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),b(k);return}}[kt.InternalError,kt.ServerUnreachable,kt.Timeout].includes(x.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Vs.getInstance().addFailedConnectionAttempt(o)),v&&!(!((g=this.abortController)===null||g===void 0)&&g.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield d(p,b,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ES(x)),b(x))}else{let v=sr.UNKNOWN_REASON;x instanceof _e&&(v=ES(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),b(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new qi((p,b)=>{d(p,b,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,s,l,c,u,d)=>E(this,void 0,void 0,function*(){var h,p,b;const m=yield l.join(o,s,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout,singlePeerConnection:u.singlePeerConnection},d.signal);let S=m.serverInfo;if(S||(S={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=S,this.log.debug("connected to Livekit Server ".concat(Object.entries(S).map(g=>{let[y,x]=g;return"".concat(y,": ").concat(x)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(p=m.room)===null||p===void 0?void 0:p.sid,identity:(b=m.participant)===null||b===void 0?void 0:b.identity}),!S.version)throw new x8("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=o=>{const s=o.participant;if(this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([s,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,s,l,c)=>E(this,void 0,void 0,function*(){var u,d;this.state===Xe.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({},bg),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,s,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(J.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const p=c.signal.aborted?_e.cancelled("Signal connection aborted"):_e.serverUnreachable("could not establish signal connection");throw h instanceof Error&&(p.message="".concat(p.message,": ").concat(h.message)),h instanceof _e&&(p.reason=h.reason,p.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),p}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),_e.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}di()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),di()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Xe.Connected),this.emit(J.Connected),Vs.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,s=new Array(o),l=0;l<o;l++)s[l]=arguments[l];return E(n,[...s],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,p;const b=yield c.disconnectLock.lock();try{if(c.state===Xe.Disconnected){c.log.debug("already disconnected",c.logContext);return}if(c.log.info("disconnect from room",Object.assign({},c.logContext)),c.state===Xe.Connecting||c.state===Xe.Reconnecting||c.isResuming){const m="Abort connection attempt due to user initiated disconnect";c.log.warn(m,c.logContext),(d=c.abortController)===null||d===void 0||d.abort(m),(p=(h=c.connectFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,_e.cancelled("Client initiated disconnect")),c.connectFuture=void 0}c.engine&&(c.engine.client.isDisconnected||(yield c.engine.client.sendLeave()),yield c.engine.close()),c.handleDisconnect(u,sr.CLIENT_INITIATED),c.engine=void 0}finally{b()}}()})},this.onPageLeave=()=>E(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>E(this,void 0,void 0,function*(){const o=[],s=ui();if(s&&s.os==="iOS"){const l="livekit-dummy-audio-el";let c=document.getElementById(l);if(!c){c=document.createElement("audio"),c.id=l,c.autoplay=!0,c.hidden=!0;const u=ag();u.enabled=!0;const d=new MediaStream([u]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(J.Disconnected,()=>{c==null||c.remove(),c=null})}o.push(c)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>E(this,void 0,void 0,function*(){const o=[];for(const s of this.remoteParticipants.values())s.videoTrackPublications.forEach(l=>{var c;(c=l.track)===null||c===void 0||c.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(s=>s.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(s=>{s.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 o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(Xe.Reconnecting)&&this.emit(J.Reconnecting)},this.handleSignalRestarted=o=>E(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(s){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:s}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(Xe.Connected),this.emit(J.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(s=>{var l;if(s.identity===this.localParticipant.identity){this.localParticipant.updateInfo(s);return}s.identity===""&&(s.identity=(l=this.sidToIdentity.get(s.sid))!==null&&l!==void 0?l:"");let c=this.remoteParticipants.get(s.identity);s.state===Ls.DISCONNECTED?this.handleParticipantDisconnected(s.identity,c):c=this.getOrCreateParticipant(s.identity,s)})},this.handleActiveSpeakersUpdate=o=>{const s=[],l={};o.forEach(c=>{if(l[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),s.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),s.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{l[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=s,this.emitWhenConnected(J.ActiveSpeakersChanged,s)},this.handleSpeakersChanged=o=>{const s=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||s.set(c.sid,c)}),o.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?s.set(c.sid,u):s.delete(c.sid))});const l=Array.from(s.values());l.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(J.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(s=>{const l=this.getRemoteParticipantBySid(s.participantSid);if(!l)return;const c=l.getTrackPublicationBySid(s.trackSid);if(!c||!c.track)return;const u=H.streamStateFromProto(s.state);c.track.setStreamState(u),u!==c.track.streamState&&(l.emit(oe.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(J.TrackStreamStateChanged,c,c.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=o=>{const s=this.getRemoteParticipantBySid(o.participantSid);if(!s)return;const l=s.getTrackPublicationBySid(o.trackSid);l&&l.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const s=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(o.trackSid));if(!s)return;const l=s.getTrackPublicationBySid(o.trackSid);l&&l.setSubscriptionError(o.err)},this.handleDataPacket=(o,s)=>{const l=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(l,o.value.value,o.kind,s);else if(o.value.case==="transcription")this.handleTranscription(l,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(l,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(l,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,l);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,s);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,s,l,c)=>{this.emit(J.DataReceived,s.payload,o,l,s.topic,c),o==null||o.emit(oe.DataReceived,s.payload,l,c)},this.handleSipDtmf=(o,s)=>{this.emit(J.SipDTMFReceived,s,o),o==null||o.emit(oe.SipDTMFReceived,s)},this.handleTranscription=(o,s)=>{const l=s.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(s.transcribedParticipantIdentity),c=l==null?void 0:l.trackPublications.get(s.trackId),u=K8(s,this.transcriptionReceivedTimes);c==null||c.emit(ee.TranscriptionReceived,u),l==null||l.emit(oe.TranscriptionReceived,u,c),this.emit(J.TranscriptionReceived,u,l,c)},this.handleChatMessage=(o,s)=>{const l=X8(s);this.emit(J.ChatMessage,l,o)},this.handleMetrics=(o,s)=>{this.emit(J.MetricsReceived,o,s)},this.handleDataStream=(o,s)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,s)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(J.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(J.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(J.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(J.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>E(this,void 0,void 0,function*(){var o;((o=ui())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(J.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const s=this.roomInfo;this.roomInfo=o,s&&s.metadata!==o.metadata&&this.emitWhenConnected(J.RoomMetadataChanged,o.metadata),(s==null?void 0:s.activeRecording)!==o.activeRecording&&this.emitWhenConnected(J.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(s=>{if(s.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(s.quality);return}const l=this.getRemoteParticipantBySid(s.participantSid);l&&l.setConnectionQuality(s.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(J.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(J.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(J.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(J.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(J.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var s;(s=o==null?void 0:o.onPublish)===null||s===void 0||s.call(o,this)},this.onLocalTrackPublished=o=>E(this,void 0,void 0,function*(){var s,l,c,u,d,h;(s=o.track)===null||s===void 0||s.on(ee.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.on(ee.Restarted,this.onLocalTrackRestarted),(d=(u=(c=o.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(J.LocalTrackPublished,o,this.localParticipant),ia(o.track)&&(yield o.track.checkForSilence())&&this.emit(J.LocalAudioSilenceDetected,o);const p=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),b=Qm(o.source);b&&p&&p!==this.localParticipant.activeDeviceMap.get(b)&&(this.localParticipant.activeDeviceMap.set(b,p),this.emit(J.ActiveDeviceChanged,b,p))}),this.onLocalTrackUnpublished=o=>{var s,l;(s=o.track)===null||s===void 0||s.off(ee.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.off(ee.Restarted,this.onLocalTrackRestarted),this.emit(J.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>E(this,void 0,void 0,function*(){const s=yield o.getDeviceId(!1),l=Qm(o.source);l&&s&&s!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(s," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,s),this.emit(J.ActiveDeviceChanged,l,s))}),this.onLocalConnectionQualityChanged=o=>{this.emit(J.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,s)=>{this.emit(J.MediaDevicesError,o,s)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(J.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(J.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},CD),e),this.log=ea((i=this.options.loggerName)!==null&&i!==void 0?i:cr.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},HS),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},VS),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},wD),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new nP,this.outgoingDataStreamManager=new aP(this.engine,this.log),this.disconnectLock=new Gn,this.localParticipant=new fP("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ha(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ha(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Ha(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),di()){const o=new AbortController;(a=navigator.mediaDevices)===null||a===void 0||a.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),Ys.cleanupRegistry&&Ys.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){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,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return E(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;const n=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new lD(i,n),this.e2eeManager.on(Ya.ParticipantEncryptionStatusChanged,(r,a)=>{J8(a)&&(this.isE2EEEnabled=r),this.emit(J.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(Ya.EncryptionError,(r,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(J.EncryptionError,r,o)}),(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,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return E(this,void 0,void 0,function*(){return this.state===Xe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(re.RoomUpdate,i),e(r.sid))};this.engine.on(re.RoomUpdate,i),this.once(J.Disconnected,()=>{this.engine.off(re.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new QD(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(re.ParticipantUpdate,this.handleParticipantUpdates).on(re.RoomUpdate,this.handleRoomUpdate).on(re.SpeakersChanged,this.handleSpeakersChanged).on(re.StreamStateChanged,this.handleStreamStateUpdate).on(re.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(re.SubscriptionError,this.handleSubscriptionError).on(re.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(re.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(re.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(re.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(re.DataPacketReceived,this.handleDataPacket).on(re.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Xe.SignalReconnecting)&&this.emit(J.SignalReconnecting)}).on(re.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Xe.Connected)&&this.emit(J.Reconnected)}).on(re.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Xe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(re.Restarting,this.handleRestarting).on(re.SignalRestarted,this.handleSignalRestarted).on(re.Offline,()=>{this.setAndEmitConnectionState(Xe.Reconnecting)&&this.emit(J.Reconnecting)}).on(re.DCBufferStatusChanged,(e,n)=>{this.emit(J.DCBufferStatusChanged,e,n)}).on(re.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(oe.LocalTrackSubscribed,n),this.emitWhenConnected(J.LocalTrackSubscribed,n,this.localParticipant)}).on(re.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(J.Moved,e.room.name),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),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return hn.getInstance().getDevices(e,n)}prepareConnection(e,n){return E(this,void 0,void 0,function*(){if(this.state===Xe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(qs(new URL(e))&&n){this.regionUrlProvider=new Ke(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Xe.Disconnected&&(this.regionUrl=i,yield fetch(kc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(kc(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,n){return E(this,void 0,void 0,function*(){let i=()=>E(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Or({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Or({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Or({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Or({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=()=>E(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Or({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>E(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Or({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 Or({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>E(this,void 0,void 0,function*(){const a=this.engine.client.onLeave;a&&a(new oh({reason:sr.CLIENT_INITIATED,action:js.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Or({scenario:{case:"subscriberBandwidth",value:Jo(n)}});break;case"leave-full-reconnect":r=new Or({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,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var s,l,c,u,d,h,p;let b=!0,m=!1;const S=o?{exact:r}:r;if(i==="audioinput"){m=a.localParticipant.audioTrackPublications.size===0;const g=(s=a.getActiveDevice(i))!==null&&s!==void 0?s:a.options.audioCaptureDefaults.deviceId;a.options.audioCaptureDefaults.deviceId=S;const y=Array.from(a.localParticipant.audioTrackPublications.values()).filter(v=>v.source===H.Source.Microphone);try{b=(yield Promise.all(y.map(v=>{var k;return(k=v.audioTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(v=>v===!0)}catch(v){throw a.options.audioCaptureDefaults.deviceId=g,v}const x=y.some(v=>{var k,T;return(T=(k=v.track)===null||k===void 0?void 0:k.isMuted)!==null&&T!==void 0?T:!1});b&&x&&(m=!0)}else if(i==="videoinput"){m=a.localParticipant.videoTrackPublications.size===0;const g=(l=a.getActiveDevice(i))!==null&&l!==void 0?l:a.options.videoCaptureDefaults.deviceId;a.options.videoCaptureDefaults.deviceId=S;const y=Array.from(a.localParticipant.videoTrackPublications.values()).filter(v=>v.source===H.Source.Camera);try{b=(yield Promise.all(y.map(v=>{var k;return(k=v.videoTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(v=>v===!0)}catch(v){throw a.options.videoCaptureDefaults.deviceId=g,v}const x=y.some(v=>{var k,T;return(T=(k=v.track)===null||k===void 0?void 0:k.isMuted)!==null&&T!==void 0?T:!1});b&&x&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!tg()&&!a.options.webAudioMix||a.options.webAudioMix&&a.audioContext&&!("setSinkId"in a.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");a.options.webAudioMix&&(r=(c=yield hn.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(p=a.options).audioOutput)!==null&&u!==void 0||(p.audioOutput={});const g=(d=a.getActiveDevice(i))!==null&&d!==void 0?d:a.options.audioOutput.deviceId;a.options.audioOutput.deviceId=r;try{a.options.webAudioMix&&((h=a.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(a.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:r})))}catch(y){throw a.options.audioOutput.deviceId=g,y}}return m&&(a.localParticipant.activeDeviceMap.set(i,r),a.emit(J.ActiveDeviceChanged,i,r)),b}()})}setupLocalParticipantEvents(){this.localParticipant.on(oe.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(oe.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(oe.AttributesChanged,this.onLocalAttributesChanged).on(oe.TrackMuted,this.onLocalTrackMuted).on(oe.TrackUnmuted,this.onLocalTrackUnmuted).on(oe.LocalTrackPublished,this.onLocalTrackPublished).on(oe.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(oe.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(oe.MediaDevicesError,this.onMediaDevicesError).on(oe.AudioStreamAcquired,this.startAudio).on(oe.ChatMessage,this.onLocalChatMessageSent).on(oe.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,n,i){if(this.state===Xe.Connecting||this.state===Xe.Reconnecting){const d=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map(p=>p.id)}),this.onTrackAdded(e,n,i),h()},h=()=>{this.off(J.Reconnected,d),this.off(J.Connected,d),this.off(J.Disconnected,h)};this.once(J.Reconnected,d),this.once(J.Connected,d),this.once(J.Disconnected,h);return}if(this.state===Xe.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=I8(n.id),a=r[0];let o=r[1],s=e.id;if(o&&o.startsWith("TR")&&(s=o),a===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const l=Array.from(this.remoteParticipants.values()).find(d=>d.sid===a);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a),this.logContext);return}if(!s.startsWith("TR")){const d=this.engine.getTrackIdForReceiver(i);if(!d){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a),this.logContext);return}s=d}s.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(o,", trackId: ").concat(s),Object.assign(Object.assign({},this.logContext),{rpID:a,streamId:o,trackId:s}));let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const u=l.addSubscribedMediaTrack(e,s,n,i,c);u!=null&&u.isEncrypted&&!this.e2eeManager&&this.emit(J.EncryptionError,new Error("Encrypted ".concat(u.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Xe.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,s;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(s=r.track)===null||s===void 0||s.stopMonitor()}),this.localParticipant.off(oe.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(oe.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(oe.AttributesChanged,this.onLocalAttributesChanged).off(oe.TrackMuted,this.onLocalTrackMuted).off(oe.TrackUnmuted,this.onLocalTrackUnmuted).off(oe.LocalTrackPublished,this.onLocalTrackPublished).off(oe.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(oe.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(oe.MediaDevicesError,this.onMediaDevicesError).off(oe.AudioStreamAcquired,this.startAudio).off(oe.ChatMessage,this.onLocalChatMessageSent).off(oe.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),di()&&(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(Xe.Disconnected),this.emit(J.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(J.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,a,o){return E(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,It.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(e,n,null,It.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield s({requestId:n,callerIdentity:e,payload:r,responseTimeout:a});yg(u)>WS?(l=It.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof It?l=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=It.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,c,l)})}selectDefaultDevices(){return E(this,void 0,void 0,function*(){var e,n,i;const r=hn.getInstance().previousDevices,a=yield hn.getInstance().getDevices(void 0,!1),o=ui();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let l of a){const c=r.find(u=>u.deviceId===l.deviceId);c&&c.label!==""&&c.kind===l.kind&&c.label!==l.label&&this.getActiveDevice(l.kind)==="default"&&this.emit(J.ActiveDeviceChanged,l.kind,l.deviceId)}const s=["audiooutput","audioinput","videoinput"];for(let l of s){const c=E8(l),u=this.localParticipant.getTrackPublication(c);if(u&&(!((e=u.track)===null||e===void 0)&&e.isUserProvided))continue;const d=a.filter(p=>p.kind===l),h=this.getActiveDevice(l);if(h===((n=r.filter(p=>p.kind===l)[0])===null||n===void 0?void 0:n.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(l,d[0].deviceId);continue}l==="audioinput"&&!xc()||l==="videoinput"||d.length>0&&!d.find(p=>p.deviceId===this.getActiveDevice(l))&&(l!=="audiooutput"||!xc())&&(yield this.switchActiveDevice(l,d[0].deviceId))}})}acquireAudioContext(){return E(this,void 0,void 0,function*(){var e,n;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=mS())!==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(),Cn(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(J.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Sh.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Sh(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(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(J.ParticipantConnected,i),i.on(oe.TrackPublished,r=>{this.emitWhenConnected(J.TrackPublished,r,i)}).on(oe.TrackSubscribed,(r,a)=>{r.kind===H.Kind.Audio?(r.on(ee.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(ee.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===H.Kind.Video&&(r.on(ee.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(ee.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(J.TrackSubscribed,r,a,i)}).on(oe.TrackUnpublished,r=>{this.emit(J.TrackUnpublished,r,i)}).on(oe.TrackUnsubscribed,(r,a)=>{this.emit(J.TrackUnsubscribed,r,a,i)}).on(oe.TrackMuted,r=>{this.emitWhenConnected(J.TrackMuted,r,i)}).on(oe.TrackUnmuted,r=>{this.emitWhenConnected(J.TrackUnmuted,r,i)}).on(oe.ParticipantMetadataChanged,r=>{this.emitWhenConnected(J.ParticipantMetadataChanged,r,i)}).on(oe.ParticipantNameChanged,r=>{this.emitWhenConnected(J.ParticipantNameChanged,r,i)}).on(oe.AttributesChanged,r=>{this.emitWhenConnected(J.ParticipantAttributesChanged,r,i)}).on(oe.ConnectionQualityChanged,r=>{this.emitWhenConnected(J.ConnectionQualityChanged,r,i)}).on(oe.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(J.ParticipantPermissionsChanged,r,i)}).on(oe.TrackSubscriptionStatusChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionStatusChanged,r,a,i)}).on(oe.TrackSubscriptionFailed,(r,a)=>{this.emit(J.TrackSubscriptionFailed,r,i,a)}).on(oe.TrackSubscriptionPermissionChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionPermissionChanged,r,a,i)}).on(oe.Active,()=>{this.emitWhenConnected(J.ParticipantActive,i),i.kind===pc.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&$8(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=wn.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,sr.STATE_MISMATCH))):e=0},mP)}clearConnectionReconcile(){this.connectionReconcileInterval&&wn.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(J.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===Xe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Xe.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return E(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Jd({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Nt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Yo({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(J.SignalConnected),this.emit(J.Connected),this.setAndEmitConnectionState(Xe.Connected),r.video){const o=new Rg(H.Kind.Video,new Is({source:Xt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO,name:"video-dummy"}),new _h(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:CS(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(oe.LocalTrackPublished,o)}if(r.audio){const o=new Rg(H.Kind.Audio,new Is({source:Xt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO}),new yh(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ag(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(oe.LocalTrackPublished,o)}for(let o=0;o<a.count-1;o+=1){let s=new Yo({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Ls.ACTIVE,tracks:[],joinedAt:Nt.parse(Date.now())});const l=this.getOrCreateParticipant(s.identity,s);if(a.video){const c=CS(160*((i=a.aspectRatios[o%a.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Is({source:Xt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}if(a.audio){const c=ag(),u=new Is({source:Xt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}l.updateInfo(s)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==J.ActiveSpeakersChanged&&e!==J.TranscriptionReceived){const a=ck(i).filter(o=>o!==void 0);(e===J.TrackSubscribed||e===J.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:a})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:a}))}return super.emit(e,...i)}}Ys.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ck(t){return t.map(e=>{if(e)return Array.isArray(e)?ck(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var hr;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(hr||(hr={}));class $a extends Mr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=hr.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new Ys(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return E(this,void 0,void 0,function*(){if(this.status!==hr.IDLE)throw Error("check is running already");this.setStatus(hr.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==hr.SKIPPED&&this.setStatus(this.isSuccess()?hr.SUCCESS:hr.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return E(this,void 0,void 0,function*(){return this.room.state===Xe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return E(this,void 0,void 0,function*(){this.room&&this.room.state!==Xe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(hr.SKIPPED)}switchProtocol(e){return E(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(J.Reconnecting,()=>{n=!0}),this.room.once(J.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(a=>setTimeout(a,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Cn(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 gP extends $a{get description(){return"Cloud regions"}perform(){return E(this,void 0,void 0,function*(){const e=new Ke(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let a=0;a<3;a++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const s=yield this.checkCloudRegion(o);this.appendMessage("".concat(s.region," RTT: ").concat(s.rtt,"ms, duration: ").concat(s.duration,"ms")),n.push(s)}n.sort((a,o)=>(a.duration-o.duration)*.5+(a.rtt-o.rtt)*.5);const r=n[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 E(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const a=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,l=1e6/o,c="A".repeat(o),u=Date.now();for(let b=0;b<l;b++)yield a.write(c);yield a.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(p.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Ag=1e4;class vP extends $a{get description(){return"Connection via UDP vs TCP"}perform(){return E(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):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/(Ag/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Ag/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return E(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const a=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(a)};a();const s=n.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(s,{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(()=>E(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(u.packetsSent=p.packetsSent,u.qualityLimitationDurations=p.qualityLimitationDurations,u.bitrateTotal+=p.targetBitrate,u.count++):p.type==="remote-inbound-rtp"&&(u.packetsLost=p.packetsLost,u.rttTotal+=p.roundTripTime,u.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Ag)),clearInterval(d),s.stop(),n.remove(),yield this.disconnect(),u})}}class bP extends $a{get description(){return"Can publish audio"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield uP();if(yield pS(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(s=>setTimeout(s,3e3));const a=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!a)throw new Error("Could not get RTCStats");let o=0;if(a.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="audio"||!s.kind&&s.mediaType==="audio")&&(o=s.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class yP extends $a{get description(){return"Can publish video"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield cP();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,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 a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(a+=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," video packets"))})}checkForVideo(e){return E(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var a,o,s,l;const c=document.createElement("canvas"),u=e.getSettings(),d=(o=(a=u.width)!==null&&a!==void 0?a:i.videoWidth)!==null&&o!==void 0?o:1280,h=(l=(s=u.height)!==null&&s!==void 0?s:i.videoHeight)!==null&&l!==void 0?l:720;c.width=d,c.height=h;const p=c.getContext("2d");p.drawImage(i,0,0);const m=p.getImageData(0,0,c.width,c.height).data;let S=!0;for(let g=0;g<m.length;g+=4)if(m[g]!==0||m[g+1]!==0||m[g+2]!==0){S=!1;break}S?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class _P extends $a{get description(){return"Resuming connection after interruption"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,a;const o=new Promise(c=>{setTimeout(c,5e3),a=c}),s=()=>{i=!0};n.on(J.SignalReconnecting,s).on(J.Reconnecting,s).on(J.Reconnected,()=>{r=!0,a(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const l=n.engine.client.onClose;if(l&&l(""),yield o,i){if(!r||n.state!==Xe.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 xP extends $a{get description(){return"Can connect via TURN"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;qs(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ke(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new ug,a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1});let o=!1,s=!1,l=!1;for(let c of a.iceServers)for(let u of c.urls)u.startsWith("turn:")?(s=!0,l=!0):u.startsWith("turns:")&&(s=!0,l=!0,o=!0),u.startsWith("stun:")&&(l=!0);l?s&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(n=this.connectOptions)===null||n===void 0?void 0:n.rtcConfig)===null||i===void 0)&&i.iceServers||s?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 SP extends $a{get description(){return"Establishing WebRTC connection"}perform(){return E(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(J.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(a,o)=>{if(a.candidate){const s=new RTCIceCandidate(a);let l="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(kP(s.address)?l+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,l+=" (passive)"):s.protocol==="udp"&&(n=!0)),this.appendMessage(l)}r&&r(a,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=a=>{a instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(a.errorCode," ").concat(a.errorText," ").concat(a.url))})});try{yield this.connect(),Ee.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"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function kP(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class TP extends $a{get description(){return"Connecting to signal connection via WebSocket"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ug,a;try{a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1})}catch(o){if(qs(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const l=yield new Ke(this.url,this.token).getNextBestRegionUrl();l&&(a=yield r.join(l,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1}),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}a?(this.appendMessage("Connected to server, version ".concat(a.serverVersion,".")),((e=a.serverInfo)===null||e===void 0?void 0:e.edition)===ix.Cloud&&(!((n=a.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=a.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class SW extends Mr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:hr.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==hr.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return E(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const a=yield i.run();return i.off("update",r),a})}checkWebsocket(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(TP)})}checkWebRTC(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(SP)})}checkTURN(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(xP)})}checkReconnect(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(_P)})}checkPublishAudio(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(bP)})}checkPublishVideo(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(yP)})}checkConnectionProtocol(){return E(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(vP);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(gP)})}}function Be(t,e,n){return(e=CP(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wP(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function CP(t){var e=wP(t,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class Kn extends Error{constructor(e,n){var i;super(e,n),Be(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Be(Kn,"code","ERR_JOSE_GENERIC");class EP extends Kn{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),Be(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Be(this,"claim",void 0),Be(this,"reason",void 0),Be(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}Be(EP,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class RP extends Kn{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),Be(this,"code","ERR_JWT_EXPIRED"),Be(this,"claim",void 0),Be(this,"reason",void 0),Be(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}Be(RP,"code","ERR_JWT_EXPIRED");class AP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Be(AP,"code","ERR_JOSE_ALG_NOT_ALLOWED");class NP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Be(NP,"code","ERR_JOSE_NOT_SUPPORTED");class OP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Be(OP,"code","ERR_JWE_DECRYPTION_FAILED");class MP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWE_INVALID")}}Be(MP,"code","ERR_JWE_INVALID");class DP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWS_INVALID")}}Be(DP,"code","ERR_JWS_INVALID");class PP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWT_INVALID")}}Be(PP,"code","ERR_JWT_INVALID");class LP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWK_INVALID")}}Be(LP,"code","ERR_JWK_INVALID");class IP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWKS_INVALID")}}Be(IP,"code","ERR_JWKS_INVALID");class jP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Be(jP,"code","ERR_JWKS_NO_MATCHING_KEY");class BP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,Symbol.asyncIterator,void 0),Be(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Be(BP,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class UP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWKS_TIMEOUT")}}Be(UP,"code","ERR_JWKS_TIMEOUT");class zP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Be(zP,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const FP=/\{[^{}]+\}/g;function qP(){return Math.random().toString(36).slice(2,11)}function HP(t){let{baseUrl:e="",Request:n=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:a,headers:o,...s}={...t};e=fk(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:p=i,Request:b=n,headers:m,params:S={},parseAs:g="json",querySerializer:y,bodySerializer:x=a??GP,body:v,...k}=d||{};h&&(e=fk(h));let T=typeof r=="function"?r:hk(r);y&&(T=typeof y=="function"?y:hk({...typeof r=="object"?r:{},...y}));const C=v===void 0?void 0:x(v),R=C===void 0||C instanceof FormData?{}:{"Content-Type":"application/json"},A={redirect:"follow",...s,...k,body:C,headers:YP(R,o,m,S.header)};let N,O,B=new n(WP(u,{baseUrl:e,params:S,querySerializer:T}),A);for(const K in k)K in B||(B[K]=k[K]);if(l.length){N=qP(),O=Object.freeze({baseUrl:e,fetch:p,parseAs:g,querySerializer:T,bodySerializer:x});for(const K of l)if(K&&typeof K=="object"&&typeof K.onRequest=="function"){const P=await K.onRequest({request:B,schemaPath:u,params:S,options:O,id:N});if(P){if(!(P instanceof n))throw new Error("onRequest: must return new Request() when modifying the request");B=P}}}let W=await p(B);if(l.length)for(let K=l.length-1;K>=0;K--){const P=l[K];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const V=await P.onResponse({request:B,response:W,schemaPath:u,params:S,options:O,id:N});if(V){if(!(V instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");W=V}}}if(W.status===204||W.headers.get("Content-Length")==="0")return W.ok?{data:{},response:W}:{error:{},response:W};if(W.ok)return g==="stream"?{data:W.body,response:W}:{data:await W[g](),response:W};let L=await W.text();try{L=JSON.parse(L)}catch{}return{error:L,response:W}}return{GET(u,d){return c(u,{...d,method:"GET"})},PUT(u,d){return c(u,{...d,method:"PUT"})},POST(u,d){return c(u,{...d,method:"POST"})},DELETE(u,d){return c(u,{...d,method:"DELETE"})},OPTIONS(u,d){return c(u,{...d,method:"OPTIONS"})},HEAD(u,d){return c(u,{...d,method:"HEAD"})},PATCH(u,d){return c(u,{...d,method:"PATCH"})},TRACE(u,d){return c(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");l.push(d)}},eject(...u){for(const d of u){const h=l.indexOf(d);h!==-1&&l.splice(h,1)}}}}function kh(t,e,n){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`${t}=${(n==null?void 0:n.allowReserved)===!0?e:encodeURIComponent(e)}`}function uk(t,e,n){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[n.style]||"&";if(n.style!=="deepObject"&&n.explode===!1){for(const s in e)i.push(s,n.allowReserved===!0?e[s]:encodeURIComponent(e[s]));const o=i.join(",");switch(n.style){case"form":return`${t}=${o}`;case"label":return`.${o}`;case"matrix":return`;${t}=${o}`;default:return o}}for(const o in e){const s=n.style==="deepObject"?`${t}[${o}]`:o;i.push(kh(s,e[o],n))}const a=i.join(r);return n.style==="label"||n.style==="matrix"?`${r}${a}`:a}function dk(t,e,n){if(!Array.isArray(e))return"";if(n.explode===!1){const a={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[n.style]||",",o=(n.allowReserved===!0?e:e.map(s=>encodeURIComponent(s))).join(a);switch(n.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${t}=${o}`;default:return`${t}=${o}`}}const i={simple:",",label:".",matrix:";"}[n.style]||"&",r=[];for(const a of e)n.style==="simple"||n.style==="label"?r.push(n.allowReserved===!0?a:encodeURIComponent(a)):r.push(kh(t,a,n));return n.style==="label"||n.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function hk(t){return function(n){const i=[];if(n&&typeof n=="object")for(const r in n){const a=n[r];if(a!=null){if(Array.isArray(a)){if(a.length===0)continue;i.push(dk(r,a,{style:"form",explode:!0,...t==null?void 0:t.array,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}if(typeof a=="object"){i.push(uk(r,a,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}i.push(kh(r,a,t))}}return i.join("&")}}function VP(t,e){let n=t;for(const i of t.match(FP)??[]){let r=i.substring(1,i.length-1),a=!1,o="simple";if(r.endsWith("*")&&(a=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(o="label",r=r.substring(1)):r.startsWith(";")&&(o="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const s=e[r];if(Array.isArray(s)){n=n.replace(i,dk(r,s,{style:o,explode:a}));continue}if(typeof s=="object"){n=n.replace(i,uk(r,s,{style:o,explode:a}));continue}if(o==="matrix"){n=n.replace(i,`;${kh(r,s)}`);continue}n=n.replace(i,o==="label"?`.${encodeURIComponent(s)}`:encodeURIComponent(s))}return n}function GP(t){return t instanceof FormData?t:JSON.stringify(t)}function WP(t,e){var r;let n=`${e.baseUrl}${t}`;(r=e.params)!=null&&r.path&&(n=VP(n,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(n+=`?${i}`),n}function YP(...t){const e=new Headers;for(const n of t){if(!n||typeof n!="object")continue;const i=n instanceof Headers?n.entries():Object.entries(n);for(const[r,a]of i)if(a===null)e.delete(r);else if(Array.isArray(a))for(const o of a)e.append(r,o);else a!==void 0&&e.set(r,a)}return e}function fk(t){return t.endsWith("/")?t.substring(0,t.length-1):t}const pk="Onboardee-Session-Token",mk="OnboardeeSessionToken";class gk{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=HP({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest:({request:n})=>{if(this.trackOnboardeeToken&&window.localStorage){const i=window.localStorage.getItem(mk);i&&n.headers.set(pk,i)}return n},onResponse:({response:n})=>{if(this.trackOnboardeeToken){const i=n.headers.get(pk);i&&window.localStorage&&window.localStorage.setItem(mk,i)}return n}})}setTrackOnboardeeToken(e){this.trackOnboardeeToken=e}setAuthToken(e){this.client.use({onRequest({request:n}){return n.headers.set("Authorization",`Bearer ${e}`),n}})}setApiToken(e){this.client.use({onRequest({request:n}){return n.headers.set("Authorization",`Token ${e}`),n}})}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,n){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:n})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}async clientInitialise(e,n={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:n})}async clientAuthConfig(e,n){return await this.client.GET("/api/client/{appToken}/auth-config",{params:{path:{appToken:e}},signal:n})}async clientStartSession(e,n){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:n})}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,n){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:n})}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 listPublishedPlansForProduct(e){return await this.client.GET("/api/products/{id}/published-plans",{params:{path:{id:String(e)}}})}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,n,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...n&&{start_date:n},...i&&{end_date:i},...r&&{course_id:r}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,n){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:n})}async getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}async getProductMeetAppToken(e){return await this.client.GET("/api/products/{id}/meet-app-token",{params:{path:{id:e}}})}async setProductMeetAppToken(e,n){return await this.client.POST("/api/products/{id}/meet-app-token",{params:{path:{id:e}},body:n})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,n){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:{content:n.content||""}})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,n){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async searchProductKnowledgeBlocks(e,n,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:n,...i&&{limit:i.toString()}}}})}async listAudiences(e,n){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)},...n?{query:n}:{}}})}async createAudience(e,n){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:n})}async getAudience(e,n){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}}})}async updateAudience(e,n,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}},body:i})}async deleteAudience(e,n){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}}})}async replaceAudiencePlans(e,n,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:n}},body:{plans:i}})}async updateProductKnowledgeBlock(e,n,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deleteProductKnowledgeBlock(e,n){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,n){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:n})}async bulkUpdateProductPronunciationRules(e,n){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:n})}async deleteProductPronunciationRule(e,n){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:n}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,n){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:n})}async updateProductExternalKnowledge(e,n,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:n}},body:i})}async deleteProductExternalKnowledge(e,n){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:n}}})}async refreshProductExternalKnowledge(e,n){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:n}}})}async listExternalKnowledgePages(e,n){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId:n}}})}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 getAdminPlanMeetAppToken(e){return await this.client.GET("/api/admin/plans/{id}/meet-app-token",{params:{path:{id:e}}})}async setAdminPlanMeetAppToken(e,n){return await this.client.POST("/api/admin/plans/{id}/meet-app-token",{params:{path:{id:e}},body:n})}async getPlanAnalytics(e,n,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...n&&{start_date:n},...i&&{end_date:i}}}})}async replacePlan(e,n){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:n})}async updatePlan(e,n){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:n})}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 n={};return e!=null&&e.search&&(n.search=e.search),e!=null&&e.page&&(n.page=e.page),e!=null&&e.limit&&(n.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(n).length>0?{query:n}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,n){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:n})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,n,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:n,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,n){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async updatePlanKnowledgeBlock(e,n,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deletePlanKnowledgeBlock(e,n){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,n){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:{content:n.content||""}})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,n){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:n})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async listPlanFAQs(e,n=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(n)}}})}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,n){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:n})}async listRevisionFAQs(e,n){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...n!==void 0&&{include_drafts:n.toString()}}}})}async createRevisionFAQ(e,n){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:n})}async updateFAQ(e,n){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:n})}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,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async createRevisionKnowledgeBlock(e,n){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async updateRevisionKnowledgeBlock(e,n,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deleteRevisionKnowledgeBlock(e,n){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async listSessions(e,n){const i={token:e};return n!=null&&n.productId&&(i.product_id=n.productId),n!=null&&n.startDate&&(i.start_date=n.startDate),n!=null&&n.endDate&&(i.end_date=n.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,n){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:n}}})}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 listUserSessions(e){const n={};return e!=null&&e.productId&&(n.product_id=e.productId),e!=null&&e.courseId&&(n.course_id=e.courseId),e!=null&&e.startDate&&(n.start_date=e.startDate),e!=null&&e.endDate&&(n.end_date=e.endDate),e!=null&&e.page&&(n.page=e.page),e!=null&&e.limit&&(n.limit=e.limit),e!=null&&e.courseName&&(n.course_name=e.courseName),e!=null&&e.userName&&(n.user_name=e.userName),e!=null&&e.company&&(n.company=e.company),e!=null&&e.email&&(n.email=e.email),e!=null&&e.sortBy&&(n.sort_by=e.sortBy),e!=null&&e.sortOrder&&(n.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(n).length>0?{query:n}:void 0})}async listUserSessionsAggregate(e){const n={};return e!=null&&e.productId&&(n.product_id=e.productId),e!=null&&e.courseId&&(n.course_id=e.courseId),e!=null&&e.startDate&&(n.start_date=e.startDate),e!=null&&e.endDate&&(n.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(n).length>0?{query:n}:void 0})}async queryTranscriptChat(e){return await this.client.POST("/api/performance/transcript-chat",{body:e})}streamTranscriptChat(e,n={},i={}){var s;const r=new AbortController,a=()=>{var l;return r.abort((l=i.signal)==null?void 0:l.reason)};(s=i.signal)!=null&&s.aborted?r.abort(i.signal.reason):i.signal&&i.signal.addEventListener("abort",a);const o=this.runTranscriptChatStream(e,n,r);return i.signal&&o.finally(()=>{var l;return(l=i.signal)==null?void 0:l.removeEventListener("abort",a)}),{cancel:()=>r.abort(),close:()=>r.abort(),signal:r.signal,closed:o}}async runTranscriptChatStream(e,n,i){const r=h=>{var p,b,m,S,g,y;switch((p=n.onEvent)==null||p.call(n,h),h.type){case"started":(b=n.onStarted)==null||b.call(n,h.data);break;case"batch_complete":(m=n.onBatchComplete)==null||m.call(n,h.data);break;case"answer_chunk":(S=n.onAnswerChunk)==null||S.call(n,h.data);break;case"completed":(g=n.onCompleted)==null||g.call(n,h.data);break;case"error":(y=n.onError)==null||y.call(n,h.data);break}},a=h=>{r({type:"error",data:h})};let o;try{o=await this.client.POST("/api/performance/transcript-chat/stream",{body:e,parseAs:"stream",signal:i.signal})}catch(h){throw console.error("[TranscriptChat] Network error:",h),a(aa(h,0,"network_error",`Failed to start transcript chat stream: ${h instanceof Error?h.message:String(h)}`)),h}const s=o.response;if(!s){console.error("[TranscriptChat] No response object"),a(aa(null,0,"no_response","No response returned from transcript chat"));return}if(s.status,s.statusText,s.headers.get("Content-Type"),!s.ok){const h=await vk(s);console.error("[TranscriptChat] HTTP error:",{status:s.status,payload:h}),a(aa(h??o.error,s.status,"http_error",`Transcript chat stream failed with status ${s.status}`));return}const l=s.headers.get("Content-Type")||"";if(!l.toLowerCase().includes("text/event-stream")){const h=await vk(s);console.error("[TranscriptChat] Invalid content type:",l),a(aa(h??o.error,s.status,"invalid_content_type","Transcript chat stream did not return an event stream"));return}if(!s.body){console.error("[TranscriptChat] Response body is null"),a(aa(null,s.status,"stream_unavailable","Streaming is not supported by this environment"));return}const c=s.body.getReader(),u=new TextDecoder;let d="";try{for(;;){const{value:h,done:p}=await c.read();d+=u.decode(h||new Uint8Array,{stream:!p});const b=d.split(`
42
+ `},pg}var US;function xD(){if(US)return dr;US=1;var t=yD(),e=_D(),n=fg();return dr.grammar=n,dr.write=e,dr.parse=t.parse,dr.parseParams=t.parseParams,dr.parseFmtpConfig=t.parseFmtpConfig,dr.parsePayloads=t.parsePayloads,dr.parseRemoteCandidates=t.parseRemoteCandidates,dr.parseImageAttributes=t.parseImageAttributes,dr.parseSimulcastStreamList=t.parseSimulcastStreamList,dr}var Ka=xD();function mg(t,e,n){var i,r,a;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,s=(r=n.callback)!=null&&r,l=n.maxWait,c=Date.now(),u=[];function d(){if(l!==void 0){var p=Date.now()-c;if(p+e>=l)return l-p}return e}var h=function(){var p=[].slice.call(arguments),b=this;return new Promise(function(m,S){var g=o&&a===void 0;if(a!==void 0&&clearTimeout(a),a=setTimeout(function(){if(a=void 0,c=Date.now(),!o){var x=t.apply(b,p);s&&s(x),u.forEach(function(v){return(0,v.resolve)(x)}),u=[]}},d()),g){var y=t.apply(b,p);return s&&s(y),m(y)}u.push({resolve:m,reject:S})})};return h.cancel=function(p){a!==void 0&&clearTimeout(a),u.forEach(function(b){return(0,b.reject)(p)}),u=[]},h}const SD=.7,kD=20,Ws={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class zS extends Mr.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Ee,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=mg(r=>E(this,void 0,void 0,function*(){this.emit(Ws.NegotiationStarted);try{yield this.createAndSendOffer()}catch(a){if(r)r(a);else throw a}}),kD),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=ea((i=n.loggerName)!==null&&i!==void 0?i:cr.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new Gn}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return E(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return E(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:a,nackMids:o}=TD(e);this.remoteStereoMids=a,this.remoteNackMids=o}else if(e.type==="answer"){const a=Ka.parse((i=e.sdp)!==null&&i!==void 0?i:"");a.media.forEach(o=>{const s=gg(o.mid);o.type==="audio"&&this.trackBitrates.some(l=>{if(!l.transceiver||s!=l.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===l.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let u=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),l.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(l.maxbr*1e3)),u=!0;break}return u||l.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(l.maxbr*1e3)}),!0})}),r=Ka.write(a)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Ws.NegotiationComplete),e.sdp&&Ka.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Ws.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{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 r=this.latestOfferId+1;this.latestOfferId=r;const a=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:a.sdp},this.logContext));const o=Ka.parse((n=a.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(s=>{qS(s),s.type==="audio"?FS(s,["all"],[]):s.type==="video"&&this.trackBitrates.some(l=>{if(!s.msid||!l.cid||!s.msid.includes(l.cid))return!1;let c=0;if(s.rtp.some(d=>d.codec.toUpperCase()===l.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(ur(l.codec)&&!$o()&&this.ensureVideoDDExtensionForSVC(s,o),!ur(l.codec)))return!0;const u=Math.round(l.maxbr*SD);for(const d of s.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(u));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(a,Ka.write(o)),this.onOffer(a,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return E(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=Ka.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{qS(r),r.type==="audio"&&FS(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Ka.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTransceiverOfKind(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new on("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new on("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}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 E(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(s=>{switch(s.type){case"transport":n=s.selectedCandidatePairId;break;case"candidate-pair":n===""&&s.selected&&(n=s.id),i.set(s.id,s);break;case"remote-candidate":r.set(s.id,"".concat(s.address,":").concat(s.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return E(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;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(a){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:a,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let a="unknown error";r instanceof Error?a=r.message:typeof r=="string"&&(a=r);const o={error:a,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Wm(a)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===bS))){if(this.ddExtID===0){let o=0;n.media.forEach(s=>{var l;s.type==="video"&&((l=s.ext)===null||l===void 0||l.forEach(c=>{c.value>o&&(o=c.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:bS})}}}function FS(t,e,n){const i=gg(t.mid);let r=0;t.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),r>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(i)&&!t.rtcpFb.some(a=>a.payload===r&&a.type==="nack")&&t.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&t.fmtp.some(a=>a.payload===r?(a.config.includes("stereo=1")||(a.config+=";stereo=1"),!0):!1))}function TD(t){var e;const n=[],i=[],r=Ka.parse((e=t.sdp)!==null&&e!==void 0?e:"");let a=0;return r.media.forEach(o=>{var s;const l=gg(o.mid);o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(a=c.payload,!0):!1),!((s=o.rtcpFb)===null||s===void 0)&&s.some(c=>c.payload===a&&c.type==="nack")&&i.push(l),o.fmtp.some(c=>c.payload===a?(c.config.includes("sprop-stereo=1")&&n.push(l),!0):!1))}),{stereoMids:n,nackMids:i}}function qS(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}function gg(t){return typeof t=="number"?t.toFixed(0):t}const vg="vp8",wD={audioPreset:Ym.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xm.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:vg,backupCodec:!0,preConnectBuffer:!1},HS={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},VS={deviceId:{ideal:"default"},resolution:bc.h720.resolution},CD={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new a8,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},bg={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Lt;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Lt||(Lt={}));class ED{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=bg.peerConnectionTimeout,this.log=Ee,this.updateState=()=>{var a,o;const s=this.state,l=this.requiredTransports.map(c=>c.getConnectionState());l.every(c=>c==="connected")?this.state=Lt.CONNECTED:l.some(c=>c==="failed")?this.state=Lt.FAILED:l.some(c=>c==="connecting")?this.state=Lt.CONNECTING:l.every(c=>c==="closed")?this.state=Lt.CLOSED:l.some(c=>c==="closed")?this.state=Lt.CLOSING:l.every(c=>c==="new")&&(this.state=Lt.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Lt[s]," to ").concat(Lt[this.state]),this.logContext),(a=this.onStateChange)===null||a===void 0||a.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=ea((r=i.loggerName)!==null&&r!==void 0?r:cr.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=n!=="subscriber-primary",this.isSubscriberConnectionRequired=n==="subscriber-primary",this.publisher=new zS(e,i),n!=="publisher-only"&&(this.subscriber=new zS(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=a=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,a,lr.SUBSCRIBER)},this.subscriber.onDataChannel=a=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,a)},this.subscriber.onTrack=a=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,a)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=a=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,a,lr.PUBLISHER)},this.publisher.onTrack=a=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,a)},this.publisher.onOffer=(a,o)=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,a,o)},this.state=Lt.NEW,this.connectionLock=new Gn,this.remoteOfferLock=new Gn}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return E(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const n=this.publisher;for(const i of n.getSenders())try{n.canRemoveTrack()&&n.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return E(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return E(this,void 0,void 0,function*(){var i;n===lr.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return E(this,void 0,void 0,function*(){var i,r,a;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,n))?yield(a=this.subscriber)===null||a===void 0?void 0:a.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,n){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return E(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(a=>this.ensureTransportConnected(a,e,n)))}finally{r()}})}negotiate(e){return E(this,void 0,void 0,function*(){return new Promise((n,i)=>E(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),a=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",a),this.publisher.once(Ws.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Ws.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTransceiverOfKind(e,n){return this.publisher.addTransceiverOfKind(e,n)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return i==null?void 0:i.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===lr.PUBLISHER?this.publisher.getConnectedAddress():e===lr.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((l,c)=>E(a,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),wn.clearTimeout(d),c(_e.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=wn.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(_e.internal("could not establish pc connection"))},o);for(;this.state!==Lt.CONNECTED;)if(yield Cn(50),r!=null&&r.signal.aborted){c(_e.cancelled("room connection has been cancelled"));return}wn.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}const GS=5e3,RD=3e4;class Ke{static fetchRegionSettings(e,n,i){return E(this,void 0,void 0,function*(){const r=yield Ke.fetchLock.lock();try{const a=yield fetch("".concat(AD(e),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(a.ok){const o=Z8(a.headers),s=o?o*1e3:GS;return{regionSettings:yield a.json(),updatedAtInMs:Date.now(),maxAgeInMs:s}}else throw a.status===401?_e.notAllowed("Could not fetch region settings: ".concat(a.statusText),a.status):_e.internal("Could not fetch region settings: ".concat(a.statusText))}catch(a){throw a instanceof _e?a:i!=null&&i.aborted?_e.cancelled("Region fetching was aborted"):_e.serverUnreachable("Could not fetch region settings, ".concat(a instanceof Error?"".concat(a.name,": ").concat(a.message):a))}finally{r()}})}static scheduleRefetch(e,n,i){return E(this,void 0,void 0,function*(){const r=Ke.settingsTimeouts.get(e.hostname);clearTimeout(r),Ke.settingsTimeouts.set(e.hostname,setTimeout(()=>E(this,void 0,void 0,function*(){try{const a=yield Ke.fetchRegionSettings(e,n);Ke.updateCachedRegionSettings(e,n,a)}catch(a){if(a instanceof _e&&a.reason===kt.NotAllowed){Ee.debug("token is not valid, cancelling auto region refresh");return}Ee.debug("auto refetching of region settings failed",{error:a}),Ke.scheduleRefetch(e,n,i)}}),i))})}static updateCachedRegionSettings(e,n,i){Ke.cache.set(e.hostname,i),Ke.scheduleRefetch(e,n,i.maxAgeInMs)}static stopRefetch(e){const n=Ke.settingsTimeouts.get(e);n&&(clearTimeout(n),Ke.settingsTimeouts.delete(e))}static scheduleCleanup(e){let n=Ke.connectionTrackers.get(e);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{const i=Ke.connectionTrackers.get(e);i&&i.connectionCount===0&&(Ee.debug("stopping region refetch after disconnect delay",{hostname:e}),Ke.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},RD))}static cancelCleanup(e){const n=Ke.connectionTrackers.get(e);n!=null&&n.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let n=Ke.connectionTrackers.get(e);n||(n={connectionCount:0},Ke.connectionTrackers.set(e,n)),n.connectionCount++,Ke.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,n=Ke.connectionTrackers.get(e);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&Ke.scheduleCleanup(e))}constructor(e,n){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return qs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return E(this,void 0,void 0,function*(){return Ke.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return E(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let n=Ke.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(e),Ke.updateCachedRegionSettings(this.serverUrl,this.token,n));const i=n.regionSettings.regions.filter(r=>!this.attemptedRegions.find(a=>a.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),Ee.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ke.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ke.cache=new Map,Ke.settingsTimeouts=new Map,Ke.connectionTrackers=new Map,Ke.fetchLock=new Gn;function AD(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class It extends Error{constructor(e,n,i){super(n),this.code=e,this.message=YS(n,It.MAX_MESSAGE_BYTES),this.data=i?YS(i,It.MAX_DATA_BYTES):void 0}static fromProto(e){return new It(e.code,e.message,e.data)}toProto(){return new ex({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new It(It.ErrorCode[e],It.ErrorMessage[e],n)}}It.MAX_MESSAGE_BYTES=256,It.MAX_DATA_BYTES=15360,It.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},It.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 WS=15360;function yg(t){return new TextEncoder().encode(t).length}function YS(t,e){if(yg(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const a=Math.floor((n+i+1)/2);r.encode(t.slice(0,a)).length<=e?n=a:i=a-1}return t.slice(0,n)}const _g=2e3;function bh(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const xg=typeof MediaRecorder<"u";class ND{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const OD=xg?MediaRecorder:ND;class MD extends OD{constructor(e,n){if(!xg)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const a=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),r==null||r.close(),r=void 0},s=l=>{r==null||r.error(l),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),r=void 0};this.byteStream=new ReadableStream({start:l=>{r=l,i=c=>E(this,void 0,void 0,function*(){let u;if(c.data.arrayBuffer){const d=yield c.data.arrayBuffer();u=new Uint8Array(d)}else if(c.data.byteArray)u=c.data.byteArray;else throw new Error("no data available!");a()||l.enqueue(u)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",s)}}function DD(){return xg}const PD=1e3,LD=1e4;class KS extends H{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,a=arguments.length>4?arguments[4]:void 0;super(e,n,a),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=mg(()=>E(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>E(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(ee.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Gn,this.pauseUpstreamLock=new Gn,this.trackChangeLock=new Gn,this.trackChangeLock.lock().then(o=>E(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==H.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return E(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Fs(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(zs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}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(a=>{zs(r??e,a)}))})}waitForDimensions(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:PD;return function*(){var i;if(e.kind===H.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ui())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Cn(10));const r=Date.now();for(;Date.now()-r<n;){const a=e.dimensions;if(a)return a;yield Cn(50)}throw new na("unable to get track dimensions after timeout")}()})}setDeviceId(e){return E(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ha(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ha(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===H.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),a=e.kind===H.Kind.Audio?"audioinput":"videoinput";return n?hn.getInstance().normalizeDeviceId(a,i,r):i}()})}mute(){return E(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return E(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return E(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new na("unable to replace an unpublished track");let r,a;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,a=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),a&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return E(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,a=o8(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===H.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?Object.assign({deviceId:i},a):!0,this.attachedElements.forEach(c=>{Fs(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===H.Kind.Video&&(yield l.applyConstraints(a)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l),this._constraints=e,this.emit(ee.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}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?ee.Muted:ee.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 E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),_S()&&(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 E(this,void 0,void 0,function*(){var e;const n=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(ee.UpstreamPaused,this);const i=ui();if((i==null?void 0:i.name)==="Safari"&&Lr(i.version,"12.0")<0)throw new Gm("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{n()}})}resumeUpstream(){return E(this,void 0,void 0,function*(){var e;const n=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(ee.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return E(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 E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const s=document.createElement(i.kind),l={kind:i.kind,track:i._mediaStreamTrack,element:s,audioContext:i.audioContext};if(yield n.init(l),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(zs(i._mediaStreamTrack,s),s.muted=!0,s.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{s.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))}),i.processor=n,i.processorElement=s,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Fs(i._mediaStreamTrack,c),zs(i.processor.processedTrack,c));yield(a=i.sender)===null||a===void 0?void 0:a.replaceTrack(i.processor.processedTrack)}i.emit(ee.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}}()})}internalStopProcessor(){return E(this,arguments,void 0,function(){var e=this;let n=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,n||((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(ee.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!DD()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new MD(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},LD)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class yh extends KS{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(e,H.Kind.Audio,n,i,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>E(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(s){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:s}));return}o&&this.prevStats&&(this._currentBitrate=bh(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ee.AudioTrackFeatureUpdate,this,dn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ee.AudioTrackFeatureUpdate,this,dn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===H.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return E(this,void 0,void 0,function*(){const n=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!==Ha(this._constraints.deviceId);return this.source===H.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{n()}})}restartTrack(e){return E(this,void 0,void 0,function*(){let n;if(e){const i=Jm({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return E(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){di()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},_g)))}setProcessor(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Pr()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());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(n=this.sender)===null||n===void 0?void 0:n.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(ee.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return E(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.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 E(this,void 0,void 0,function*(){const e=yield pS(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ee.AudioSilenceDetected)),e})}}function ID(t,e,n){switch(t.kind){case"audio":return new yh(t,e,!1,void 0,n);case"video":return new _h(t,e,!1,n);default:throw new na("unsupported track type: ".concat(t.kind))}}const jD=Object.values(bc),BD=Object.values(Km),UD=Object.values(Xm),zD=[bc.h180,bc.h360],FD=[Km.h180,Km.h360],qD=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new dt(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Sg=["q","h","f"];function kg(t,e,n,i){var r,a;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const s=i==null?void 0:i.simulcast,l=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!o&&!s&&!l||!e||!n)return[{}];o||(o=VD(t,e,n,c),Ee.debug("using video encoding",o));const u=o.maxFramerate,d=new dt(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(l&&ur(c)){const b=new JS(l),m=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const S=ui();if(xc()||Pr()||(S==null?void 0:S.name)==="Chrome"&&Lr(S==null?void 0:S.version,"113")<0){const g=b.suffix=="h"?2:3,y=F8(S);for(let x=0;x<b.spatial;x+=1)m.push({rid:Sg[2-x],maxBitrate:o.maxBitrate/Math.pow(g,x),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,x):void 0});m[0].scalabilityMode=l}else m.push({maxBitrate:o.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:l});return d.encoding.priority&&(m[0].priority=d.encoding.priority,m[0].networkPriority=d.encoding.priority),Ee.debug("using svc encoding",{encodings:m}),m}if(!s)return[o];let h=[];t?h=(r=$S(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:XS(t,d):h=(a=$S(i==null?void 0:i.videoSimulcastLayers))!==null&&a!==void 0?a:XS(t,d);let p;if(h.length>0){const b=h[0];h.length>1&&([,p]=h);const m=Math.max(e,n);if(m>=960&&p)return Tg(e,n,[b,p,d],u);if(m>=480)return Tg(e,n,[b,d],u)}return Tg(e,n,[d])}function HD(t,e,n){var i,r,a,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Ee.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const s=t.mediaStreamTrack.getSettings(),l=(i=s.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,c=(a=s.height)!==null&&a!==void 0?a:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===H.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),kg(t.source===H.Source.ScreenShare,l,c,n)}function VD(t,e,n,i){const r=GD(t,e,n);let{encoding:a}=r[0];const o=Math.max(e,n);for(let s=0;s<r.length;s+=1){const l=r[s];if(a=l.encoding,l.width>=o)break}if(i)switch(i){case"av1":case"h265":a=Object.assign({},a),a.maxBitrate=a.maxBitrate*.7;break;case"vp9":a=Object.assign({},a),a.maxBitrate=a.maxBitrate*.85;break}return a}function GD(t,e,n){if(t)return UD;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?jD:BD}function XS(t,e){if(t)return qD(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?zD:FD}function Tg(t,e,n,i){const r=[];if(n.forEach((a,o)=>{if(o>=Sg.length)return;const s=Math.min(t,e),c={rid:Sg[o],scaleResolutionDownBy:Math.max(1,s/Math.min(a.width,a.height)),maxBitrate:a.encoding.maxBitrate},u=i&&a.encoding.maxFramerate?Math.min(i,a.encoding.maxFramerate):a.encoding.maxFramerate;u&&(c.maxFramerate=u);const d=Xo()||o===0;a.encoding.priority&&d&&(c.priority=a.encoding.priority,c.networkPriority=a.encoding.priority),r.push(c)}),Pr()&&SS()==="ios"){let a;r.forEach(s=>{a?s.maxFramerate&&s.maxFramerate>a&&(a=s.maxFramerate):a=s.maxFramerate});let o=!0;r.forEach(s=>{var l;s.maxFramerate!=a&&(o&&(o=!1,Ee.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ee.info('Setting framerate of encoding "'.concat((l=s.rid)!==null&&l!==void 0?l:"",'" to ').concat(a)),s.maxFramerate=a)})}return r}function $S(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;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 JS{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function WD(t){return t.source===H.Source.ScreenShare||t.constraints.height&&Ha(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const YD=5e3;class _h extends KS{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,H.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>E(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(l){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:l}));return}const o=new Map(a.map(l=>[l.rid,l])),s=a.some(l=>l.qualityLimitationReason==="cpu");if(s!==this.isCpuConstrained&&(this.isCpuConstrained=s,this.isCpuConstrained&&this.emit(ee.CpuConstrained)),this.prevStats){let l=0;o.forEach((c,u)=>{var d;const h=(d=this.prevStats)===null||d===void 0?void 0:d.get(u);l+=bh(c,h)}),this._currentBitrate=l}this.prevStats=o}),this.senderLock=new Gn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!di())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},_g))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return E(this,void 0,void 0,function*(){var n,i,r,a,o;yield e.pauseUpstream.call(this);try{for(var s=!0,l=ta(this.simulcastCodecs.values()),c;c=yield l.next(),n=c.done,!n;s=!0)a=c.value,s=!1,yield(o=a.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(u){i={error:u}}finally{try{!s&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return E(this,void 0,void 0,function*(){var n,i,r,a,o;yield e.resumeUpstream.call(this);try{for(var s=!0,l=ta(this.simulcastCodecs.values()),c;c=yield l.next(),n=c.done,!n;s=!0){a=c.value,s=!1;const u=a;yield(o=u.sender)===null||o===void 0?void 0:o.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!s&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===H.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===H.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{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return E(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var a;if(r.type==="outbound-rtp"){const o={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:(a=r.rid)!==null&&a!==void 0?a:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},s=i.get(r.remoteId);s&&(o.jitter=s.jitter,o.packetsLost=s.packetsLost,o.roundTripTime=s.roundTripTime),n.push(o)}}),n.sort((r,a)=>{var o,s;return((o=a.frameWidth)!==null&&o!==void 0?o:0)-((s=r.frameWidth)!==null&&s!==void 0?s:0)}),n})}setPublishingQuality(e){const n=[];for(let i=wi.LOW;i<=wi.HIGH;i+=1)n.push(new Om({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ur(this.codec),n)}restartTrack(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o;let s;if(e){const d=Jm({video:e});typeof d.video!="boolean"&&(s=d.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var l=!0,c=ta(this.simulcastCodecs.values()),u;u=yield c.next(),n=u.done,!n;l=!0){a=u.value,l=!1;const d=a;d.sender&&((o=d.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!l&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return E(this,arguments,void 0,function(i){var r=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,s,l,c,u,d;if(yield n.setProcessor.call(r,i,a),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,p=ta(r.simulcastCodecs.values()),b;b=yield p.next(),o=b.done,!o;h=!0)c=b.value,h=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){s={error:m}}finally{try{!h&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return E(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){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:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},YD))}setPublishingCodecs(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o,s,l;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(ur(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(n=!0,i=ta(e);r=yield i.next(),a=r.done,!a;n=!0){l=r.value,n=!1;const u=l;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(ur(u.codec),u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){c.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield QS(d.sender,d.encodings,u.qualities,this.senderLock,ur(u.codec),this.log,this.logContext))}}}catch(u){o={error:u}}finally{try{!n&&!a&&(s=i.return)&&(yield s.call(i))}finally{if(o)throw o.error}}return c})}setPublishingLayers(e,n){return E(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield QS(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return E(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var a;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((a=this.mediaStreamTrack.getSettings().height)!==null&&a!==void 0?a:360)/360)),scalabilityMode:r===0&&ur(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),_S()&&this.isInBackground&&this.source===H.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function QS(t,e,n,i,r,a,o){return E(this,void 0,void 0,function*(){const s=yield i.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const l=t.getParameters(),{encodings:c}=l;if(!c)return;if(c.length!==e.length){a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:c,senderEncodings:e}));return}let u=!1;!1&&c[0].scalabilityMode||(r&&n.some(p=>p.enabled)&&n.forEach(p=>p.enabled=!0),c.forEach((h,p)=>{var b;let m=(b=h.rid)!==null&&b!==void 0?b:"";m===""&&(m="q");const S=ZS(m),g=n.find(y=>y.quality===S);g&&h.active!==g.enabled&&(u=!0,h.active=g.enabled,a.debug("setting layer ".concat(g.quality," to ").concat(h.active?"enabled":"disabled"),o),Xo()&&(g.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),u&&(l.encodings=c,a.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:l.encodings})),yield t.setParameters(l))}finally{s()}})}function ZS(t){switch(t){case"f":return wi.HIGH;case"h":return wi.MEDIUM;case"q":return wi.LOW;default:return wi.HIGH}}function ek(t,e,n,i){if(!n)return[new Fa({quality:wi.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,a=new JS(r),o=[],s=a.suffix=="h"?1.5:2,l=a.suffix=="h"?2:3;for(let c=0;c<a.spatial;c+=1)o.push(new Fa({quality:Math.min(wi.HIGH,a.spatial-1)-c,width:Math.ceil(t/Math.pow(s,c)),height:Math.ceil(e/Math.pow(s,c)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(l,c)):0,ssrc:0}));return o}return n.map(r=>{var a,o,s;const l=(a=r.scaleResolutionDownBy)!==null&&a!==void 0?a:1;let c=ZS((o=r.rid)!==null&&o!==void 0?o:"");return new Fa({quality:c,width:Math.ceil(t/l),height:Math.ceil(e/l),bitrate:(s=r.maxBitrate)!==null&&s!==void 0?s:0,ssrc:0})})}const tk="_lossy",nk="_reliable",KD=2*1e3,wg="leave-reconnect",XD=3e4,$D=8*1024,JD=256*1024;var Hi;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(Hi||(Hi={}));class QD extends Mr.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=bg.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Hi.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=Ee,this.reliableDataSequence=1,this.reliableMessageBuffer=new LS,this.reliableReceivedState=new bD(XD),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>E(this,[i],void 0,function(r){var a=this;let{channel:o}=r;return function*(){if(o){if(o.label===nk)a.reliableDCSub=o;else if(o.label===tk)a.lossyDCSub=o;else return;a.log.debug("on data channel ".concat(o.id,", ").concat(o.label),a.logContext),o.onmessage=a.handleDataMessage}}()}),this.handleDataMessage=i=>E(this,void 0,void 0,function*(){var r,a,o,s,l;const c=yield this.dataProcessLock.lock();try{let u;if(i.data instanceof ArrayBuffer)u=i.data;else if(i.data instanceof Blob)u=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const d=Wn.fromBinary(new Uint8Array(u));if(d.sequence>0&&d.participantSid!==""){const h=this.reliableReceivedState.get(d.participantSid);if(h&&d.sequence<=h)return;this.reliableReceivedState.set(d.participantSid,d.sequence)}if(((r=d.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(re.ActiveSpeakersUpdate,d.value.value.speakers);else if(((a=d.value)===null||a===void 0?void 0:a.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(d.value.value.encryptedValue,d.value.value.iv,d.participantIdentity,d.value.value.keyIndex),p=J_.fromBinary(h.payload),b=new Wn({value:p.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((s=b.value)===null||s===void 0?void 0:s.case)==="user"&&ik(b,b.value.value),this.emit(re.DataPacketReceived,b,d.value.value.encryptionType)}else((l=d.value)===null||l===void 0?void 0:l.case)==="user"&&ik(d,d.value.value),this.emit(re.DataPacketReceived,d,an.NONE)}finally{c()}}),this.handleDataError=i=>{const a=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(a,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(a),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const a=i.currentTarget.maxRetransmits===0?Oe.LOSSY:Oe.RELIABLE;this.updateAndEmitDCBufferStatus(a)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const a=l=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(l,"ms. giving up"),this.logContext),this.emit(re.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){a(o);return}i===wg&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=wn.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Hi.Connected&&i();const a=()=>{this.off(re.Disconnected,o),i()},o=()=>{this.off(re.Restarted,a),r()};this.once(re.Restarted,a),this.once(re.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Oe.RELIABLE){const a=this.dataChannelForKind(i);a&&this.reliableMessageBuffer.alignBufferedAmount(a.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(re.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>E(this,void 0,void 0,function*(){!this.url||!(yield fetch(kc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===mt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===mt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Wo.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>E(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(kc(this.url),{method:"HEAD"}),Cn(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ea((n=e.loggerName)!==null&&n!==void 0?n:cr.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ug(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Gn,this.dataProcessLock=new Gn,this.dcBufferStatus=new Map([[Oe.LOSSY,!0],[Oe.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(re.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(re.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(re.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(re.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(re.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(re.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(re.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(re.SignalRequestResponse,i)}get logContext(){var e,n,i,r,a,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(a=this.latestJoinResponse)===null||a===void 0?void 0:a.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return E(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const a=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=a,this.subscriberPrimary=a.subscriberPrimary,this.pcManager||(yield this.configure(a)),(!this.subscriberPrimary||a.fastPublish)&&this.negotiate().catch(o=>{Ee.error(o,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=a.clientConfiguration,this.emit(re.SignalConnected,a),a}catch(a){if(a instanceof _e&&a.reason===kt.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,n,i,r);throw a}})}close(){return E(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(re.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return E(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 n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new LS,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return E(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new na("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(_e.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:a=>{clearTimeout(r),n(a)},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:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return E(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 E(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Lt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ED(r,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(re.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,s)=>E(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===Lt.CONNECTED){const u=this.pcState===Hi.New;this.pcState=Hi.Connected,u&&this.emit(re.Connected,e)}else a===Lt.FAILED&&(this.pcState===Hi.Connected||this.pcState===Hi.Reconnecting)&&(this.pcState=Hi.Disconnected,this.handleDisconnect("peerconnection failed",s==="failed"?Wo.RR_SUBSCRIBER_FAILED:Wo.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===mt.RECONNECTING,c=[Lt.FAILED,Lt.CLOSING,Lt.CLOSED].includes(a);l&&c&&!this._isClosed&&this.emit(re.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(re.MediaTrackAdded,a.track,a.streams[0],a.receiver)},ZD((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n,i)=>E(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n,i)=>E(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);r&&this.client.sendAnswer(r,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.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(re.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(re.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var n;this.token=e,(n=this.regionUrlProvider)===null||n===void 0||n.updateToken(e)},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(re.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(re.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(re.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var n,i;const r={direction:"recvonly"};for(let a=0;a<e.numAudios;a++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",r);for(let a=0;a<e.numVideos;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",r);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Wo.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({updatedAtInMs:Date.now(),maxAgeInMs:GS,regionSettings:e.regions})),e.action){case js.DISCONNECT:this.emit(re.Disconnected,e==null?void 0:e.reason),this.close();break;case js.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wg);break;case js.RESUME:this.handleDisconnect(wg)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.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(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===fc.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(tk,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(nk,{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,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Oe.LOSSY);if(e){const n=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(n,$D),JD)}},1e3))}createSender(e,n,i){return E(this,void 0,void 0,function*(){if(Zm())return yield this.createTransceiverRTCRtpSender(e,n,i);if(eg())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new on("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(Zm())return this.createSimulcastTransceiverSender(e,n,i,r);if(eg())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new on("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Va(e)&&(e.codec=n.videoCodec);const a={direction:"sendonly",streams:r};return i&&(a.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,a)).sender})}createSimulcastTransceiverSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("publisher is closed");const a={direction:"sendonly"};r&&(a.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,a);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return E(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Ee.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===fc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Lt.NEW)===Lt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(a){this.reconnectAttempts+=1;let o=!0;a instanceof on?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:a})),o=!1):a instanceof Us||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Wo.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(re.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return E(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new on("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(re.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let a;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Us;a=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof _e&&o.reason===kt.NotAllowed?new on("could not reconnect, token might be expired"):new Us}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(re.SignalRestarted,a),yield this.waitForPCReconnected(),this.client.currentState!==mt.CONNECTED)throw new Us("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(re.Restarted)}catch(a){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),a}})}resumeConnection(e){return E(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new on("could not reconnect, url or token not saved");if(!this.pcManager)throw new on("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(re.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let a="";throw r instanceof Error&&(a=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof _e&&r.reason===kt.NotAllowed?new on("could not reconnect, token might be expired"):r instanceof _e&&r.reason===kt.LeaveRequest?r:new Us(a)}if(this.emit(re.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}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!==mt.CONNECTED)throw new Us("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(re.Resumed)})}waitForPCInitialConnection(e,n){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new on("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return E(this,void 0,void 0,function*(){this.pcState=Hi.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Cn(KD),!this.pcManager)throw new on("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Hi.Connected}catch(e){throw this.pcState=Hi.Disconnected,_e.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,n,i,r){return E(this,void 0,void 0,function*(){const a=new Wn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcResponse",value:new Tm({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(a,Oe.RELIABLE)})}publishRpcAck(e,n){return E(this,void 0,void 0,function*(){const i=new Wn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcAck",value:new km({requestId:n})}});yield this.sendDataPacket(i,Oe.RELIABLE)})}sendDataPacket(e,n){return E(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(n),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const a=sD(e);if(a){const o=yield this.e2eeManager.encryptData(a.toBinary());e.value={case:"encryptedPacket",value:new $_({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}n===Oe.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===Oe.RELIABLE)yield this.waitForBufferStatusLow(n),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(n)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return E(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Oe.RELIABLE);const n=this.dataChannelForKind(Oe.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(Oe.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>E(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(re.Closing,r);!this.dcBufferStatus.get(e);)yield Cn(10);this.off(re.Closing,r),n()}}))}ensureDataTransportConnected(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var a;if(!i.pcManager)throw new on("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,s=r?"Subscriber":"Publisher";if(!o)throw _e.internal("".concat(s," connection not set"));let l=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),l=!0),!l&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(l=!0),l&&i.negotiate().catch(d=>{Ee.error(d,i.logContext)});const c=i.dataChannelForKind(n,r);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(o.isICEConnected&&((a=i.dataChannelForKind(n,r))===null||a===void 0?void 0:a.readyState)==="open")return;yield Cn(50)}throw _e.internal("could not establish ".concat(s," connection, state: ").concat(o.getICEConnectionState()))}()})}ensurePublisherConnected(e){return E(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Lt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return E(this,void 0,void 0,function*(){return new Promise((e,n)=>E(this,void 0,void 0,function*(){if(!this.pcManager){n(new Wm("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&&n("cannot negotiate on closed engine"),this.on(re.Closing,r),this.pcManager.publisher.once(Ws.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(s=>{const l=s.codec.toLowerCase();W8(l)&&o.set(s.payload,l)}),this.emit(re.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(a){a instanceof Wm&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Wo.RR_UNKNOWN),n(a)}finally{this.off(re.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===Oe.LOSSY)return this.lossyDCSub;if(e===Oe.RELIABLE)return this.reliableDCSub}else{if(e===Oe.LOSSY)return this.lossyDC;if(e===Oe.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.publisher.getLocalDescription(),l=this.pcManager.publisher.getRemoteDescription(),c=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),u=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getLocalDescription(),d=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,p=new Array;e.forEach(b=>{b.isDesired!==d&&h.push(b.trackSid),b.isEnabled||p.push(b.trackSid)}),this.client.sendSyncState(new Mm({answer:this.options.singlePeerConnection?l?Gs({sdp:l.sdp,type:l.type}):void 0:u?Gs({sdp:u.sdp,type:u.type}):void 0,offer:this.options.singlePeerConnection?s?Gs({sdp:s.sdp,type:s.type}):void 0:c?Gs({sdp:c.sdp,type:c.type}):void 0,subscription:new ah({trackSids:h,subscribe:!d,participantTracks:[]}),publishTracks:A8(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((b,m)=>new bx({publisherSid:m,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new yx({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Oe.LOSSY),lr.PUBLISHER),n(this.dataChannelForKind(Oe.RELIABLE),lr.PUBLISHER),n(this.dataChannelForKind(Oe.LOSSY,!0),lr.SUBSCRIBER),n(this.dataChannelForKind(Oe.RELIABLE,!0),lr.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&wn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){di()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){di()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var n;const i=(n=this.pcManager)===null||n===void 0?void 0:n.getMidForReceiver(e);if(i){const r=Object.entries(this.midToTrackId).find(a=>{let[o]=a;return o===i});if(r)return r[1]}}}function ZD(t){return t!==void 0&&t>13}function ik(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class rk{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Fi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Yn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Fi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Yn.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class eP extends rk{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new qi,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var s;(s=n.reject)===null||s===void 0||s.call(n,o.reason)},o.addEventListener("abort",r),i=o}const a=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>E(this,void 0,void 0,function*(){var o,s;try{const{done:l,value:c}=yield Promise.race([e.read(),n.promise,(s=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&s!==void 0?s:new Promise(()=>{})]);return l?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(c),{done:!1,value:c.content})}catch(l){throw a(),l}}),return(){return E(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,a,o;let s=new Set;const l=n.signal?e.withAbortSignal(n.signal):e;try{for(var c=!0,u=ta(l),d;d=yield u.next(),i=d.done,!i;c=!0){o=d.value,c=!1;const h=o;s.add(h)}}catch(h){r={error:h}}finally{try{!c&&!i&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}return Array.from(s)}()})}}class tP extends rk{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=vh(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const a=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,a)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new qi,r=null,a=null;if(this.signal){const s=this.signal;a=()=>{var l;(l=i.reject)===null||l===void 0||l.call(i,s.reason)},s.addEventListener("abort",a),r=s}const o=()=>{e.releaseLock(),r&&a&&r.removeEventListener("abort",a),this.signal=void 0};return{next:()=>E(this,void 0,void 0,function*(){var s,l;try{const{done:c,value:u}=yield Promise.race([e.read(),i.promise,(l=(s=this.outOfBandFailureRejectingFuture)===null||s===void 0?void 0:s.promise)!==null&&l!==void 0?l:new Promise(()=>{})]);if(c)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(u);let d;try{d=n.decode(u.content)}catch(h){throw new Fi("Cannot decode datastream chunk ".concat(u.chunkIndex," as text: ").concat(h),Yn.DecodeFailed)}return{done:!1,value:d}}}catch(c){throw o(),c}}),return(){return E(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,a,o;let s="";const l=n.signal?e.withAbortSignal(n.signal):e;try{for(var c=!0,u=ta(l),d;d=yield u.next(),i=d.done,!i;c=!0)o=d.value,c=!1,s+=o}catch(h){r={error:h}}finally{try{!c&&!i&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}return s}()})}}class nP{constructor(){this.log=Ee,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new Fi('A text stream handler for topic "'.concat(e,'" has already been set.'),Yn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new Fi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Yn.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,a;const o=Array.from(this.textStreamControllers.entries()).filter(l=>l[1].sendingParticipantIdentity===e),s=Array.from(this.byteStreamControllers.entries()).filter(l=>l[1].sendingParticipantIdentity===e);if(o.length>0||s.length>0){const l=new Fi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Yn.AbnormalEnd);for(const[c,u]of s)(i=(n=u.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,l),this.byteStreamControllers.delete(c);for(const[c,u]of o)(a=(r=u.outOfBandFailureRejectingFuture).reject)===null||a===void 0||a.call(r,l),this.textStreamControllers.delete(c)}}handleDataStreamPacket(e,n){return E(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,n);case"streamChunk":return this.handleStreamChunk(e.value.value,n);case"streamTrailer":return this.handleStreamTrailer(e.value.value,n);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n,i){return E(this,void 0,void 0,function*(){var r;if(e.contentHeader.case==="byteHeader"){const a=this.byteStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const s=new qi;s.promise.catch(u=>{this.log.error(u)});const l={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:vh(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new Fi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Yn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new eP(l,c,vh(e.totalLength),s),{identity:n})}else if(e.contentHeader.case==="textHeader"){const a=this.textStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const s=new qi;s.promise.catch(u=>{this.log.error(u)});const l={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new Fi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Yn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new tP(l,c,vh(e.totalLength),s),{identity:n})}})}handleStreamChunk(e,n){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Yn.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Yn.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,n){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Yn.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new Fi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Yn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class ak{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return E(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 iP extends ak{}class rP extends ak{}const ok=15e3;class aP{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return E(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,s=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),l=new Array(s?s.length+1:1).fill(0),c=(d,h)=>{var p;l[h]=d;const b=l.reduce((m,S)=>m+S,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,b)},u=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:s,attributes:n==null?void 0:n.attributes});return yield u.write(e),c(1,0),yield u.close(),n!=null&&n.attachments&&s&&(yield Promise.all(n.attachments.map((d,h)=>E(this,void 0,void 0,function*(){return this._sendFile(s[h],d,{topic:n.topic,mimeType:d.type,onProgress:p=>{c(p,h+1)}})})))),u.info})}streamText(e){return E(this,void 0,void 0,function*(){var n,i,r;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),o={id:a,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,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?an.GCM:an.NONE},s=new eh({streamId:a,mimeType:o.mimeType,topic:o.topic,timestamp:Jo(o.timestamp),totalLength:Jo(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new cx({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"?wm.UPDATE:wm.CREATE})}}),l=e==null?void 0:e.destinationIdentities,c=new Wn({destinationIdentities:l,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,Oe.RELIABLE);let u=0;const d=this.engine,h=new WritableStream({write(m){return E(this,void 0,void 0,function*(){for(const S of Q8(m,ok)){const g=new th({content:S,streamId:a,chunkIndex:Jo(u)}),y=new Wn({destinationIdentities:l,value:{case:"streamChunk",value:g}});yield d.sendDataPacket(y,Oe.RELIABLE),u+=1}})},close(){return E(this,void 0,void 0,function*(){const m=new nh({streamId:a}),S=new Wn({destinationIdentities:l,value:{case:"streamTrailer",value:m}});yield d.sendDataPacket(S,Oe.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let p=()=>E(this,void 0,void 0,function*(){yield b.close()});d.once(re.Closing,p);const b=new iP(h,o,()=>this.engine.off(re.Closing,p));return b})}sendFile(e,n){return E(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return E(this,void 0,void 0,function*(){var r;const a=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:s,value:l}=yield o.read();if(s)break;yield a.write(l)}return yield a.close(),a.info})}streamBytes(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o,s;const l=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,u={id:l,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:(a=e==null?void 0:e.name)!==null&&a!==void 0?a:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?an.GCM:an.NONE},d=new eh({totalLength:Jo((s=u.size)!==null&&s!==void 0?s:0),mimeType:u.mimeType,streamId:l,topic:u.topic,timestamp:Jo(Date.now()),attributes:u.attributes,contentHeader:{case:"byteHeader",value:new ux({name:u.name})}}),h=new Wn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(h,Oe.RELIABLE);let p=0;const b=new Gn,m=this.engine,S=this.log,g=new WritableStream({write(x){return E(this,void 0,void 0,function*(){const v=yield b.lock();let k=0;try{for(;k<x.byteLength;){const T=x.slice(k,k+ok),C=new Wn({destinationIdentities:c,value:{case:"streamChunk",value:new th({content:T,streamId:l,chunkIndex:Jo(p)})}});yield m.sendDataPacket(C,Oe.RELIABLE),p+=1,k+=T.byteLength}}finally{v()}})},close(){return E(this,void 0,void 0,function*(){const x=new nh({streamId:l}),v=new Wn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield m.sendDataPacket(v,Oe.RELIABLE)})},abort(x){S.error("Sink error:",x)}});return new rP(g,u)})}}class sk extends H{constructor(e,n,i,r,a){super(e,i,a),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ee.Muted:ee.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ee.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return E(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(),_g)),N8()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:a}=i;a&&this.rtpTimestamp!==a&&(this.emit(ee.TimeSyncUpdate,{timestamp:r,rtpTimestamp:a}),this.rtpTimestamp=a)}};e()}}class oP extends sk{constructor(e,n,i,r,a,o){super(e,n,H.Kind.Audio,i,o),this.monitorReceiver=()=>E(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=bh(s,this.prevStats)),this.prevStats=s}),this.audioContext=r,this.webAudioPluginNodes=[],a&&(this.sinkId=a.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;Pr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Pr())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return E(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(tg(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&tg(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(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 n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}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,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.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(ee.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(ee.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return E(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={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})}),n})}}const Cg=100;class sP extends sk{constructor(e,n,i,r,a){super(e,n,H.Kind.Video,i,a),this.elementInfos=[],this.monitorReceiver=()=>E(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=bh(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=mg(()=>{this.updateDimensions()},Cg),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===H.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Fs(this._mediaStreamTrack,n):zs(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new lP(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===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 n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return E(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(a=>{a.type==="inbound-rtp"?(i=a.codecId,n={type:"video",streamId:a.id,framesDecoded:a.framesDecoded,framesDropped:a.framesDropped,framesReceived:a.framesReceived,packetsReceived:a.packetsReceived,packetsLost:a.packetsLost,frameWidth:a.frameWidth,frameHeight:a.frameHeight,pliCount:a.pliCount,firCount:a.firCount,nackCount:a.nackCount,jitter:a.jitter,timestamp:a.timestamp,bytesReceived:a.bytesReceived,decoderImplementation:a.decoderImplementation}):a.type==="codec"&&r.set(a.id,a)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var n,i;const r=this.elementInfos.reduce((l,c)=>Math.max(l,c.visibilityChangedAt||0),0),a=!((i=(n=this.adaptiveStreamSettings)===null||n===void 0?void 0:n.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(l=>l.pictureInPicture),s=this.elementInfos.some(l=>l.visible)&&!a||o;if(!(this.lastVisible===s&&!e)){if(!s&&Date.now()-r<Cg){wn.setTimeout(()=>{this.updateVisibility()},Cg);return}this.lastVisible=s,this.emit(ee.VisibilityChanged,s,this)}}updateDimensions(){var e,n;let i=0,r=0;const a=this.getPixelDensity();for(const o of this.elementInfos){const s=o.width()*a,l=o.height()*a;s+l>i+r&&(i=s,r=l)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(ee.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?kS():n||(kS()>2?2:1)}}class lP{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:a,isIntersecting:o}=i;a===this.element&&(this.isIntersecting=o,this.isPiP=Cc(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,a;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Cc(this.element),(a=this.handleVisibilityChanged)===null||a===void 0||a.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Cc(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??Eg(e),this.isPiP=di()&&Cc(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=Eg(this.element),this.isPiP=Cc(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,wS().observe(this.element),TS().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=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,a;(e=wS())===null||e===void 0||e.unobserve(this.element),(n=TS())===null||n===void 0||n.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),(a=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||a===void 0||a.removeEventListener("pagehide",this.onLeavePiP)}}function Cc(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Eg(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function Eg(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const a=t.offsetWidth,o=t.offsetHeight,{hidden:s}=t,{display:l}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+a>n.pageXOffset&&!s&&l!=="none"}class ra extends Mr.EventEmitter{constructor(e,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=an.NONE,this.log=Ee,this.handleMuted=()=>{this.emit(ee.Muted)},this.handleUnmuted=()=>{this.emit(ee.Unmuted)},this.log=ea((a=r==null?void 0:r.loggerName)!==null&&a!==void 0?a:cr.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=H.Source.Unknown}setTrack(e){this.track&&(this.track.off(ee.Muted,this.handleMuted),this.track.off(ee.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ee.Muted,this.handleMuted),e.on(ee.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),je(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==an.NONE}get audioTrack(){if(Ir(this.track))return this.track}get videoTrack(){if(Va(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=H.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===H.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(ra||(ra={}));class Rg extends ra{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ee.Ended)},this.handleCpuConstrained=()=>{this.track&&Va(this.track)&&this.emit(ee.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ee.Ended,this.handleTrackEnded),this.track.off(ee.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ee.Ended,this.handleTrackEnded),e.on(ee.CpuConstrained,this.handleCpuConstrained))}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 E(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return E(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return E(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return E(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ir(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(dn.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(dn.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(dn.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(dn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(dn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(dn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function xh(t,e){return E(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:a}=gS(t);let o=a.audio,s=a.video;if(i&&typeof a.audio=="object"&&(a.audio.processor=i),r&&typeof a.video=="object"&&(a.video.processor=r),t.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const d=a.audio.deviceId;a.audio.deviceId={exact:d},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:d}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const d=a.video.deviceId;a.video.deviceId={exact:d},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:d}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const l=fS(a,HS,VS),c=Jm(l),u=navigator.mediaDevices.getUserMedia(c);a.audio&&(hn.userMediaPromiseMap.set("audioinput",u),u.catch(()=>hn.userMediaPromiseMap.delete("audioinput"))),a.video&&(hn.userMediaPromiseMap.set("videoinput",u),u.catch(()=>hn.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>E(this,void 0,void 0,function*(){const p=h.kind==="audio";let b=p?l.audio:l.video;(typeof b=="boolean"||!b)&&(b={});let m;const S=p?c.audio:c.video;typeof S!="boolean"&&(m=S);const g=h.getSettings().deviceId;m!=null&&m.deviceId&&Ha(m.deviceId)!==g?m.deviceId=g:m||(m={deviceId:g});const y=ID(h,m,e);return y.kind===H.Kind.Video?y.source=H.Source.Camera:y.kind===H.Kind.Audio&&(y.source=H.Source.Microphone),y.mediaStream=d,Ir(y)&&i?yield y.setProcessor(i):Va(y)&&r&&(yield y.setProcessor(r)),y})))}catch(d){if(!n)throw d;return xh(Object.assign(Object.assign({},t),{audio:o,video:s}),e)}})}function cP(t){return E(this,void 0,void 0,function*(){return(yield xh({audio:!1,video:t??!0}))[0]})}function uP(t){return E(this,void 0,void 0,function*(){return(yield xh({audio:t??!0,video:!1}))[0]})}var Xa;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(Xa||(Xa={}));function dP(t){switch(t){case hc.EXCELLENT:return Xa.Excellent;case hc.GOOD:return Xa.Good;case hc.POOR:return Xa.Poor;case hc.LOST:return Xa.Lost;default:return Xa.Unknown}}class lk extends Mr.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.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===pc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ls.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,a,o){let s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:pc.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Xa.Unknown,this.log=Ee,this.log=ea((l=o==null?void 0:o.loggerName)!==null&&l!==void 0?l:cr.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=s,this._attributes=a??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new qi,this.once(oe.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(H.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(H.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(H.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 n;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===Ls.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Ls.ACTIVE&&this.emit(oe.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(oe.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(oe.ParticipantNameChanged,e)}_setAttributes(e){const n=O8(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(oe.AttributesChanged,n)}setPermissions(e){var n,i,r,a,o,s;const l=this.permissions,c=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.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!==((a=this.permissions)===null||a===void 0?void 0:a.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.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!==((s=this.permissions)===null||s===void 0?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(oe.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(oe.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=dP(e),n!==this._connectionQuality&&this.emit(oe.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Ir(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(ee.Muted,()=>{this.emit(oe.TrackMuted,e)}),e.on(ee.Unmuted,()=>{this.emit(oe.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case H.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case H.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function hP(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new gx({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class fP extends lk{constructor(e,n,i,r,a,o){super(e,n,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=an.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new qi)},this.handleReconnected=()=>{var s,l;(l=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||l===void 0||l.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var s,l,c,u,d,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(p=>this.log.warn(p.message,this.logContext)),(l=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||l===void 0||l.call(s,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(c=this.signalConnectedFuture).reject)===null||u===void 0||u.call(c,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(d=this.activeAgentFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=s=>{var l,c;s.participant&&this.updateInfo(s.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new qi),(c=(l=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(l)},this.handleSignalRequestResponse=s=>{const{requestId:l,reason:c,message:u}=s,d=this.pendingSignalRequests.get(l);d&&(c!==Dm.OK&&d.reject(new dS(u,c)),this.pendingSignalRequests.delete(l))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let l=s.value.value,c=null,u=null;l.value.case==="payload"?c=l.value.value:l.value.case==="error"&&(u=It.fromProto(l.value.value)),this.handleIncomingRpcResponse(l.requestId,c,u);break;case"rpcAck":let d=s.value.value;this.handleIncomingRpcAck(d.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>hP(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,l)=>{if(l===void 0&&(l=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),je(s)));return}this.engine.updateMuteStatus(s.sid,l)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),je(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),je(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const l=this.audioTrackPublications.get(s.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(s,l)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),je(l))),this.emit(oe.LocalTrackCpuConstrained,s,l)},this.handleSubscribedQualityUpdate=s=>E(this,void 0,void 0,function*(){var l,c,u,d,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const p=this.videoTrackPublications.get(s.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(!p.videoTrack)return;const b=yield p.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var m=!0,S=ta(b),g;g=yield S.next(),l=g.done,!l;m=!0){d=g.value,m=!1;const y=d;C8(y)&&(this.log.debug("publish ".concat(y," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),je(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,y,p.options))}}catch(y){c={error:y}}finally{try{!m&&!l&&(u=S.return)&&(yield u.call(S))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=s=>{const l=this.trackPublications.get(s.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(l.track)},this.handleTrackEnded=s=>E(this,void 0,void 0,function*(){if(s.source===H.Source.ScreenShare||s.source===H.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),je(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(ia(s)||Ga(s))try{if(di())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:s.source===H.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),je(s))),l.onchange=()=>{l.state!=="denied"&&(s.isMuted||s.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),je(s))),ia(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),je(s))),yield s.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=a,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==an.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(re.RemoteMute,(i,r)=>{const a=this.trackPublications.get(i);!a||!a.track||(r?a.mute():a.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(re.Connected,this.handleReconnected).on(re.SignalConnected,this.handleSignalConnected).on(re.SignalRestarted,this.handleReconnected).on(re.SignalResumed,this.handleReconnected).on(re.Restarting,this.handleReconnecting).on(re.Resuming,this.handleReconnecting).on(re.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(re.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(re.Closing,this.handleClosing).on(re.SignalRequestResponse,this.handleSignalRequestResponse).on(re.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return E(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:a,attributes:o}=n;return function*(){return new Promise((s,l)=>E(i,void 0,void 0,function*(){var c,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(u=a??this.name)!==null&&u!==void 0?u:"",o),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:s,reject:b=>{l(b),d=!0},values:{name:a,metadata:r,attributes:o}});performance.now()-p<5e3&&!d;){if((!a||this.name===a)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(b=>{let[m,S]=b;return this.attributes[m]===S||S===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),s();return}yield Cn(50)}l(new dS("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(H.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(H.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(H.Source.ScreenShare,e,n,i)}setE2EEEnabled(e){return E(this,void 0,void 0,function*(){this.encryptionType=e?an.GCM:an.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return E(this,void 0,void 0,function*(){var a,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let s=this.getTrackPublication(e);if(n)if(s)yield s.unmute();else{let l;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case H.Source.Camera:l=yield this.createTracks({video:(a=i)!==null&&a!==void 0?a:!0});break;case H.Source.Microphone:l=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case H.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new na(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(oe.MediaDevicesError,c,Qm(e)),this.pendingPublishing.delete(e),c}for(const c of l){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===H.Source.Microphone&&Ir(c)&&u.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),c.startPreConnectBuffer())}try{const c=[];for(const d of l)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),je(d))),c.push(this.publishTrack(d,r));[s]=yield Promise.all(c)}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(s!=null&&s.track)&&this.pendingPublishing.has(e)&&(s=yield this.waitForPendingPublicationOfSource(e),s||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),s&&s.track)if(e===H.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const l=this.getTrackPublication(H.Source.ScreenShareAudio);l&&l.track&&this.unpublishTrack(l.track)}else yield s.mute();return s})}enableCameraAndMicrophone(){return E(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(H.Source.Camera)||this.pendingPublishing.has(H.Source.Microphone))){this.pendingPublishing.add(H.Source.Camera),this.pendingPublishing.add(H.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(H.Source.Camera),this.pendingPublishing.delete(H.Source.Microphone)}}})}createTracks(e){return E(this,void 0,void 0,function*(){var n,i;e??(e={});const r=fS(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield xh(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(Ir(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=H.Source.Microphone,this.emit(oe.AudioStreamAcquired)),Va(s)&&(this.cameraError=void 0,s.source=H.Source.Camera),s))}catch(a){throw a instanceof Error&&(e.audio&&(this.microphoneError=a),e.video&&(this.cameraError=a)),a}})}createScreenTracks(e){return E(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Gm("getDisplayMedia not supported");e.resolution===void 0&&!z8()&&(e.resolution=Xm.h1080fps30.resolution);const n=R8(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new na("no video track found");const a=new _h(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=H.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);const o=[a];if(i.getAudioTracks().length>0){this.emit(oe.AudioStreamAcquired);const s=new yh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=H.Source.ScreenShareAudio,o.push(s)}return o})}publishTrack(e,n){return E(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var s,l,c,u;ia(i)&&i.setAudioContext(a.audioContext),yield(s=a.reconnectFuture)===null||s===void 0?void 0:s.promise,a.republishPromise&&!o&&(yield a.republishPromise),Hs(i)&&a.pendingPublishPromises.has(i)&&(yield a.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let g;switch(i.source){case H.Source.Microphone:g="audioinput";break;case H.Source.Camera:g="videoinput"}g&&a.activeDeviceMap.has(g)&&(d=Object.assign(Object.assign({},d),{deviceId:a.activeDeviceMap.get(g)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new yh(i,d,!0,a.audioContext,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;case"video":i=new _h(i,d,!0,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;default:throw new na("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});let h;if(a.trackPublications.forEach(g=>{g.track&&g.track===i&&(h=g)}),h)return a.log.warn("track has already been published, skipping",Object.assign(Object.assign({},a.logContext),je(h))),h;const p=Object.assign(Object.assign({},a.roomOptions.publishDefaults),r),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(l=p.forceStereo)!==null&&l!==void 0?l:b;m&&(p.dtx===void 0&&a.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},a.logContext),je(i))),p.red===void 0&&a.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=p.dtx)!==null&&c!==void 0||(p.dtx=!1),(u=p.red)!==null&&u!==void 0||(p.red=!1)),!q8()&&a.roomOptions.e2ee&&(a.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},a.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const S=new Promise((g,y)=>E(a,void 0,void 0,function*(){try{if(this.engine.client.currentState!==mt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:je(i)}));let x=!1;const v=setTimeout(()=>{x=!0,i.stop(),y(new uS("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(v),x)return;const k=yield this.publish(i,p,m);g(k)}else try{const x=yield this.publish(i,p,m);g(x)}catch(x){y(x)}}catch(x){y(x)}}));a.pendingPublishPromises.set(i,S);try{return yield S}catch(g){throw g}finally{a.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new qi),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),je(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>M8(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),je(e))),!1)}publish(e,n,i){return E(this,void 0,void 0,function*(){var r,a,o,s,l,c,u,d,h,p;if(!this.hasPermissionsToPublish(e))throw new uS("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Hs(e)&&A.source===e.source)&&e.source!==H.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),je(e))),n.stopMicTrackOnMute&&Ir(e)&&(e.stopOnMute=!0),e.source===H.Source.ScreenShare&&Xo()&&(n.simulcast=!1),n.videoCodec==="av1"&&!j8()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!B8()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=vg),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>n.videoCodec===yc(A.mime))||(n.videoCodec=yc(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;e.on(ee.Muted,this.onTrackMuted),e.on(ee.Unmuted,this.onTrackUnmuted),e.on(ee.Ended,this.handleTrackEnded),e.on(ee.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ee.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ee.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],g=!(!((r=n.dtx)!==null&&r!==void 0)||r),y=e.getSourceTrackSettings();y.autoGainControl&&S.push(dn.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&S.push(dn.TF_ECHO_CANCELLATION),y.noiseSuppression&&S.push(dn.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&S.push(dn.TF_STEREO),g&&S.push(dn.TF_NO_DTX),ia(e)&&e.hasPreConnectBuffer&&S.push(dn.TF_PRECONNECT_BUFFER);const x=new mc({cid:e.mediaStreamTrack.id,name:n.name,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((a=n.red)!==null&&a!==void 0)||a),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:S});let v;if(e.kind===H.Kind.Video){let A={width:0,height:0};try{A=yield e.waitForDimensions()}catch{const O=(s=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&s!==void 0?s:bc.h720.resolution;A={width:O.width,height:O.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{dims:A}))}x.width=A.width,x.height=A.height,Ga(e)&&(ur(m)&&(e.source===H.Source.ScreenShare&&(n.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),je(e))))),n.scalabilityMode=(l=n.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),x.simulcastCodecs=[new Em({codec:m,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:vg}),n.backupCodec&&m!==n.backupCodec.codec&&x.encryption===an.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Em({codec:n.backupCodec.codec,cid:""})))),v=kg(e.source===H.Source.ScreenShare,x.width,x.height,n),x.layers=ek(x.width,x.height,v,ur(n.videoCodec))}else e.kind===H.Kind.Audio&&(v=[{maxBitrate:(c=n.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(u=n.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(p=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new on("cannot publish track when not connected");const k=()=>E(this,void 0,void 0,function*(){var A,N,O;if(!this.engine.pcManager)throw new on("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,v),this.emit(oe.LocalSenderCreated,e.sender,e),Ga(e)&&((A=n.degradationPreference)!==null&&A!==void 0||(n.degradationPreference=WD(e)),e.setDegradationPreference(n.degradationPreference)),v)if(Xo()&&e.kind===H.Kind.Audio){let B;for(const W of this.engine.pcManager.publisher.getTransceivers())if(W.sender===e.sender){B=W;break}B&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:B,codec:"opus",maxbr:!((N=v[0])===null||N===void 0)&&N.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&ur(e.codec)&&(!((O=v[0])===null||O===void 0)&&O.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const C=new Promise((A,N)=>E(this,void 0,void 0,function*(){var O;try{T=yield this.engine.addTrack(x),A(T)}catch(B){e.sender&&(!((O=this.engine.pcManager)===null||O===void 0)&&O.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(W=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{error:W}))})),N(B)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([C,k()]))[0];else{T=yield C;let A;if(T.codecs.forEach(N=>{A===void 0&&(A=N.mimeType)}),A&&e.kind===H.Kind.Video){const N=yc(A);N!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{codec:N})),n.videoCodec=N,v=kg(e.source===H.Source.ScreenShare,x.width,x.height,n))}yield k()}const R=new Rg(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(R.on(ee.CpuConstrained,A=>this.onTrackCpuConstrained(A,R)),R.options=n,e.sid=T.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:T})),Ga(e)?e.startMonitor(this.engine.client):ia(e)&&e.startMonitor(),this.addTrackPublication(R),this.emit(oe.LocalTrackPublished,R),ia(e)&&T.audioFeatures.includes(dn.TF_PRECONNECT_BUFFER)){const A=e.getPreConnectBuffer(),N=e.getPreConnectBufferMimeType();this.on(oe.LocalTrackSubscribed,O=>{if(O.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),je(e))),e.stopPreConnectBuffer()}}),A&&new Promise((B,W)=>E(this,void 0,void 0,function*(){var L,K,P,V,X,te;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),je(e)));const Q=setTimeout(()=>{W(new Error("agent not active within 10 seconds"))},1e4),ce=yield this.waitUntilActiveAgentPresent();clearTimeout(Q),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),je(e)));const j=yield this.streamBytes({name:"preconnect-buffer",mimeType:N,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ce.identity],attributes:{trackId:R.trackSid,sampleRate:String((X=y.sampleRate)!==null&&X!==void 0?X:"48000"),channels:String((te=y.channelCount)!==null&&te!==void 0?te:"1")}});try{for(var $=!0,z=ta(A),Z;Z=yield z.next(),L=Z.done,!L;$=!0){V=Z.value,$=!1;const ge=V;yield j.write(ge)}}catch(ge){K={error:ge}}finally{try{!$&&!L&&(P=z.return)&&(yield P.call(z))}finally{if(K)throw K.error}}yield j.close(),B()}catch(Q){W(Q)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),je(e)))}).catch(B=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{error:B}))})}return R})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return E(this,void 0,void 0,function*(){var r;if(this.encryptionType!==an.NONE)return;let a;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(a=p)}),!a)throw new na("track is not published");if(!Ga(e))throw new na("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),s=HD(e,n,o);if(!s){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),je(e)));return}const l=e.addSimulcastTrack(n,s);if(!l)return;const c=new mc({cid:l.mediaStreamTrack.id,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=ek(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new on("cannot publish track when not connected");const u=()=>E(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,l,o,s),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:h}))})}unpublishTrack(e,n){return E(this,void 0,void 0,function*(){var i,r;if(Hs(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),je(e))),yield c)}const a=this.getPublicationForTrack(e),o=a?je(a):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!a||!a.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=a.track,e.off(ee.Muted,this.onTrackMuted),e.off(ee.Unmuted,this.onTrackUnmuted),e.off(ee.Ended,this.handleTrackEnded),e.off(ee.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ee.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ee.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let s=!1;const l=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Lt.FAILED&&l)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===l&&(c.direction="inactive",s=!0);if(this.engine.removeTrack(l)&&(s=!0),Ga(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(s=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:c}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case H.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case H.Kind.Video:this.videoTrackPublications.delete(a.trackSid);break}return this.emit(oe.LocalTrackUnpublished,a),a.setTrack(void 0),s&&(yield this.engine.negotiate()),a})}unpublishTracks(e){return E(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return E(this,arguments,void 0,function(n){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((a,o)=>E(i,void 0,void 0,function*(){try{const s=[];this.trackPublications.forEach(l=>{l.track&&(n&&(l.options=Object.assign(Object.assign({},l.options),n)),s.push(l))}),yield Promise.all(s.map(l=>E(this,void 0,void 0,function*(){const c=l.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==H.Source.ScreenShare&&c.source!==H.Source.ScreenShareAudio&&(ia(c)||Ga(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:l.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,l.options,!0)}))),a()}catch(s){o(s)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const a=r.reliable?Oe.RELIABLE:Oe.LOSSY,o=r.destinationIdentities,s=r.topic;let l=new xm({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:s});const c=new Wn({kind:a,value:{case:"user",value:l}});yield i.engine.sendDataPacket(c,a)}()})}publishDtmf(e,n){return E(this,void 0,void 0,function*(){const i=new Wn({kind:Oe.RELIABLE,value:{case:"sipDtmf",value:new Z_({code:e,digit:n})}});yield this.engine.sendDataPacket(i,Oe.RELIABLE)})}sendChatMessage(e,n){return E(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new Wn({value:{case:"chatMessage",value:new Zd(Object.assign(Object.assign({},i),{timestamp:Nt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(oe.ChatMessage,i),i})}editChatMessage(e,n){return E(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new Wn({value:{case:"chatMessage",value:new Zd(Object.assign(Object.assign({},i),{timestamp:Nt.parse(i.timestamp),editTimestamp:Nt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(oe.ChatMessage,i),i})}sendText(e,n){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return E(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:a,payload:o,responseTimeout:s=15e3}=n;return function*(){return new Promise((u,d)=>E(i,void 0,void 0,function*(){var h,p,b,m;if(yg(o)>WS){d(It.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((p=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||p===void 0)&&p.version&&Lr((m=(b=this.engine.latestJoinResponse)===null||b===void 0?void 0:b.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){d(It.builtIn("UNSUPPORTED_SERVER"));return}const S=Math.max(s,8e3),g=crypto.randomUUID();yield this.publishRpcRequest(r,g,a,o,S);const y=setTimeout(()=>{this.pendingAcks.delete(g),d(It.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(x)},7e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(y)},participantIdentity:r});const x=setTimeout(()=>{this.pendingResponses.delete(g),d(It.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(g,{resolve:(v,k)=>{clearTimeout(x),this.pendingAcks.has(g)&&(this.log.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(y)),k?d(k):u(v??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,n){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,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,a){return E(this,void 0,void 0,function*(){const o=new Wn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcRequest",value:new Sm({id:n,method:i,payload:r,responseTimeoutMs:a,version:1})}});yield this.engine.sendDataPacket(o,Oe.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,It.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const a=this.trackPublications.get(n.sid);if(a){const o=a.isMuted||((r=(i=a.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),je(a)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,a;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(a=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||a===void 0||a.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new qi),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(ia(r)||Ga(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return E(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(a=>{let[o]=a;return o.source===e});if(r)return r[1];yield Cn(20)}})}}class pP extends ra{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=a=>{this.setTrack(void 0),this.emit(ee.Ended,a)},this.handleVisibilityChange=a=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(a),this.logContext),this.visible=a,this.emitTrackUpdate()},this.handleVideoDimensionsChange=a=>{this.log.debug("adaptivestream video dimensions ".concat(a.width,"x").concat(a.height),this.logContext),this.videoDimensionsAdaptiveStream=a,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new ah({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tx({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ee.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?ra.SubscriptionStatus.Unsubscribed:super.isSubscribed?ra.SubscriptionStatus.Subscribed:ra.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ra.PermissionStatus.Allowed:ra.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(sg(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&sg(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:wi.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(ee.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(ee.VisibilityChanged,this.handleVisibilityChange),r.off(ee.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(ee.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ee.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ee.VisibilityChanged,this.handleVisibilityChange),e.on(ee.Ended,this.handleEnded),this.emit(ee.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(ee.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?ee.Muted:ee.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(ee.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ee.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sg(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new hx({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===H.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)vS(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=D8(this.trackInfo,this.requestedMaxQuality);i&&vS(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:wi.HIGH})),e.quality=wi.HIGH)}this.emit(ee.UpdateSettings,e)}}class Sh extends lk{static fromParticipantInfo(e,n,i){return new Sh(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,a,o,s){let l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:pc.STANDARD;super(n,i||"",r,a,o,s,l),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ee.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),je(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(ee.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(ee.SubscriptionPermissionChanged,n=>{this.emit(oe.TrackSubscriptionPermissionChanged,e,n)}),e.on(ee.SubscriptionStatusChanged,n=>{this.emit(oe.TrackSubscriptionStatusChanged,e,n)}),e.on(ee.Subscribed,n=>{this.emit(oe.TrackSubscribed,n,e)}),e.on(ee.Unsubscribed,n=>{this.emit(oe.TrackUnsubscribed,n,e)}),e.on(ee.SubscriptionFailed,n=>{this.emit(oe.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:H.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:H.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,a,o){let s=this.getTrackPublicationBySid(n);if(s||n.startsWith("TR")||this.trackPublications.forEach(u=>{!s&&e.kind===u.kind.toString()&&(s=u)}),!s){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(oe.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,a,o-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),je(s))),this.emit(oe.TrackSubscriptionFailed,n);return}const l=e.kind==="video";let c;return l?c=new sP(e,n,r,a):c=new oP(e,n,r,this.audioContext,this.audioOutput),c.source=s.source,c.isMuted=s.isMuted,c.setMediaStream(i),c.start(),s.setTrack(c),this.volumeMap.has(s.source)&&og(c)&&Ir(c)&&c.setVolume(this.volumeMap.get(s.source)),s}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var a,o;let s=this.getTrackPublicationBySid(r.sid);if(s)s.updateInfo(r);else{const l=H.kindFromProto(r.type);if(!l)return;s=new pP(l,r,(a=this.signalClient.connectOptions)===null||a===void 0?void 0:a.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),s.updateInfo(r),i.set(r.sid,s);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(s==null?void 0:s.source));c&&s.source!==H.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:je(c),newTrack:je(s)})),this.addTrackPublication(s)}n.set(r.sid,s)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),je(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(oe.TrackPublished,r)}),!0}unpublishTrack(e,n){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 H.Kind.Audio:this.audioTrackPublications.delete(e);break;case H.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(oe.TrackUnpublished,i)}setAudioOutput(e){return E(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Ir(i.track)&&og(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;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 Xe;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(Xe||(Xe={}));const mP=4*1e3;class Ys extends Mr.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var n,i,r,a;if(super(),n=this,this.state=Xe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ee,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,s,l)=>E(this,void 0,void 0,function*(){var c;if(!U8())throw Pr()?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===Xe.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(Xe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==RS(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),qs(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ke(o,s):this.regionUrlProvider.updateToken(s),this.regionUrlProvider.fetchRegionSettings().then(p=>{var b;(b=this.regionUrlProvider)===null||b===void 0||b.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const d=(p,b,m)=>E(this,void 0,void 0,function*(){var S,g;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{if(yield Vs.getInstance().getBackOffPromise(o),y.signal.aborted)throw _e.cancelled("Connection attempt aborted");yield this.attemptConnection(m??o,s,l,y),this.abortController=void 0,p()}catch(x){if(this.regionUrlProvider&&x instanceof _e&&x.reason!==kt.Cancelled&&x.reason!==kt.NotAllowed){let v=null;try{this.log.debug("Fetching next region"),v=yield this.regionUrlProvider.getNextBestRegionUrl((S=this.abortController)===null||S===void 0?void 0:S.signal)}catch(k){if(k instanceof _e&&(k.status===401||k.reason===kt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),b(k);return}}[kt.InternalError,kt.ServerUnreachable,kt.Timeout].includes(x.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Vs.getInstance().addFailedConnectionAttempt(o)),v&&!(!((g=this.abortController)===null||g===void 0)&&g.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield d(p,b,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ES(x)),b(x))}else{let v=sr.UNKNOWN_REASON;x instanceof _e&&(v=ES(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),b(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new qi((p,b)=>{d(p,b,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,s,l,c,u,d)=>E(this,void 0,void 0,function*(){var h,p,b;const m=yield l.join(o,s,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout,singlePeerConnection:u.singlePeerConnection},d.signal);let S=m.serverInfo;if(S||(S={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=S,this.log.debug("connected to Livekit Server ".concat(Object.entries(S).map(g=>{let[y,x]=g;return"".concat(y,": ").concat(x)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(p=m.room)===null||p===void 0?void 0:p.sid,identity:(b=m.participant)===null||b===void 0?void 0:b.identity}),!S.version)throw new x8("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=o=>{const s=o.participant;if(this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([s,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,s,l,c)=>E(this,void 0,void 0,function*(){var u,d;this.state===Xe.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({},bg),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,s,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(J.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const p=c.signal.aborted?_e.cancelled("Signal connection aborted"):_e.serverUnreachable("could not establish signal connection");throw h instanceof Error&&(p.message="".concat(p.message,": ").concat(h.message)),h instanceof _e&&(p.reason=h.reason,p.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),p}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),_e.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}di()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),di()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Xe.Connected),this.emit(J.Connected),Vs.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,s=new Array(o),l=0;l<o;l++)s[l]=arguments[l];return E(n,[...s],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,p;const b=yield c.disconnectLock.lock();try{if(c.state===Xe.Disconnected){c.log.debug("already disconnected",c.logContext);return}if(c.log.info("disconnect from room",Object.assign({},c.logContext)),c.state===Xe.Connecting||c.state===Xe.Reconnecting||c.isResuming){const m="Abort connection attempt due to user initiated disconnect";c.log.warn(m,c.logContext),(d=c.abortController)===null||d===void 0||d.abort(m),(p=(h=c.connectFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,_e.cancelled("Client initiated disconnect")),c.connectFuture=void 0}c.engine&&(c.engine.client.isDisconnected||(yield c.engine.client.sendLeave()),yield c.engine.close()),c.handleDisconnect(u,sr.CLIENT_INITIATED),c.engine=void 0}finally{b()}}()})},this.onPageLeave=()=>E(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>E(this,void 0,void 0,function*(){const o=[],s=ui();if(s&&s.os==="iOS"){const l="livekit-dummy-audio-el";let c=document.getElementById(l);if(!c){c=document.createElement("audio"),c.id=l,c.autoplay=!0,c.hidden=!0;const u=ag();u.enabled=!0;const d=new MediaStream([u]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(J.Disconnected,()=>{c==null||c.remove(),c=null})}o.push(c)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>E(this,void 0,void 0,function*(){const o=[];for(const s of this.remoteParticipants.values())s.videoTrackPublications.forEach(l=>{var c;(c=l.track)===null||c===void 0||c.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(s=>s.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(s=>{s.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 o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(Xe.Reconnecting)&&this.emit(J.Reconnecting)},this.handleSignalRestarted=o=>E(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(s){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:s}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(Xe.Connected),this.emit(J.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(s=>{var l;if(s.identity===this.localParticipant.identity){this.localParticipant.updateInfo(s);return}s.identity===""&&(s.identity=(l=this.sidToIdentity.get(s.sid))!==null&&l!==void 0?l:"");let c=this.remoteParticipants.get(s.identity);s.state===Ls.DISCONNECTED?this.handleParticipantDisconnected(s.identity,c):c=this.getOrCreateParticipant(s.identity,s)})},this.handleActiveSpeakersUpdate=o=>{const s=[],l={};o.forEach(c=>{if(l[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),s.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),s.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{l[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=s,this.emitWhenConnected(J.ActiveSpeakersChanged,s)},this.handleSpeakersChanged=o=>{const s=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||s.set(c.sid,c)}),o.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?s.set(c.sid,u):s.delete(c.sid))});const l=Array.from(s.values());l.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(J.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(s=>{const l=this.getRemoteParticipantBySid(s.participantSid);if(!l)return;const c=l.getTrackPublicationBySid(s.trackSid);if(!c||!c.track)return;const u=H.streamStateFromProto(s.state);c.track.setStreamState(u),u!==c.track.streamState&&(l.emit(oe.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(J.TrackStreamStateChanged,c,c.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=o=>{const s=this.getRemoteParticipantBySid(o.participantSid);if(!s)return;const l=s.getTrackPublicationBySid(o.trackSid);l&&l.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const s=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(o.trackSid));if(!s)return;const l=s.getTrackPublicationBySid(o.trackSid);l&&l.setSubscriptionError(o.err)},this.handleDataPacket=(o,s)=>{const l=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(l,o.value.value,o.kind,s);else if(o.value.case==="transcription")this.handleTranscription(l,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(l,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(l,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,l);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,s);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,s,l,c)=>{this.emit(J.DataReceived,s.payload,o,l,s.topic,c),o==null||o.emit(oe.DataReceived,s.payload,l,c)},this.handleSipDtmf=(o,s)=>{this.emit(J.SipDTMFReceived,s,o),o==null||o.emit(oe.SipDTMFReceived,s)},this.handleTranscription=(o,s)=>{const l=s.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(s.transcribedParticipantIdentity),c=l==null?void 0:l.trackPublications.get(s.trackId),u=K8(s,this.transcriptionReceivedTimes);c==null||c.emit(ee.TranscriptionReceived,u),l==null||l.emit(oe.TranscriptionReceived,u,c),this.emit(J.TranscriptionReceived,u,l,c)},this.handleChatMessage=(o,s)=>{const l=X8(s);this.emit(J.ChatMessage,l,o)},this.handleMetrics=(o,s)=>{this.emit(J.MetricsReceived,o,s)},this.handleDataStream=(o,s)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,s)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(J.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(J.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(J.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(J.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>E(this,void 0,void 0,function*(){var o;((o=ui())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(J.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const s=this.roomInfo;this.roomInfo=o,s&&s.metadata!==o.metadata&&this.emitWhenConnected(J.RoomMetadataChanged,o.metadata),(s==null?void 0:s.activeRecording)!==o.activeRecording&&this.emitWhenConnected(J.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(s=>{if(s.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(s.quality);return}const l=this.getRemoteParticipantBySid(s.participantSid);l&&l.setConnectionQuality(s.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(J.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(J.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(J.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(J.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(J.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var s;(s=o==null?void 0:o.onPublish)===null||s===void 0||s.call(o,this)},this.onLocalTrackPublished=o=>E(this,void 0,void 0,function*(){var s,l,c,u,d,h;(s=o.track)===null||s===void 0||s.on(ee.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.on(ee.Restarted,this.onLocalTrackRestarted),(d=(u=(c=o.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(J.LocalTrackPublished,o,this.localParticipant),ia(o.track)&&(yield o.track.checkForSilence())&&this.emit(J.LocalAudioSilenceDetected,o);const p=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),b=Qm(o.source);b&&p&&p!==this.localParticipant.activeDeviceMap.get(b)&&(this.localParticipant.activeDeviceMap.set(b,p),this.emit(J.ActiveDeviceChanged,b,p))}),this.onLocalTrackUnpublished=o=>{var s,l;(s=o.track)===null||s===void 0||s.off(ee.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.off(ee.Restarted,this.onLocalTrackRestarted),this.emit(J.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>E(this,void 0,void 0,function*(){const s=yield o.getDeviceId(!1),l=Qm(o.source);l&&s&&s!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(s," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,s),this.emit(J.ActiveDeviceChanged,l,s))}),this.onLocalConnectionQualityChanged=o=>{this.emit(J.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,s)=>{this.emit(J.MediaDevicesError,o,s)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(J.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(J.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},CD),e),this.log=ea((i=this.options.loggerName)!==null&&i!==void 0?i:cr.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},HS),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},VS),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},wD),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new nP,this.outgoingDataStreamManager=new aP(this.engine,this.log),this.disconnectLock=new Gn,this.localParticipant=new fP("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ha(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ha(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Ha(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),di()){const o=new AbortController;(a=navigator.mediaDevices)===null||a===void 0||a.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),Ys.cleanupRegistry&&Ys.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){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,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return E(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;const n=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new lD(i,n),this.e2eeManager.on(Ya.ParticipantEncryptionStatusChanged,(r,a)=>{J8(a)&&(this.isE2EEEnabled=r),this.emit(J.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(Ya.EncryptionError,(r,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(J.EncryptionError,r,o)}),(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,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return E(this,void 0,void 0,function*(){return this.state===Xe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(re.RoomUpdate,i),e(r.sid))};this.engine.on(re.RoomUpdate,i),this.once(J.Disconnected,()=>{this.engine.off(re.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new QD(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(re.ParticipantUpdate,this.handleParticipantUpdates).on(re.RoomUpdate,this.handleRoomUpdate).on(re.SpeakersChanged,this.handleSpeakersChanged).on(re.StreamStateChanged,this.handleStreamStateUpdate).on(re.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(re.SubscriptionError,this.handleSubscriptionError).on(re.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(re.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(re.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(re.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(re.DataPacketReceived,this.handleDataPacket).on(re.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Xe.SignalReconnecting)&&this.emit(J.SignalReconnecting)}).on(re.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Xe.Connected)&&this.emit(J.Reconnected)}).on(re.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Xe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(re.Restarting,this.handleRestarting).on(re.SignalRestarted,this.handleSignalRestarted).on(re.Offline,()=>{this.setAndEmitConnectionState(Xe.Reconnecting)&&this.emit(J.Reconnecting)}).on(re.DCBufferStatusChanged,(e,n)=>{this.emit(J.DCBufferStatusChanged,e,n)}).on(re.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(oe.LocalTrackSubscribed,n),this.emitWhenConnected(J.LocalTrackSubscribed,n,this.localParticipant)}).on(re.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(J.Moved,e.room.name),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),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return hn.getInstance().getDevices(e,n)}prepareConnection(e,n){return E(this,void 0,void 0,function*(){if(this.state===Xe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(qs(new URL(e))&&n){this.regionUrlProvider=new Ke(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Xe.Disconnected&&(this.regionUrl=i,yield fetch(kc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(kc(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,n){return E(this,void 0,void 0,function*(){let i=()=>E(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Or({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Or({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Or({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Or({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=()=>E(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Or({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>E(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Or({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 Or({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>E(this,void 0,void 0,function*(){const a=this.engine.client.onLeave;a&&a(new oh({reason:sr.CLIENT_INITIATED,action:js.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Or({scenario:{case:"subscriberBandwidth",value:Jo(n)}});break;case"leave-full-reconnect":r=new Or({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,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var s,l,c,u,d,h,p;let b=!0,m=!1;const S=o?{exact:r}:r;if(i==="audioinput"){m=a.localParticipant.audioTrackPublications.size===0;const g=(s=a.getActiveDevice(i))!==null&&s!==void 0?s:a.options.audioCaptureDefaults.deviceId;a.options.audioCaptureDefaults.deviceId=S;const y=Array.from(a.localParticipant.audioTrackPublications.values()).filter(v=>v.source===H.Source.Microphone);try{b=(yield Promise.all(y.map(v=>{var k;return(k=v.audioTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(v=>v===!0)}catch(v){throw a.options.audioCaptureDefaults.deviceId=g,v}const x=y.some(v=>{var k,T;return(T=(k=v.track)===null||k===void 0?void 0:k.isMuted)!==null&&T!==void 0?T:!1});b&&x&&(m=!0)}else if(i==="videoinput"){m=a.localParticipant.videoTrackPublications.size===0;const g=(l=a.getActiveDevice(i))!==null&&l!==void 0?l:a.options.videoCaptureDefaults.deviceId;a.options.videoCaptureDefaults.deviceId=S;const y=Array.from(a.localParticipant.videoTrackPublications.values()).filter(v=>v.source===H.Source.Camera);try{b=(yield Promise.all(y.map(v=>{var k;return(k=v.videoTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(v=>v===!0)}catch(v){throw a.options.videoCaptureDefaults.deviceId=g,v}const x=y.some(v=>{var k,T;return(T=(k=v.track)===null||k===void 0?void 0:k.isMuted)!==null&&T!==void 0?T:!1});b&&x&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!tg()&&!a.options.webAudioMix||a.options.webAudioMix&&a.audioContext&&!("setSinkId"in a.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");a.options.webAudioMix&&(r=(c=yield hn.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(p=a.options).audioOutput)!==null&&u!==void 0||(p.audioOutput={});const g=(d=a.getActiveDevice(i))!==null&&d!==void 0?d:a.options.audioOutput.deviceId;a.options.audioOutput.deviceId=r;try{a.options.webAudioMix&&((h=a.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(a.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:r})))}catch(y){throw a.options.audioOutput.deviceId=g,y}}return m&&(a.localParticipant.activeDeviceMap.set(i,r),a.emit(J.ActiveDeviceChanged,i,r)),b}()})}setupLocalParticipantEvents(){this.localParticipant.on(oe.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(oe.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(oe.AttributesChanged,this.onLocalAttributesChanged).on(oe.TrackMuted,this.onLocalTrackMuted).on(oe.TrackUnmuted,this.onLocalTrackUnmuted).on(oe.LocalTrackPublished,this.onLocalTrackPublished).on(oe.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(oe.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(oe.MediaDevicesError,this.onMediaDevicesError).on(oe.AudioStreamAcquired,this.startAudio).on(oe.ChatMessage,this.onLocalChatMessageSent).on(oe.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,n,i){if(this.state===Xe.Connecting||this.state===Xe.Reconnecting){const d=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map(p=>p.id)}),this.onTrackAdded(e,n,i),h()},h=()=>{this.off(J.Reconnected,d),this.off(J.Connected,d),this.off(J.Disconnected,h)};this.once(J.Reconnected,d),this.once(J.Connected,d),this.once(J.Disconnected,h);return}if(this.state===Xe.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=I8(n.id),a=r[0];let o=r[1],s=e.id;if(o&&o.startsWith("TR")&&(s=o),a===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const l=Array.from(this.remoteParticipants.values()).find(d=>d.sid===a);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a),this.logContext);return}if(!s.startsWith("TR")){const d=this.engine.getTrackIdForReceiver(i);if(!d){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a),this.logContext);return}s=d}s.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(o,", trackId: ").concat(s),Object.assign(Object.assign({},this.logContext),{rpID:a,streamId:o,trackId:s}));let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const u=l.addSubscribedMediaTrack(e,s,n,i,c);u!=null&&u.isEncrypted&&!this.e2eeManager&&this.emit(J.EncryptionError,new Error("Encrypted ".concat(u.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Xe.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,s;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(s=r.track)===null||s===void 0||s.stopMonitor()}),this.localParticipant.off(oe.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(oe.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(oe.AttributesChanged,this.onLocalAttributesChanged).off(oe.TrackMuted,this.onLocalTrackMuted).off(oe.TrackUnmuted,this.onLocalTrackUnmuted).off(oe.LocalTrackPublished,this.onLocalTrackPublished).off(oe.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(oe.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(oe.MediaDevicesError,this.onMediaDevicesError).off(oe.AudioStreamAcquired,this.startAudio).off(oe.ChatMessage,this.onLocalChatMessageSent).off(oe.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),di()&&(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(Xe.Disconnected),this.emit(J.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(J.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,a,o){return E(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,It.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(e,n,null,It.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield s({requestId:n,callerIdentity:e,payload:r,responseTimeout:a});yg(u)>WS?(l=It.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof It?l=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=It.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,c,l)})}selectDefaultDevices(){return E(this,void 0,void 0,function*(){var e,n,i;const r=hn.getInstance().previousDevices,a=yield hn.getInstance().getDevices(void 0,!1),o=ui();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let l of a){const c=r.find(u=>u.deviceId===l.deviceId);c&&c.label!==""&&c.kind===l.kind&&c.label!==l.label&&this.getActiveDevice(l.kind)==="default"&&this.emit(J.ActiveDeviceChanged,l.kind,l.deviceId)}const s=["audiooutput","audioinput","videoinput"];for(let l of s){const c=E8(l),u=this.localParticipant.getTrackPublication(c);if(u&&(!((e=u.track)===null||e===void 0)&&e.isUserProvided))continue;const d=a.filter(p=>p.kind===l),h=this.getActiveDevice(l);if(h===((n=r.filter(p=>p.kind===l)[0])===null||n===void 0?void 0:n.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(l,d[0].deviceId);continue}l==="audioinput"&&!xc()||l==="videoinput"||d.length>0&&!d.find(p=>p.deviceId===this.getActiveDevice(l))&&(l!=="audiooutput"||!xc())&&(yield this.switchActiveDevice(l,d[0].deviceId))}})}acquireAudioContext(){return E(this,void 0,void 0,function*(){var e,n;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=mS())!==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(),Cn(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(J.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Sh.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Sh(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(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(J.ParticipantConnected,i),i.on(oe.TrackPublished,r=>{this.emitWhenConnected(J.TrackPublished,r,i)}).on(oe.TrackSubscribed,(r,a)=>{r.kind===H.Kind.Audio?(r.on(ee.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(ee.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===H.Kind.Video&&(r.on(ee.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(ee.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(J.TrackSubscribed,r,a,i)}).on(oe.TrackUnpublished,r=>{this.emit(J.TrackUnpublished,r,i)}).on(oe.TrackUnsubscribed,(r,a)=>{this.emit(J.TrackUnsubscribed,r,a,i)}).on(oe.TrackMuted,r=>{this.emitWhenConnected(J.TrackMuted,r,i)}).on(oe.TrackUnmuted,r=>{this.emitWhenConnected(J.TrackUnmuted,r,i)}).on(oe.ParticipantMetadataChanged,r=>{this.emitWhenConnected(J.ParticipantMetadataChanged,r,i)}).on(oe.ParticipantNameChanged,r=>{this.emitWhenConnected(J.ParticipantNameChanged,r,i)}).on(oe.AttributesChanged,r=>{this.emitWhenConnected(J.ParticipantAttributesChanged,r,i)}).on(oe.ConnectionQualityChanged,r=>{this.emitWhenConnected(J.ConnectionQualityChanged,r,i)}).on(oe.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(J.ParticipantPermissionsChanged,r,i)}).on(oe.TrackSubscriptionStatusChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionStatusChanged,r,a,i)}).on(oe.TrackSubscriptionFailed,(r,a)=>{this.emit(J.TrackSubscriptionFailed,r,i,a)}).on(oe.TrackSubscriptionPermissionChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionPermissionChanged,r,a,i)}).on(oe.Active,()=>{this.emitWhenConnected(J.ParticipantActive,i),i.kind===pc.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&$8(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=wn.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,sr.STATE_MISMATCH))):e=0},mP)}clearConnectionReconcile(){this.connectionReconcileInterval&&wn.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(J.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===Xe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Xe.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return E(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Jd({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Nt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Yo({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(J.SignalConnected),this.emit(J.Connected),this.setAndEmitConnectionState(Xe.Connected),r.video){const o=new Rg(H.Kind.Video,new Is({source:Xt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO,name:"video-dummy"}),new _h(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:CS(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(oe.LocalTrackPublished,o)}if(r.audio){const o=new Rg(H.Kind.Audio,new Is({source:Xt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO}),new yh(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ag(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(oe.LocalTrackPublished,o)}for(let o=0;o<a.count-1;o+=1){let s=new Yo({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Ls.ACTIVE,tracks:[],joinedAt:Nt.parse(Date.now())});const l=this.getOrCreateParticipant(s.identity,s);if(a.video){const c=CS(160*((i=a.aspectRatios[o%a.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Is({source:Xt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}if(a.audio){const c=ag(),u=new Is({source:Xt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:or.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}l.updateInfo(s)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==J.ActiveSpeakersChanged&&e!==J.TranscriptionReceived){const a=ck(i).filter(o=>o!==void 0);(e===J.TrackSubscribed||e===J.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:a})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:a}))}return super.emit(e,...i)}}Ys.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function ck(t){return t.map(e=>{if(e)return Array.isArray(e)?ck(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var hr;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(hr||(hr={}));class $a extends Mr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=hr.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new Ys(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return E(this,void 0,void 0,function*(){if(this.status!==hr.IDLE)throw Error("check is running already");this.setStatus(hr.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==hr.SKIPPED&&this.setStatus(this.isSuccess()?hr.SUCCESS:hr.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return E(this,void 0,void 0,function*(){return this.room.state===Xe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return E(this,void 0,void 0,function*(){this.room&&this.room.state!==Xe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(hr.SKIPPED)}switchProtocol(e){return E(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(J.Reconnecting,()=>{n=!0}),this.room.once(J.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(a=>setTimeout(a,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Cn(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 gP extends $a{get description(){return"Cloud regions"}perform(){return E(this,void 0,void 0,function*(){const e=new Ke(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let a=0;a<3;a++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const s=yield this.checkCloudRegion(o);this.appendMessage("".concat(s.region," RTT: ").concat(s.rtt,"ms, duration: ").concat(s.duration,"ms")),n.push(s)}n.sort((a,o)=>(a.duration-o.duration)*.5+(a.rtt-o.rtt)*.5);const r=n[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 E(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const a=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,l=1e6/o,c="A".repeat(o),u=Date.now();for(let b=0;b<l;b++)yield a.write(c);yield a.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(p.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Ag=1e4;class vP extends $a{get description(){return"Connection via UDP vs TCP"}perform(){return E(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):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/(Ag/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Ag/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return E(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const a=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(a)};a();const s=n.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(s,{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(()=>E(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(u.packetsSent=p.packetsSent,u.qualityLimitationDurations=p.qualityLimitationDurations,u.bitrateTotal+=p.targetBitrate,u.count++):p.type==="remote-inbound-rtp"&&(u.packetsLost=p.packetsLost,u.rttTotal+=p.roundTripTime,u.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Ag)),clearInterval(d),s.stop(),n.remove(),yield this.disconnect(),u})}}class bP extends $a{get description(){return"Can publish audio"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield uP();if(yield pS(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(s=>setTimeout(s,3e3));const a=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!a)throw new Error("Could not get RTCStats");let o=0;if(a.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="audio"||!s.kind&&s.mediaType==="audio")&&(o=s.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class yP extends $a{get description(){return"Can publish video"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield cP();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,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 a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(a+=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," video packets"))})}checkForVideo(e){return E(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var a,o,s,l;const c=document.createElement("canvas"),u=e.getSettings(),d=(o=(a=u.width)!==null&&a!==void 0?a:i.videoWidth)!==null&&o!==void 0?o:1280,h=(l=(s=u.height)!==null&&s!==void 0?s:i.videoHeight)!==null&&l!==void 0?l:720;c.width=d,c.height=h;const p=c.getContext("2d");p.drawImage(i,0,0);const m=p.getImageData(0,0,c.width,c.height).data;let S=!0;for(let g=0;g<m.length;g+=4)if(m[g]!==0||m[g+1]!==0||m[g+2]!==0){S=!1;break}S?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class _P extends $a{get description(){return"Resuming connection after interruption"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,a;const o=new Promise(c=>{setTimeout(c,5e3),a=c}),s=()=>{i=!0};n.on(J.SignalReconnecting,s).on(J.Reconnecting,s).on(J.Reconnected,()=>{r=!0,a(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const l=n.engine.client.onClose;if(l&&l(""),yield o,i){if(!r||n.state!==Xe.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 xP extends $a{get description(){return"Can connect via TURN"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;qs(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ke(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new ug,a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1});let o=!1,s=!1,l=!1;for(let c of a.iceServers)for(let u of c.urls)u.startsWith("turn:")?(s=!0,l=!0):u.startsWith("turns:")&&(s=!0,l=!0,o=!0),u.startsWith("stun:")&&(l=!0);l?s&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(n=this.connectOptions)===null||n===void 0?void 0:n.rtcConfig)===null||i===void 0)&&i.iceServers||s?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 SP extends $a{get description(){return"Establishing WebRTC connection"}perform(){return E(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(J.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(a,o)=>{if(a.candidate){const s=new RTCIceCandidate(a);let l="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(kP(s.address)?l+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,l+=" (passive)"):s.protocol==="udp"&&(n=!0)),this.appendMessage(l)}r&&r(a,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=a=>{a instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(a.errorCode," ").concat(a.errorText," ").concat(a.url))})});try{yield this.connect(),Ee.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"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function kP(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class TP extends $a{get description(){return"Connecting to signal connection via WebSocket"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ug,a;try{a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1})}catch(o){if(qs(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const l=yield new Ke(this.url,this.token).getNextBestRegionUrl();l&&(a=yield r.join(l,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1}),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}a?(this.appendMessage("Connected to server, version ".concat(a.serverVersion,".")),((e=a.serverInfo)===null||e===void 0?void 0:e.edition)===ix.Cloud&&(!((n=a.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=a.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class SW extends Mr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:hr.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==hr.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return E(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const a=yield i.run();return i.off("update",r),a})}checkWebsocket(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(TP)})}checkWebRTC(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(SP)})}checkTURN(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(xP)})}checkReconnect(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(_P)})}checkPublishAudio(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(bP)})}checkPublishVideo(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(yP)})}checkConnectionProtocol(){return E(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(vP);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(gP)})}}function Be(t,e,n){return(e=CP(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wP(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function CP(t){var e=wP(t,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class Kn extends Error{constructor(e,n){var i;super(e,n),Be(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Be(Kn,"code","ERR_JOSE_GENERIC");class EP extends Kn{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),Be(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Be(this,"claim",void 0),Be(this,"reason",void 0),Be(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}Be(EP,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class RP extends Kn{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),Be(this,"code","ERR_JWT_EXPIRED"),Be(this,"claim",void 0),Be(this,"reason",void 0),Be(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}Be(RP,"code","ERR_JWT_EXPIRED");class AP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Be(AP,"code","ERR_JOSE_ALG_NOT_ALLOWED");class NP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Be(NP,"code","ERR_JOSE_NOT_SUPPORTED");class OP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Be(OP,"code","ERR_JWE_DECRYPTION_FAILED");class MP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWE_INVALID")}}Be(MP,"code","ERR_JWE_INVALID");class DP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWS_INVALID")}}Be(DP,"code","ERR_JWS_INVALID");class PP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWT_INVALID")}}Be(PP,"code","ERR_JWT_INVALID");class LP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWK_INVALID")}}Be(LP,"code","ERR_JWK_INVALID");class IP extends Kn{constructor(){super(...arguments),Be(this,"code","ERR_JWKS_INVALID")}}Be(IP,"code","ERR_JWKS_INVALID");class jP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Be(jP,"code","ERR_JWKS_NO_MATCHING_KEY");class BP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,Symbol.asyncIterator,void 0),Be(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Be(BP,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class UP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWKS_TIMEOUT")}}Be(UP,"code","ERR_JWKS_TIMEOUT");class zP extends Kn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),Be(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Be(zP,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const FP=/\{[^{}]+\}/g;function qP(){return Math.random().toString(36).slice(2,11)}function HP(t){let{baseUrl:e="",Request:n=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:a,headers:o,...s}={...t};e=fk(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:p=i,Request:b=n,headers:m,params:S={},parseAs:g="json",querySerializer:y,bodySerializer:x=a??GP,body:v,...k}=d||{};h&&(e=fk(h));let T=typeof r=="function"?r:hk(r);y&&(T=typeof y=="function"?y:hk({...typeof r=="object"?r:{},...y}));const C=v===void 0?void 0:x(v),R=C===void 0||C instanceof FormData?{}:{"Content-Type":"application/json"},A={redirect:"follow",...s,...k,body:C,headers:YP(R,o,m,S.header)};let N,O,B=new n(WP(u,{baseUrl:e,params:S,querySerializer:T}),A);for(const K in k)K in B||(B[K]=k[K]);if(l.length){N=qP(),O=Object.freeze({baseUrl:e,fetch:p,parseAs:g,querySerializer:T,bodySerializer:x});for(const K of l)if(K&&typeof K=="object"&&typeof K.onRequest=="function"){const P=await K.onRequest({request:B,schemaPath:u,params:S,options:O,id:N});if(P){if(!(P instanceof n))throw new Error("onRequest: must return new Request() when modifying the request");B=P}}}let W=await p(B);if(l.length)for(let K=l.length-1;K>=0;K--){const P=l[K];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const V=await P.onResponse({request:B,response:W,schemaPath:u,params:S,options:O,id:N});if(V){if(!(V instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");W=V}}}if(W.status===204||W.headers.get("Content-Length")==="0")return W.ok?{data:{},response:W}:{error:{},response:W};if(W.ok)return g==="stream"?{data:W.body,response:W}:{data:await W[g](),response:W};let L=await W.text();try{L=JSON.parse(L)}catch{}return{error:L,response:W}}return{GET(u,d){return c(u,{...d,method:"GET"})},PUT(u,d){return c(u,{...d,method:"PUT"})},POST(u,d){return c(u,{...d,method:"POST"})},DELETE(u,d){return c(u,{...d,method:"DELETE"})},OPTIONS(u,d){return c(u,{...d,method:"OPTIONS"})},HEAD(u,d){return c(u,{...d,method:"HEAD"})},PATCH(u,d){return c(u,{...d,method:"PATCH"})},TRACE(u,d){return c(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");l.push(d)}},eject(...u){for(const d of u){const h=l.indexOf(d);h!==-1&&l.splice(h,1)}}}}function kh(t,e,n){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`${t}=${(n==null?void 0:n.allowReserved)===!0?e:encodeURIComponent(e)}`}function uk(t,e,n){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[n.style]||"&";if(n.style!=="deepObject"&&n.explode===!1){for(const s in e)i.push(s,n.allowReserved===!0?e[s]:encodeURIComponent(e[s]));const o=i.join(",");switch(n.style){case"form":return`${t}=${o}`;case"label":return`.${o}`;case"matrix":return`;${t}=${o}`;default:return o}}for(const o in e){const s=n.style==="deepObject"?`${t}[${o}]`:o;i.push(kh(s,e[o],n))}const a=i.join(r);return n.style==="label"||n.style==="matrix"?`${r}${a}`:a}function dk(t,e,n){if(!Array.isArray(e))return"";if(n.explode===!1){const a={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[n.style]||",",o=(n.allowReserved===!0?e:e.map(s=>encodeURIComponent(s))).join(a);switch(n.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${t}=${o}`;default:return`${t}=${o}`}}const i={simple:",",label:".",matrix:";"}[n.style]||"&",r=[];for(const a of e)n.style==="simple"||n.style==="label"?r.push(n.allowReserved===!0?a:encodeURIComponent(a)):r.push(kh(t,a,n));return n.style==="label"||n.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function hk(t){return function(n){const i=[];if(n&&typeof n=="object")for(const r in n){const a=n[r];if(a!=null){if(Array.isArray(a)){if(a.length===0)continue;i.push(dk(r,a,{style:"form",explode:!0,...t==null?void 0:t.array,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}if(typeof a=="object"){i.push(uk(r,a,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}i.push(kh(r,a,t))}}return i.join("&")}}function VP(t,e){let n=t;for(const i of t.match(FP)??[]){let r=i.substring(1,i.length-1),a=!1,o="simple";if(r.endsWith("*")&&(a=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(o="label",r=r.substring(1)):r.startsWith(";")&&(o="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const s=e[r];if(Array.isArray(s)){n=n.replace(i,dk(r,s,{style:o,explode:a}));continue}if(typeof s=="object"){n=n.replace(i,uk(r,s,{style:o,explode:a}));continue}if(o==="matrix"){n=n.replace(i,`;${kh(r,s)}`);continue}n=n.replace(i,o==="label"?`.${encodeURIComponent(s)}`:encodeURIComponent(s))}return n}function GP(t){return t instanceof FormData?t:JSON.stringify(t)}function WP(t,e){var r;let n=`${e.baseUrl}${t}`;(r=e.params)!=null&&r.path&&(n=VP(n,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(n+=`?${i}`),n}function YP(...t){const e=new Headers;for(const n of t){if(!n||typeof n!="object")continue;const i=n instanceof Headers?n.entries():Object.entries(n);for(const[r,a]of i)if(a===null)e.delete(r);else if(Array.isArray(a))for(const o of a)e.append(r,o);else a!==void 0&&e.set(r,a)}return e}function fk(t){return t.endsWith("/")?t.substring(0,t.length-1):t}const pk="Onboardee-Session-Token",mk="OnboardeeSessionToken";class gk{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=HP({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest:({request:n})=>{if(this.trackOnboardeeToken&&window.localStorage){const i=window.localStorage.getItem(mk);i&&n.headers.set(pk,i)}return n},onResponse:({response:n})=>{if(this.trackOnboardeeToken){const i=n.headers.get(pk);i&&window.localStorage&&window.localStorage.setItem(mk,i)}return n}})}setTrackOnboardeeToken(e){this.trackOnboardeeToken=e}setAuthToken(e){this.client.use({onRequest({request:n}){return n.headers.set("Authorization",`Bearer ${e}`),n}})}setApiToken(e){this.client.use({onRequest({request:n}){return n.headers.set("Authorization",`Token ${e}`),n}})}async getAuthUrl(e,n){const i={path:{type:e},...n!=null&&n.returnUrl?{query:{return_url:n.returnUrl}}:{}};return await this.client.GET("/api/auth/{type}",{params:i})}async adminLoginAs(e){return await this.client.POST("/api/admin/login-as",{body: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 switchAccount(e){return await this.client.POST("/api/me/account",{body:e})}async listUsers(){return await this.client.GET("/api/users")}async createUser(e){return await this.client.POST("/api/users",{body:e})}async updateUser(e,n){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:n})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}async clientInitialise(e,n={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:n})}async clientAuthConfig(e,n){return await this.client.GET("/api/client/{appToken}/auth-config",{params:{path:{appToken:e}},signal:n})}async clientStartSession(e,n){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:n})}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,n){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:n})}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 listPublishedPlansForProduct(e){return await this.client.GET("/api/products/{id}/published-plans",{params:{path:{id:String(e)}}})}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,n,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...n&&{start_date:n},...i&&{end_date:i},...r&&{course_id:r}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,n){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:n})}async getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}async getProductMeetAppToken(e){return await this.client.GET("/api/products/{id}/meet-app-token",{params:{path:{id:e}}})}async setProductMeetAppToken(e,n){return await this.client.POST("/api/products/{id}/meet-app-token",{params:{path:{id:e}},body:n})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,n){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:{content:n.content||""}})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,n){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async searchProductKnowledgeBlocks(e,n,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:n,...i&&{limit:i.toString()}}}})}async listAudiences(e,n){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)},...n?{query:n}:{}}})}async createAudience(e,n){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:n})}async getAudience(e,n){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}}})}async updateAudience(e,n,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}},body:i})}async deleteAudience(e,n){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}}})}async replaceAudiencePlans(e,n,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:n}},body:{plans:i}})}async updateProductKnowledgeBlock(e,n,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deleteProductKnowledgeBlock(e,n){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,n){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:n})}async bulkUpdateProductPronunciationRules(e,n){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:n})}async deleteProductPronunciationRule(e,n){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:n}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,n){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:n})}async updateProductExternalKnowledge(e,n,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:n}},body:i})}async deleteProductExternalKnowledge(e,n){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:n}}})}async refreshProductExternalKnowledge(e,n){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:n}}})}async listExternalKnowledgePages(e,n){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId:n}}})}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 getAdminPlanMeetAppToken(e){return await this.client.GET("/api/admin/plans/{id}/meet-app-token",{params:{path:{id:e}}})}async setAdminPlanMeetAppToken(e,n){return await this.client.POST("/api/admin/plans/{id}/meet-app-token",{params:{path:{id:e}},body:n})}async getPlanAnalytics(e,n,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...n&&{start_date:n},...i&&{end_date:i}}}})}async replacePlan(e,n){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:n})}async updatePlan(e,n){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:n})}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 n={};return e!=null&&e.search&&(n.search=e.search),e!=null&&e.page&&(n.page=e.page),e!=null&&e.limit&&(n.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(n).length>0?{query:n}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,n){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:n})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,n,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:n,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,n){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async updatePlanKnowledgeBlock(e,n,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deletePlanKnowledgeBlock(e,n){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,n){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:{content:n.content||""}})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,n){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:n})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async listPlanFAQs(e,n=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(n)}}})}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,n){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:n})}async listRevisionFAQs(e,n){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...n!==void 0&&{include_drafts:n.toString()}}}})}async createRevisionFAQ(e,n){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:n})}async updateFAQ(e,n){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:n})}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,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async createRevisionKnowledgeBlock(e,n){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async updateRevisionKnowledgeBlock(e,n,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deleteRevisionKnowledgeBlock(e,n){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async listSessions(e,n){const i={token:e};return n!=null&&n.productId&&(i.product_id=n.productId),n!=null&&n.startDate&&(i.start_date=n.startDate),n!=null&&n.endDate&&(i.end_date=n.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,n){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:n}}})}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 listUserSessions(e){const n={};return e!=null&&e.productId&&(n.product_id=e.productId),e!=null&&e.courseId&&(n.course_id=e.courseId),e!=null&&e.startDate&&(n.start_date=e.startDate),e!=null&&e.endDate&&(n.end_date=e.endDate),e!=null&&e.page&&(n.page=e.page),e!=null&&e.limit&&(n.limit=e.limit),e!=null&&e.courseName&&(n.course_name=e.courseName),e!=null&&e.userName&&(n.user_name=e.userName),e!=null&&e.company&&(n.company=e.company),e!=null&&e.email&&(n.email=e.email),e!=null&&e.sortBy&&(n.sort_by=e.sortBy),e!=null&&e.sortOrder&&(n.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(n).length>0?{query:n}:void 0})}async listUserSessionsAggregate(e){const n={};return e!=null&&e.productId&&(n.product_id=e.productId),e!=null&&e.courseId&&(n.course_id=e.courseId),e!=null&&e.startDate&&(n.start_date=e.startDate),e!=null&&e.endDate&&(n.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(n).length>0?{query:n}:void 0})}async queryTranscriptChat(e){return await this.client.POST("/api/performance/transcript-chat",{body:e})}streamTranscriptChat(e,n={},i={}){var s;const r=new AbortController,a=()=>{var l;return r.abort((l=i.signal)==null?void 0:l.reason)};(s=i.signal)!=null&&s.aborted?r.abort(i.signal.reason):i.signal&&i.signal.addEventListener("abort",a);const o=this.runTranscriptChatStream(e,n,r);return i.signal&&o.finally(()=>{var l;return(l=i.signal)==null?void 0:l.removeEventListener("abort",a)}),{cancel:()=>r.abort(),close:()=>r.abort(),signal:r.signal,closed:o}}async runTranscriptChatStream(e,n,i){const r=h=>{var p,b,m,S,g,y;switch((p=n.onEvent)==null||p.call(n,h),h.type){case"started":(b=n.onStarted)==null||b.call(n,h.data);break;case"batch_complete":(m=n.onBatchComplete)==null||m.call(n,h.data);break;case"answer_chunk":(S=n.onAnswerChunk)==null||S.call(n,h.data);break;case"completed":(g=n.onCompleted)==null||g.call(n,h.data);break;case"error":(y=n.onError)==null||y.call(n,h.data);break}},a=h=>{r({type:"error",data:h})};let o;try{o=await this.client.POST("/api/performance/transcript-chat/stream",{body:e,parseAs:"stream",signal:i.signal})}catch(h){throw console.error("[TranscriptChat] Network error:",h),a(aa(h,0,"network_error",`Failed to start transcript chat stream: ${h instanceof Error?h.message:String(h)}`)),h}const s=o.response;if(!s){console.error("[TranscriptChat] No response object"),a(aa(null,0,"no_response","No response returned from transcript chat"));return}if(s.status,s.statusText,s.headers.get("Content-Type"),!s.ok){const h=await vk(s);console.error("[TranscriptChat] HTTP error:",{status:s.status,payload:h}),a(aa(h??o.error,s.status,"http_error",`Transcript chat stream failed with status ${s.status}`));return}const l=s.headers.get("Content-Type")||"";if(!l.toLowerCase().includes("text/event-stream")){const h=await vk(s);console.error("[TranscriptChat] Invalid content type:",l),a(aa(h??o.error,s.status,"invalid_content_type","Transcript chat stream did not return an event stream"));return}if(!s.body){console.error("[TranscriptChat] Response body is null"),a(aa(null,s.status,"stream_unavailable","Streaming is not supported by this environment"));return}const c=s.body.getReader(),u=new TextDecoder;let d="";try{for(;;){const{value:h,done:p}=await c.read();d+=u.decode(h||new Uint8Array,{stream:!p});const b=d.split(`
43
43
 
44
44
  `);d=b.pop()??"";for(const m of b){const S=bk(m);if(!S)continue;let g;try{g=S.data?JSON.parse(S.data):void 0}catch(x){throw console.error("[TranscriptChat] Failed to parse SSE event:",{event:S.event,data:S.data,error:x}),a(aa(x,s.status,"stream_parse_error",`Failed to parse transcript chat stream event: ${S.event}`)),x}const y=yk(S.event,g);if(!y){console.warn("[TranscriptChat] Unknown event type received:",S.event,g);continue}if(y.type,y.data,r(y),y.type==="error")return}if(p){if(d.trim()){const m=bk(d);if(m){let S;try{S=m.data?JSON.parse(m.data):void 0}catch(y){throw console.error("[TranscriptChat] Failed to parse final SSE event:",{event:m.event,data:m.data,error:y}),a(aa(y,s.status,"stream_parse_error",`Failed to parse final transcript chat stream event: ${m.event}`)),y}const g=yk(m.event,S);g&&(g.type,g.data,r(g))}}return}}}catch(h){if(!i.signal.aborted)throw console.error("[TranscriptChat] Stream error:",h),a(aa(h,s.status,"stream_error",`Transcript chat stream failed: ${h instanceof Error?h.message:String(h)}`)),h}finally{c.releaseLock()}}async getJoinToken(e,{clientType:n,user:i}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...n&&{client_type:n},...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,n){return await this.client.POST("/api/voices/generate-sample",{body:{product_id:n,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}}async function vk(t){try{return await t.clone().json()}catch{return null}}function aa(t,e,n,i){const r=typeof t=="object"&&t!==null?t:{},a=Ja(r.status_code??r.statusCode??r.status)??(typeof e=="number"?e:0),o=typeof r.code=="string"?r.code:typeof r.error=="string"?r.error:n,s=typeof r.message=="string"?r.message:i,l=r.details;return{statusCode:a,code:o,message:s,details:l,raw:t??void 0}}function bk(t){const e=t.split(/\r?\n/);let n="";const i=[];for(const r of e){const a=r.trimEnd();!a||a.startsWith(":")||(a.startsWith("event:")?n=a.slice(6).trim():a.startsWith("data:")&&i.push(a.slice(5).trim()))}return!n||i.length===0?null:{event:n,data:i.join(`
45
45
  `)}}function yk(t,e){switch(t){case"started":return{type:"started",data:KP(e)};case"batch_complete":return{type:"batch_complete",data:XP(e)};case"answer_chunk":return{type:"answer_chunk",data:$P(e)};case"completed":return{type:"completed",data:JP(e)};case"error":return{type:"error",data:aa(e,0,"stream_error","Transcript chat stream error")};default:return null}}function KP(t){return{sessionCount:Ja((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,batchCount:Ja((t==null?void 0:t.batchCount)??(t==null?void 0:t.BatchCount))??0,timeframe:typeof((t==null?void 0:t.timeframe)??(t==null?void 0:t.Timeframe))=="string"?t.timeframe??t.Timeframe:void 0}}function XP(t){return{batchNumber:Ja((t==null?void 0:t.batchNumber)??(t==null?void 0:t.BatchNumber))??0,totalBatches:Ja((t==null?void 0:t.totalBatches)??(t==null?void 0:t.TotalBatches))??0,sessionsInBatch:Ja((t==null?void 0:t.sessionsInBatch)??(t==null?void 0:t.SessionsInBatch))??0}}function $P(t){return{content:typeof(t==null?void 0:t.content)=="string"?t.content:typeof(t==null?void 0:t.Content)=="string"?t.Content:""}}function JP(t){const e=_k((t==null?void 0:t.sessionUuids)??(t==null?void 0:t.SessionUUIDs)),n=_k((t==null?void 0:t.mapSummaries)??(t==null?void 0:t.MapSummaries));return{answer:typeof(t==null?void 0:t.answer)=="string"?t.answer:typeof(t==null?void 0:t.Answer)=="string"?t.Answer:"",sessionCount:Ja((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,sessionUuids:e,batchCount:Ja((t==null?void 0:t.batchCount)??(t==null?void 0:t.BatchCount))??void 0,model:typeof(t==null?void 0:t.model)=="string"?t.model:typeof(t==null?void 0:t.Model)=="string"?t.Model:void 0,mapSummaries:n}}function Ja(t){if(typeof t=="number"&&!Number.isNaN(t))return t;if(typeof t=="string"&&t.trim()!==""){const e=Number(t);if(!Number.isNaN(e))return e}}function _k(t){if(Array.isArray(t))return t.map(e=>String(e))}const xk="https://app.coragents.ai";class Th extends Ep{constructor(e,n,i,r){super(),this.state=null,this.isPaused=!1,this.preferredMicrophoneDeviceId=null,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.productName=null,this.assistantSubtitle=null,this.isMarketing=null,this.isMultilingual=!1,this.languageCodes=null,this.defaultLanguageCode=null,this.voiceId=null,this.selectedLanguage=null,this.agentAnalyser=null,this.userAnalyser=null,this.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.humanJoinAcked=!1,this.humanJoinRetryTimeout=null,this.humanJoinRetryCount=0,this.humanJoinInFlight=!1,this.humanJoinPayload=null,this.chatMessages=[],this.publishedAudioStream=null,this.publishedAudioTrack=null,this.transcriptionStreams=[],this.appToken=e,this.planId=n,this.clientType=i,this.api=r.api||new gk({baseUrl:xk}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(a=>new Ys(a)),this.captureScreen=r.captureScreen||null,this.preferredMicrophoneDeviceId=r.preferredMicrophoneDeviceId||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,...this.planId&&{onboarding_plan:this.planId},...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(),this.productName=i&&"product_name"in i?i.product_name??null:null,this.assistantSubtitle=i&&"assistant_subtitle"in i?i.assistant_subtitle??null:null,this.isMarketing=i&&"is_marketing"in i?i.is_marketing??null:null,this.isMultilingual=(i==null?void 0:i.is_multilingual)||!1,this.languageCodes=(i==null?void 0:i.language_codes)||null,this.defaultLanguageCode=(i==null?void 0:i.default_language_code)||null,this.voiceId=(i==null?void 0:i.voice_id)||null,await this.joinRoom({withMicrophone:e==null?void 0:e.withMicrophone}),this.setState("volume-check"),this.planId,this.sessionUuid}catch(n){console.error("[obi] error starting session",{error:n}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:n=!1}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.resetHumanJoinHandshake(),this.room.on(J.Disconnected,i=>{if(!this.room)return;this.transcriptionStreams=[],this.emit("captions",[]);let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(J.TrackSubscribed,i=>{if(console.info("[obi] track subscribed kind=",i.kind,"source=",i.source),i.kind==="audio"&&(i.attach(),i.source===H.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:a}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=a}}),this.room.on(J.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:a}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=a}}),this.room.on(J.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(J.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),a=JSON.parse(r);switch(a.status||a.request||a.type){case"course_progress":typeof a.current_step=="number"&&typeof a.total_steps=="number"&&Array.isArray(a.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,a.current_step),totalSteps:Math.max(1,a.total_steps),stepNames:a.step_names});break;case"introduction_complete":this.emit("introductionComplete");break;case"course_selection":if(Array.isArray(a.courses)){const s=a.courses.map(l=>{if(typeof(l==null?void 0:l.uuid)!="string"||typeof(l==null?void 0:l.name)!="string")return console.warn("[obi] skipping invalid course in course_selection",l),null;const c={uuid:l.uuid,name:l.name};return typeof l.description=="string"&&(c.description=l.description),typeof l.overview=="string"&&(c.overview=l.overview),typeof l.goal=="string"&&(c.goal=l.goal),typeof l.agent_type=="string"&&(c.agent_type=l.agent_type),typeof l.duration=="number"&&(c.duration=l.duration),typeof l.order=="number"&&(c.order=l.order),typeof l.completed=="boolean"&&(c.completed=l.completed),c}).filter(l=>l!==null);this.emit("courseSelection",{courses:s})}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().catch(s=>console.warn("[obi] failed to mute microphone from server request",s));break;case"unmute_microphone":this.unmuteMicrophone().catch(s=>console.warn("[obi] failed to unmute microphone from server request",s));break;case"transcript":this.emit("transcript",a.transcript,a.role);break;case"screen_capture":this.captureScreenshareFrame().then(s=>{this.emit("screenCaptureNotification",s)}).catch(s=>{console.error("[obi] failed to capture screenshare frame on notification",s),this.emit("screenCaptureNotification",null)});break;case"human_joined_ack":this.handleHumanJoinedAck();break;default:console.warn("[obi] unknown data received",a)}}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,a=null;try{r=await this.captureScreen()}catch(o){r=null,a=o}if(!r||a)return console.error("[obi] error capturing screen",{error:a}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),this.emit("screenCaptured",r),"ok"}catch(o){return console.error("[obi] error sending screen capture",{error:o}),"error"}}),this.room.localParticipant.registerRpcMethod("send_chat_message",async i=>{var r,a;try{const o=i!=null&&i.payload?JSON.parse(i.payload):{},s=typeof(o==null?void 0:o.message)=="string"&&o.message.trim().length>0?o.message.trim():null;if(!s)return console.warn("[obi] received send_chat_message with empty payload"),"error";const l=typeof o.timestamp=="number"&&!Number.isNaN(o.timestamp)?o.timestamp:Date.now();let c=null,u=null;const d=(r=this.room)==null?void 0:r.remoteParticipants.get("agent-avatar");if(d)c=d.identity,u=d.name??null;else if(this.room){for(const p of this.room.remoteParticipants.values())if((a=p.identity)!=null&&a.startsWith("agent-")){c=p.identity,u=p.name??null;break}}const h=typeof o.sender_name=="string"&&o.sender_name.trim().length>0?o.sender_name.trim():u||"Agent";return this.appendChatMessage({id:typeof o.id=="string"&&o.id.length>0?o.id:`agent-${i.requestId||Date.now()}`,timestamp:l,message:s,from:{identity:c||"agent-avatar",name:h},attributes:{senderName:h,source:"agent-rpc"},isAgent:!0}),"ok"}catch(o){return console.error("[obi] failed to handle send_chat_message RPC",o),"error"}}),this.room.registerTextStreamHandler("lk.transcription",async(i,r)=>{var l;const o=((l=i.info.attributes)==null?void 0:l["lk.segment_id"])||i.info.id;let s="";for await(const c of i){s+=c;const u=this.transcriptionStreams.findIndex(h=>{var m;return(((m=h.streamInfo.attributes)==null?void 0:m["lk.segment_id"])||h.streamInfo.id)===o}),d={text:s,participantInfo:{identity:r.identity},streamInfo:i.info};u>=0?this.transcriptionStreams[u]=d:this.transcriptionStreams.push(d),this.emit("captions",[...this.transcriptionStreams])}}),await this.room.connect(this.roomUrl,this.joinToken),e){this.isPaused;try{await this.room.localParticipant.setMicrophoneEnabled(!0,{deviceId:this.preferredMicrophoneDeviceId||void 0}),this.isMicShared=!0}catch(i){if(this.preferredMicrophoneDeviceId)console.warn("[obi] joinRoom: failed to set microphone with preferred device, retrying with default",i),await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0;else throw i}this.isPaused,this.isPaused&&await this.muteMicrophone()}if(n){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?this.speakingStateChanged("speaking"):this.speakingStateChanged("listening"),this.selectedLanguage&&this.setLanguage(this.selectedLanguage).catch(r=>{console.error("[obi] failed to restore language selection",r)})}}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(n){console.error("[obi] error checking microphone permission:",n)}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;let e=null,n=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0,{deviceId:this.preferredMicrophoneDeviceId||void 0}),this.isMicShared=!0}catch(i){if(this.preferredMicrophoneDeviceId){console.warn("[obi] failed to share microphone with preferred device, retrying with default",i);try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){n=r,this.isMicShared=!1}}else n=i,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:n}),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 sendHumanJoined(e){if(this.clientType!=="meet")return;const n=this.buildHumanJoinedPayload(e);if(!this.isSameHumanJoinPayload(n,this.humanJoinPayload)){if(this.humanJoinPayload=n,this.humanJoinAcked){if(this.humanJoinInFlight)return;await this.publishHumanJoinedUpdate(n);return}this.humanJoinRetryTimeout||this.humanJoinInFlight||(this.humanJoinRetryCount=0,await this.trySendHumanJoined())}}async publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const c=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",c),!1}console.log("[obi] requesting audio track via getUserMedia");try{const c=this.preferredMicrophoneDeviceId?{deviceId:{exact:this.preferredMicrophoneDeviceId}}:!0;this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:c})}catch(c){if(this.preferredMicrophoneDeviceId)console.warn("[obi] failed to get user media with preferred device, retrying with default",c),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});else throw c}const n=this.publishedAudioStream.getAudioTracks().map(c=>{var u,d;return{id:c.id,label:c.label,enabled:c.enabled,muted:c.muted,readyState:c.readyState,constraints:(u=c.getConstraints)==null?void 0:u.call(c),settings:(d=c.getSettings)==null?void 0:d.call(c)}});console.log("[obi] getUserMedia resolved",n);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const c=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",c),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},a=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,a);const o=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:H.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,a,o.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:s,context:l}=this.createFFT(this.publishedAudioStream);this.userAnalyser=s,this.userAudioContext=l,this.isAudioTrackPublished=!0,e=!0}catch(n){if(console.error("[obi] failed to publish audio track",n),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 setScreenShareEnabled(e){var i,r;if(this.sessionUuid,this.room,(i=this.room)==null||i.state,!this.room){console.warn("[obi] cannot set screen share: room not connected");return}const n=await this.room.localParticipant.setScreenShareEnabled(e,e?{video:{displaySurface:"window"}}:void 0);if(e&&n){const a=n.track,o=a==null?void 0:a.mediaStreamTrack;console.info("[obi] screen share track published",{trackSid:n.trackSid,trackName:n.trackName,source:n.source,isEnabled:n.isEnabled,isMuted:n.isMuted,isSubscribed:n.isSubscribed,mediaTrackEnabled:o==null?void 0:o.enabled,mediaTrackMuted:o==null?void 0:o.muted,mediaTrackReadyState:o==null?void 0:o.readyState,mediaTrackLabel:o==null?void 0:o.label,mediaTrackContentHint:o==null?void 0:o.contentHint,videoSettings:(r=o==null?void 0:o.getSettings)==null?void 0:r.call(o)})}await this.sendData({request:"share_screen",success:e}),e&&this.setState("navigate")}async shareScreen(){this.sessionUuid,await this.setScreenShareEnabled(!0)}async captureScreenshareFrame(){if(!this.room)return console.warn("[obi] cannot capture screenshare frame: no room"),null;const e=this.room.localParticipant.getTrackPublications();let n=null;for(const i of e)if(i.kind==="video"&&i.source===H.Source.ScreenShare&&i.track){n=i.track.mediaStreamTrack;break}if(!n)return console.warn("[obi] no screenshare track found to capture frame from"),null;try{const i=document.createElement("video");i.srcObject=new MediaStream([n]),i.muted=!0,await new Promise((s,l)=>{i.onloadedmetadata=()=>s(),i.onerror=()=>l(new Error("Failed to load video metadata")),setTimeout(()=>l(new Error("Video metadata load timeout")),5e3)}),await i.play();const r=document.createElement("canvas");r.width=i.videoWidth,r.height=i.videoHeight;const a=r.getContext("2d");if(!a)return console.error("[obi] failed to get canvas context"),null;a.drawImage(i,0,0,r.width,r.height);const o=r.toDataURL("image/png");return i.pause(),i.srcObject=null,r.width,r.height,o.length,o}catch(i){return console.error("[obi] failed to capture screenshare frame",i),null}}async pause(){await this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){await this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}async endCourse(e){await this.sendData({request:"end_course",...e?{reason:e}:{}})}async switchMicrophoneDevice(e){var n;if(this.sessionUuid,this.room,(n=this.room)==null||n.state,this.isMicShared,!this.room)return console.warn("[obi] cannot switch microphone device: room not connected"),!1;try{const i=await this.room.switchActiveDevice("audioinput",e);return i?(this.preferredMicrophoneDeviceId=e,this.sessionUuid):console.warn("[obi] failed to switch microphone device",{deviceId:e}),i}catch(i){return console.error("[obi] error switching microphone device",{err:i,deviceId:e}),!1}}async muteMicrophone(){var n;this.sessionUuid;const e=this.room.localParticipant.getTrackPublications();for(const i of e)i.kind==="audio"&&i.source===H.Source.Microphone&&await((n=i.mute)==null?void 0:n.call(i))}async unmuteMicrophone(){var n;this.sessionUuid;const e=this.room.localParticipant.getTrackPublications();for(const i of e)i.kind==="audio"&&i.source===H.Source.Microphone&&await((n=i.unmute)==null?void 0:n.call(i))}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.resetHumanJoinHandshake({clearPayload:!0}),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)}try{this.room.unregisterTextStreamHandler("lk.transcription")}catch(i){console.warn("[obi] failed to unregister text stream handler",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const n=this.room;this.room=null,await n.disconnect(),this.sessionUuid}this.transcriptionStreams=[],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.clearChatMessages(),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})}appendChatMessage(e){const n={...e,from:e.from?{...e.from}:e.from,attributes:e.attributes?{...e.attributes}:e.attributes};this.chatMessages=[...this.chatMessages,n],this.emit("chatMessagesChanged",[...this.chatMessages]),this.emit("chatMessageReceived",n)}clearChatMessages(){this.chatMessages.length&&(this.chatMessages=[],this.emit("chatMessagesChanged",[]))}async setLanguage(e){var n;this.selectedLanguage=e,(n=this.room)!=null&&n.localParticipant&&await this.sendData({request:"set_language",language_code: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,productName:this.productName,assistantSubtitle:this.assistantSubtitle,isMarketing:this.isMarketing,isMultilingual:this.isMultilingual,languageCodes:this.languageCodes,defaultLanguageCode:this.defaultLanguageCode,voiceId:this.voiceId,selectedLanguage:this.selectedLanguage,preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId,chatMessages:this.chatMessages.map(e=>({...e,from:e.from?{...e.from}:e.from,attributes:e.attributes?{...e.attributes}:e.attributes}))})}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=[],a=50,o=5e3,s=8,l=Math.pow(o/a,1/s);for(let c=0;c<s;c++){const u=a*Math.pow(l,c),d=a*Math.pow(l,c+1),h=Math.floor(u/i),p=Math.floor(d/i),b=Math.min(p,this.frequencyDataBuffer.length),m=Math.min(h,b);if(m<b){let S=0;for(let y=m;y<b;y++)S+=this.frequencyDataBuffer[y];const g=S/(b-m)/255;r.push(g)}else r.push(0)}return r}setState(e){this.state;const n=this.state;this.state=e,this.emit("stateChanged",e,n)}static deserialise(e,n,i,r={}){const a=JSON.parse(e),o=new Th(n,a.planId,i,r);return o.state=a.state,o.speakingState=a.speakingState,o.identity=a.identity||null,o.isPaused=a.isPaused||!1,o.sessionUuid=a.sessionUuid||null,o.roomId=a.roomId||null,o.joinToken=a.joinToken||null,o.roomUrl=a.roomUrl||null,o.startedAt=a.startedAt||null,o.productName=a.productName??null,o.assistantSubtitle=a.assistantSubtitle??null,o.isMarketing=a.isMarketing??null,o.isMultilingual=a.isMultilingual||!1,o.languageCodes=a.languageCodes||null,o.defaultLanguageCode=a.defaultLanguageCode||null,o.voiceId=a.voiceId||null,o.selectedLanguage=a.selectedLanguage||null,o.preferredMicrophoneDeviceId=a.preferredMicrophoneDeviceId||r.preferredMicrophoneDeviceId||null,o.chatMessages=(a.chatMessages||[]).map(s=>({...s,from:s.from?{...s.from}:s.from,attributes:s.attributes?{...s.attributes}:s.attributes})),o}buildHumanJoinedPayload(e){const n={request:"human_joined"};return e!=null&&e.name&&e.name.trim().length>0&&(n.name=e.name.trim()),e!=null&&e.email&&e.email.trim().length>0&&(n.email=e.email.trim()),typeof(e==null?void 0:e.screenShareSupported)=="boolean"&&(n.screen_share_supported=e.screenShareSupported),n}isSameHumanJoinPayload(e,n){return!e||!n?!1:(e.name??void 0)===(n.name??void 0)&&(e.email??void 0)===(n.email??void 0)&&e.screen_share_supported===n.screen_share_supported}async trySendHumanJoined(){if(this.clientType!=="meet"||this.humanJoinAcked||this.humanJoinInFlight)return;if(this.humanJoinInFlight=!0,!this.room||this.room.state!==Xe.Connected||!this.room.localParticipant){this.humanJoinInFlight=!1,this.scheduleHumanJoinRetry();return}const e=this.humanJoinPayload||{request:"human_joined"};try{await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}catch(n){console.warn("[obi] failed to publish human_joined message",n)}finally{this.humanJoinInFlight=!1}this.humanJoinAcked||this.scheduleHumanJoinRetry()}async publishHumanJoinedUpdate(e){if(!(!this.room||this.room.state!==Xe.Connected||!this.room.localParticipant)){this.humanJoinInFlight=!0;try{await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}catch(n){console.warn("[obi] failed to publish human_joined message",n)}finally{this.humanJoinInFlight=!1}}}scheduleHumanJoinRetry(){if(this.humanJoinAcked||this.humanJoinRetryTimeout)return;const e=Math.min(500*Math.pow(2,this.humanJoinRetryCount),5e3);this.humanJoinRetryCount+=1,this.humanJoinRetryTimeout=setTimeout(()=>{this.humanJoinRetryTimeout=null,this.trySendHumanJoined()},e)}clearHumanJoinRetryTimer(){this.humanJoinRetryTimeout&&(clearTimeout(this.humanJoinRetryTimeout),this.humanJoinRetryTimeout=null)}resetHumanJoinHandshake(e={}){this.clearHumanJoinRetryTimer(),this.humanJoinAcked=!1,this.humanJoinInFlight=!1,this.humanJoinRetryCount=0,e.clearPayload&&(this.humanJoinPayload=null)}handleHumanJoinedAck(){this.humanJoinAcked||(this.humanJoinAcked=!0,this.humanJoinInFlight=!1,this.humanJoinRetryCount=0,this.clearHumanJoinRetryTimer())}speakingStateChanged(e){this.speakingState;const n=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,n)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const n=new AudioContext,i=n.createAnalyser();return n.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,{analyser:i,context:n}}}class wh extends Ep{constructor(e,n,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.preferredMicrophoneDeviceId=null,this.appToken=e,this.clientType=n,this.api=i.api||new gk({baseUrl:i.apiBaseUrl||xk}),this.sessionFactory=i.sessionFactory||((r,a,o,s)=>new Th(r,a,o,s)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var n,i,r,a,o,s,l;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const c=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});this.identity=e.identity||null,this.product=((n=c.data)==null?void 0:n.product)||null,this.plans=((i=c.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=c.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((a=c.data)==null?void 0:a.plan_is_completed)||[],this.showWidget=((o=c.data)==null?void 0:o.show_widget)||!1,this.engagement=((s=c.data)==null?void 0:s.engagement)||null;const u=((l=this.product)==null?void 0:l.track_onboardee_token)??!0;if(this.api.setTrackOnboardeeToken(u),e.planUuid){let d=null,h=!1;try{const p=await this.api.getPlanSDK(e.planUuid);if(p.error)throw new Error(`Plan not found: ${p.error}`);p.data&&(d=p.data)}catch(p){try{const b=await this.api.getSessionPlan(e.planUuid);if(b.error)throw new Error(`Session plan not found: ${b.error}`);b.data&&(d=b.data,h=!0)}catch(b){console.error("[obi] error getting plan via both endpoints",{planErr:p,sessionErr:b})}}d?(this.selectedPlan=d,this.selectedPlanUuid=h?d.uuid:e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(c){throw this.error=c instanceof Error?c:new Error(String(c)),this.setState("error"),c}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}setPreferredMicrophoneDeviceId(e){this.preferredMicrophoneDeviceId=e,this.session&&(this.session.preferredMicrophoneDeviceId=e)}async startSession(e,n,i){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen,preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId}),this.prepareSession(n),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 n,i;return this.state,(n=this.session)==null||n.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",n=>{var i,r,a;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const o=this.plans.findIndex(s=>{var l;return s.uuid===((l=this.selectedPlan)==null?void 0:l.uuid)});o!==-1&&(this.planIsCompleted[o]=!0)}(a=(r=this.session)==null?void 0:r.removeAllListeners)==null||a.call(r),this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",n),this.session=null}),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(),preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId,serialisedAt:new Date().toISOString()})}static deserialise(e,n,i,r={}){const a=JSON.parse(e),o=new wh(n,i,r);return o.state=a.state,o.identity=a.identity||null,o.product=a.product||null,o.engagement=a.engagement||null,o.plans=a.plans||[],o.selectedPlan=a.selectedPlan||null,o.selectedPlanUuid=a.selectedPlanUuid||null,o.showWidget=a.showWidget||!1,o.preferredMicrophoneDeviceId=a.preferredMicrophoneDeviceId||null,a.session&&(o.session=Th.deserialise(a.session,n,i,{api:o.api,preferredMicrophoneDeviceId:o.preferredMicrophoneDeviceId})),o}setState(e){const n=this.state;this.state=e,this.emit("stateChanged",e,n)}trackEvent(e,n={}){var i,r,a;this.emit("trackEvent",e,{...n,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(a=this.session)==null?void 0:a.sessionUuid})}}var Sk={exports:{}},Ch={};var QP=Symbol.for("react.transitional.element"),ZP=Symbol.for("react.fragment");function kk(t,e,n){var i=null;if(n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),"key"in e){n={};for(var r in e)r!=="key"&&(n[r]=e[r])}else n=e;return e=n.ref,{$$typeof:QP,type:t,key:i,ref:e!==void 0?e:null,props:n}}Ch.Fragment=ZP,Ch.jsx=kk,Ch.jsxs=kk,Sk.exports=Ch;var f=Sk.exports,Tk={exports:{}},ke={};var Ng=Symbol.for("react.transitional.element"),eL=Symbol.for("react.portal"),tL=Symbol.for("react.fragment"),nL=Symbol.for("react.strict_mode"),iL=Symbol.for("react.profiler"),rL=Symbol.for("react.consumer"),aL=Symbol.for("react.context"),oL=Symbol.for("react.forward_ref"),sL=Symbol.for("react.suspense"),lL=Symbol.for("react.memo"),wk=Symbol.for("react.lazy"),cL=Symbol.for("react.activity"),Ck=Symbol.iterator;function uL(t){return t===null||typeof t!="object"?null:(t=Ck&&t[Ck]||t["@@iterator"],typeof t=="function"?t:null)}var Ek={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Rk=Object.assign,Ak={};function Ks(t,e,n){this.props=t,this.context=e,this.refs=Ak,this.updater=n||Ek}Ks.prototype.isReactComponent={},Ks.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")},Ks.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Nk(){}Nk.prototype=Ks.prototype;function Og(t,e,n){this.props=t,this.context=e,this.refs=Ak,this.updater=n||Ek}var Mg=Og.prototype=new Nk;Mg.constructor=Og,Rk(Mg,Ks.prototype),Mg.isPureReactComponent=!0;var Ok=Array.isArray;function Dg(){}var Tt={H:null,A:null,T:null,S:null},Mk=Object.prototype.hasOwnProperty;function Pg(t,e,n){var i=n.ref;return{$$typeof:Ng,type:t,key:e,ref:i!==void 0?i:null,props:n}}function dL(t,e){return Pg(t.type,e,t.props)}function Lg(t){return typeof t=="object"&&t!==null&&t.$$typeof===Ng}function hL(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Dk=/\/+/g;function Ig(t,e){return typeof t=="object"&&t!==null&&t.key!=null?hL(""+t.key):e.toString(36)}function fL(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Dg,Dg):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function Xs(t,e,n,i,r){var a=typeof t;(a==="undefined"||a==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(a){case"bigint":case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case Ng:case eL:o=!0;break;case wk:return o=t._init,Xs(o(t._payload),e,n,i,r)}}if(o)return r=r(t),o=i===""?"."+Ig(t,0):i,Ok(r)?(n="",o!=null&&(n=o.replace(Dk,"$&/")+"/"),Xs(r,e,n,"",function(c){return c})):r!=null&&(Lg(r)&&(r=dL(r,n+(r.key==null||t&&t.key===r.key?"":(""+r.key).replace(Dk,"$&/")+"/")+o)),e.push(r)),1;o=0;var s=i===""?".":i+":";if(Ok(t))for(var l=0;l<t.length;l++)i=t[l],a=s+Ig(i,l),o+=Xs(i,e,n,a,r);else if(l=uL(t),typeof l=="function")for(t=l.call(t),l=0;!(i=t.next()).done;)i=i.value,a=s+Ig(i,l++),o+=Xs(i,e,n,a,r);else if(a==="object"){if(typeof t.then=="function")return Xs(fL(t),e,n,i,r);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return o}function Eh(t,e,n){if(t==null)return t;var i=[],r=0;return Xs(t,i,"","",function(a){return e.call(n,a,r++)}),i}function pL(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Pk=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},mL={map:Eh,forEach:function(t,e,n){Eh(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Eh(t,function(){e++}),e},toArray:function(t){return Eh(t,function(e){return e})||[]},only:function(t){if(!Lg(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};ke.Activity=cL,ke.Children=mL,ke.Component=Ks,ke.Fragment=tL,ke.Profiler=iL,ke.PureComponent=Og,ke.StrictMode=nL,ke.Suspense=sL,ke.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Tt,ke.__COMPILER_RUNTIME={__proto__:null,c:function(t){return Tt.H.useMemoCache(t)}},ke.cache=function(t){return function(){return t.apply(null,arguments)}},ke.cacheSignal=function(){return null},ke.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var i=Rk({},t.props),r=t.key;if(e!=null)for(a in e.key!==void 0&&(r=""+e.key),e)!Mk.call(e,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&e.ref===void 0||(i[a]=e[a]);var a=arguments.length-2;if(a===1)i.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];i.children=o}return Pg(t.type,r,i)},ke.createContext=function(t){return t={$$typeof:aL,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:rL,_context:t},t},ke.createElement=function(t,e,n){var i,r={},a=null;if(e!=null)for(i in e.key!==void 0&&(a=""+e.key),e)Mk.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(r[i]=e[i]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),l=0;l<o;l++)s[l]=arguments[l+2];r.children=s}if(t&&t.defaultProps)for(i in o=t.defaultProps,o)r[i]===void 0&&(r[i]=o[i]);return Pg(t,a,r)},ke.createRef=function(){return{current:null}},ke.forwardRef=function(t){return{$$typeof:oL,render:t}},ke.isValidElement=Lg,ke.lazy=function(t){return{$$typeof:wk,_payload:{_status:-1,_result:t},_init:pL}},ke.memo=function(t,e){return{$$typeof:lL,type:t,compare:e===void 0?null:e}},ke.startTransition=function(t){var e=Tt.T,n={};Tt.T=n;try{var i=t(),r=Tt.S;r!==null&&r(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(Dg,Pk)}catch(a){Pk(a)}finally{e!==null&&n.types!==null&&(e.types=n.types),Tt.T=e}},ke.unstable_useCacheRefresh=function(){return Tt.H.useCacheRefresh()},ke.use=function(t){return Tt.H.use(t)},ke.useActionState=function(t,e,n){return Tt.H.useActionState(t,e,n)},ke.useCallback=function(t,e){return Tt.H.useCallback(t,e)},ke.useContext=function(t){return Tt.H.useContext(t)},ke.useDebugValue=function(){},ke.useDeferredValue=function(t,e){return Tt.H.useDeferredValue(t,e)},ke.useEffect=function(t,e){return Tt.H.useEffect(t,e)},ke.useEffectEvent=function(t){return Tt.H.useEffectEvent(t)},ke.useId=function(){return Tt.H.useId()},ke.useImperativeHandle=function(t,e,n){return Tt.H.useImperativeHandle(t,e,n)},ke.useInsertionEffect=function(t,e){return Tt.H.useInsertionEffect(t,e)},ke.useLayoutEffect=function(t,e){return Tt.H.useLayoutEffect(t,e)},ke.useMemo=function(t,e){return Tt.H.useMemo(t,e)},ke.useOptimistic=function(t,e){return Tt.H.useOptimistic(t,e)},ke.useReducer=function(t,e,n){return Tt.H.useReducer(t,e,n)},ke.useRef=function(t){return Tt.H.useRef(t)},ke.useState=function(t){return Tt.H.useState(t)},ke.useSyncExternalStore=function(t,e,n){return Tt.H.useSyncExternalStore(t,e,n)},ke.useTransition=function(){return Tt.H.useTransition()},ke.version="19.2.3",Tk.exports=ke;var w=Tk.exports;const hi=dy(w);function gL(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Lk={exports:{}};(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var a="",o=0;o<arguments.length;o++){var s=arguments[o];s&&(a=r(a,i(s)))}return a}function i(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return n.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var o="";for(var s in a)e.call(a,s)&&a[s]&&(o=r(o,s));return o}function r(a,o){return o?a?a+" "+o:a+o:a}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Lk);var vL=Lk.exports;const Rh=gL(vL),bL="_box_1r6by_1",yL={box:bL},Ik={none:"0px",xxs:"var(--space-xxs)",xs:"var(--space-xs)",sm:"var(--space-sm)",md:"var(--space-md)",lg:"var(--space-lg)",xl:"var(--space-xl)","2xl":"var(--space-2xl)","3xl":"var(--space-3xl)","4xl":"var(--space-4xl)","5xl":"var(--space-5xl)"};function fr(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in Ik)return Ik[t];if(typeof t=="string"&&t.trim().length>0)return t}}const jk={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},Bk={surface:"var(--color-surface)",surfaceMuted:"var(--color-surface-muted)",surfaceAlt:"var(--color-surface-alt)",primarySoft:"var(--color-primary-soft)",primarySofter:"var(--color-primary-softer)",dangerSurface:"var(--color-danger-surface)"};function _L(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in jk)return jk[t];if(typeof t=="string"&&t.trim().length>0)return t}}function xL(t){if(t!==void 0){if(t in Bk)return Bk[t];if(typeof t=="string"&&t.trim().length>0)return t}}function SL(t,e){const{as:n,className:i,padding:r,paddingX:a,paddingY:o,paddingTop:s,paddingBottom:l,paddingLeft:c,paddingRight:u,paddingSm:d,paddingMd:h,paddingLg:p,paddingXl:b,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:v,marginRight:k,radius:T,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:B,radiusBottomLeft:W,radiusBottomRight:L,background:K,gap:P,style:V,...X}=t,te=n??"div",$={...V},z=$,Z={},Q=(U,fe)=>{if(fe===void 0)return;const me=fr(fe);me&&($[U]=me)},ce=(U,fe)=>{if(fe===void 0)return;const me=fr(fe);me&&($[U]=me)},j=(U,fe)=>{if(fe===void 0)return;const me=_L(fe);me&&($[U]=me)};if(r!==void 0){const U=fr(r);U&&(z["--box-padding"]=U)}if(a!==void 0){const U=fr(a);U&&($.paddingLeft=U,$.paddingRight=U)}if(o!==void 0){const U=fr(o);U&&($.paddingTop=U,$.paddingBottom=U)}Q("paddingTop",s),Q("paddingBottom",l),Q("paddingLeft",c),Q("paddingRight",u);const ge=[["sm",d],["md",h],["lg",p],["xl",b]];for(const[U,fe]of ge){if(fe===void 0)continue;const me=fr(fe);me&&(z[`--box-padding-${U}`]=me,Z[`data-padding-${U}`]="")}if(m!==void 0){const U=fr(m);U&&($.margin=U)}if(S!==void 0){const U=fr(S);U&&($.marginLeft=U,$.marginRight=U)}if(g!==void 0){const U=fr(g);U&&($.marginTop=U,$.marginBottom=U)}if(ce("marginTop",y),ce("marginBottom",x),ce("marginLeft",v),ce("marginRight",k),P!==void 0){const U=fr(P);U&&($.gap=U)}if(j("borderRadius",T),C!==void 0&&(j("borderTopLeftRadius",C),j("borderTopRightRadius",C)),R!==void 0&&(j("borderBottomLeftRadius",R),j("borderBottomRightRadius",R)),A!==void 0&&(j("borderTopLeftRadius",A),j("borderBottomLeftRadius",A)),N!==void 0&&(j("borderTopRightRadius",N),j("borderBottomRightRadius",N)),j("borderTopLeftRadius",O),j("borderTopRightRadius",B),j("borderBottomLeftRadius",W),j("borderBottomRightRadius",L),K!==void 0){const U=xL(K);U&&($.background=U)}return f.jsx(te,{ref:e,className:Rh(yL.box,i),style:$,...Z,...X})}const kL=hi.forwardRef(SL);kL.displayName="Box";const TL="_inline_1gpyx_1",wL="_vertical_1gpyx_6",CL="_divider_1gpyx_10",EL="_dividerVertical_1gpyx_16",RL="_customDivider_1gpyx_21",Ec={inline:TL,vertical:wL,divider:CL,dividerVertical:EL,customDivider:RL};function AL(t,e){const{as:n,direction:i="horizontal",gap:r,align:a="center",justify:o,wrap:s=!1,divider:l,className:c,style:u,children:d,...h}=t,p=n??"div",b={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=fr(r);y&&(b.gap=y)}const m=hi.Children.toArray(d).filter(y=>y!=null&&typeof y!="boolean"),S=y=>!l||y===0?null:l===!0||l==="line"?f.jsx("span",{"aria-hidden":"true",className:Rh(Ec.divider,i==="vertical"&&Ec.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:Ec.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const v=S(x);v&&g.push(v)}g.push(y)}),f.jsx(p,{ref:e,className:Rh(Ec.inline,i==="vertical"&&Ec.vertical,c),style:b,...h,children:g})}const NL=hi.forwardRef(AL);NL.displayName="Inline",w.createContext("vertical");function OL({size:t=24,color:e="#000"}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-x-icon lucide-x",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]})}function Uk({onClose:t}){return f.jsx("button",{className:"obi-button obi-close-button",onClick:t,"aria-label":"Close",type:"button",style:{outline:"none"},autoFocus:!1,children:f.jsx(OL,{})})}function zk({open:t=!1,children:e,onClose:n,size:i="medium",preventOutsideClick:r=!1}){const a=w.useRef(null),o=w.useRef(null);w.useEffect(()=>{const u=a.current;u&&(t&&!u.open?u.showModal():!t&&u.open&&(o.current="programmatic",u.close()))},[t]);const s=u=>{const d=a.current;u.target===d&&!r&&(o.current="user-initiated",d==null||d.close())},l=u=>{u.preventDefault(),o.current||(o.current="user-initiated");const d=o.current;o.current=null,n==null||n(d)},c=()=>{var u;o.current="user-initiated",(u=a.current)==null||u.close()};return w.useEffect(()=>{const u=a.current;if(u)return u.addEventListener("click",s),u.addEventListener("close",l),()=>{u.removeEventListener("click",s),u.removeEventListener("close",l)}},[n]),f.jsxs("dialog",{ref:a,className:`modal-${i}`,children:[f.jsx(Uk,{onClose:c}),f.jsx("div",{className:"modal-content",children:t?typeof e=="function"?e():e:null})]})}const Fk=8,Ah=8,ML=100,DL=.7,$s=3;function qk({getBands:t,color:e="white"}){const n=w.useRef(null);return w.useEffect(()=>{if(!t)return;let i=0,r;const a=o=>{try{if(o-i>=ML){const s=t();if(n.current){const l=n.current.querySelectorAll(".bar"),c=s&&s.length>0?s.slice(0,Ah).map(u=>{const d=Math.abs(u);return Math.min(d/DL*Fk,Fk)||$s}):Array(Ah).fill($s);for(;c.length<Ah;)c.push($s);c.forEach((u,d)=>{if(u<$s&&(u=$s),l[d]){const h=u*2;l[d].style.height=`${h}px`,l[d].style.display=u>0?"block":"none"}})}i=o}r=requestAnimationFrame(a)}catch(s){console.warn("Error updating equaliser:",s),r=requestAnimationFrame(a)}};return r=requestAnimationFrame(a),()=>{cancelAnimationFrame(r)}},[t]),f.jsx("div",{className:"obi-equaliser",ref:n,children:Array.from({length:Ah},(i,r)=>f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar",style:{height:`${$s}px`,backgroundColor:e,display:"block"}})},r))})}function Nh({className:t="",isActive:e=!1,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o}){let s=`obi-pill container ${e&&"active"}`;return n==="user-speaking"&&(s+=" user-speaking"),n==="busy"&&(s+=" busy"),f.jsx("div",{className:s,onMouseEnter:r,onMouseLeave:a,children:f.jsx("div",{className:`obi-pill pill ${t}`,onClick:i,children:o})})}function PL({className:t="",active:e,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o,...s}){const l=`obi-pill2 container ${e?"active":""} ${n==="user-speaking"?"user-speaking":""} ${t}`;return f.jsx("div",{className:l,...s,children:f.jsx("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:a,children:o})})}function LL({className:t="",active:e,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o,...s}){const l=`obi-pill-up container ${e?"active":""} ${n==="user-speaking"?"user-speaking":""} ${t}`;return f.jsx("div",{className:l,...s,children:f.jsx("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:a,children:o})})}function IL(t){const{spectrum:e}=t;return f.jsx(Nh,{isActive:!0,children:f.jsx(qk,{getBands:e})})}function jg(t){const{children:e,className:n="",...i}=t;return f.jsx("div",{className:`${n} obi-panel`,...i,children:e})}function Hk({className:t="",size:e=64}){return f.jsx("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,children:f.jsx("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 jL(t){const{currentStep:e,totalSteps:n,stepNames:i,className:r,onStepClick:a}=t,[o,s]=w.useState(null),l=Array.from({length:n},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),c=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(o!==null){const d=i[o]&&i[o].trim().length>0?i[o]:`Step ${o+1}`;return`${o+1}/${n} \u2022 ${d}`}return`${e}/${n} \u2022 ${c}`})();return f.jsxs("div",{className:`obi-course-progress ${r||""}`,children:[f.jsx("div",{className:"obi-course-progress-steps",children:l.map((d,h)=>{const p=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,b=d.isCompleted?"completed":"future";function m(){a&&a(h,p)}function S(g){a&&(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),m())}return f.jsx("div",{className:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>s(h),onMouseLeave:()=>s(null),onClick:a?m:void 0,onKeyDown:a?S:void 0,role:a?"button":void 0,tabIndex:a?0:void 0,children:f.jsx("div",{className:`obi-course-progress-step ${b}`,"aria-label":p})},h)})}),f.jsx("div",{className:"obi-course-progress-description",children:u})]})}function BL({onContinue:t,onWrapUp:e}){return f.jsx(jg,{className:"obi-exit-survey",children:f.jsx(zL,{onContinue:t,onWrapUp:()=>{e()}})})}function UL({onOtherSelect:t,onReasonSelect:e,onClose:n}){const[i,r]=w.useState("reason"),a=o=>{o==="other"?(t(),r("other-reason")):e(o)};return f.jsx(jg,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?f.jsx(FL,{onReasonSelect:a}):f.jsx(qL,{onReasonSelect:a,onClose:n})})}function zL({onContinue:t,onWrapUp:e}){return f.jsxs("div",{className:"obi-exit-survey-container",children:[f.jsx("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),f.jsxs("div",{className:"obi-exit-survey-options",children:[f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:t,type:"button",children:"No, let's continue"}),f.jsx("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 FL({onReasonSelect:t}){return f.jsxs("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[f.jsx("div",{className:"obi-exit-survey-header",children:f.jsx("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),f.jsxs("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("do-later"),type:"button",children:"Will do later"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("cant-talk"),type:"button",children:"Can't talk right now"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("prefer-written"),type:"button",children:"Prefer written instructions"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function qL({onReasonSelect:t,onClose:e}){const[n,i]=w.useState("");return f.jsxs("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[f.jsxs("div",{className:"obi-exit-survey-header",children:[f.jsx(Uk,{onClose:e}),f.jsx("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),f.jsxs("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[f.jsx("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:n,onChange:r=>i(r.target.value)}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>t("other-feedback",n),type:"button",children:"Send feedback"})]})]})}const HL=8;function Vk({color:t="white"}){return f.jsx("div",{className:"obi-loading-dots",children:Array.from({length:HL},(e,n)=>f.jsxs("div",{className:"column",children:[f.jsx("div",{className:"bar",style:{backgroundColor:t,animationDelay:`${n*.15}s`}}),f.jsx("div",{className:"dot",style:{backgroundColor:t}})]},n))})}function oa({className:t,children:e,onClick:n}){return n?f.jsx("button",{className:`obi-button obi-message ${t} clickable`,onClick:n,children:e}):f.jsx("div",{className:`obi-message ${t}`,children:e})}function VL(t){const{placeholder:e="Type your message...",value:n,defaultValue:i,onChange:r,onSend:a,onCancel:o,onExpand:s,isLoading:l=!1,disabled:c=!1,maxLength:u=500,children:d}=t,[h,p]=w.useState(n||i||""),[b,m]=w.useState((n||i||"").length>24),S=w.useRef(null);w.useLayoutEffect(()=>{b&&(s==null||s(!0))},[]);const g=n!==void 0?n:h,y=k=>{const T=k.currentTarget.value;n===void 0&&p(T),r==null||r(T)},x=k=>{k.key==="Escape"&&(p(n||i||""),m(!1),o==null||o()),k.key==="Enter"&&!k.shiftKey&&g.trim()&&(k.preventDefault(),p(n||i||""),m(!1),v()),(g||"").length>=24&&!b&&(m(!0),s==null||s(!0))};w.useEffect(()=>{S.current&&S.current.focus()},[S.current]);const v=()=>{!g.trim()||l||c||(a==null||a(g.trim()),n===void 0&&p(""))};return f.jsxs("div",{className:`obi-message-input ${b?"expanded":""}`,children:[f.jsx("div",{className:"container",children:f.jsx("textarea",{ref:S,className:"field",placeholder:e,value:g,onInput:y,onKeyDown:x,disabled:c||l,maxLength:u,rows:1})}),f.jsxs("div",{className:"button-container",children:[b&&f.jsx("div",{children:d}),f.jsx("button",{className:"obi-button send",onClick:v,disabled:!g.trim()||l||c,type:"button",children:f.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:f.jsx("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"})})})]})]})}const Bg=w.createContext(null);function GL({children:t}){const e=w.useContext(Bg);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:n,isOpen:i,setIsOpen:r,setAnimating:a,targetRef:o,trigger:s,onChange:l,delayMs:c}=e,u=w.useRef(null),d=Gk(o,a),[h,p]=w.useState(!1);w.useEffect(()=>{n!==void 0&&n!==h&&(n?m():S()),p(n)},[n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);function b(){u.current&&(clearTimeout(u.current),u.current=null)}function m(){b(),c>0?u.current=setTimeout(()=>{l==null||l(!0),r(!0),u.current=null},c):(l==null||l(!0),r(!0))}function S(){b(),l==null||l(!1),r(!1)}const g=()=>{s==="click"&&(i?S():m())};function y(){s==="hover"&&m()}function x(){s==="hover"&&S()}return f.jsx("div",{ref:d,className:"target",onClick:g,onMouseEnter:y,onMouseLeave:x,children:t})}function WL({children:t}){const e=w.useContext(Bg);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:n,animating:i,setAnimating:r,targetRef:a,contentRef:o}=e,s=Gk(o,r);return w.useLayoutEffect(()=>{if(n&&!i&&a.current&&o.current){const l=o.current;if(!l)return;const c=a.current;if(!c)return;const u=l.getBoundingClientRect(),d=c.getBoundingClientRect(),h=d.right-d.left;l.style.top=`${u.top-u.bottom-(8+e.offset)}px`,l.style.left=`${-(u.right-u.left-h)/2}px`}},[n,i]),n?f.jsx("div",{ref:s,className:"content",style:{opacity:i?0:1},children:t}):null}function fi({trigger:t="click",open:e,onChange:n,children:i,delayMs:r=0,offset:a=0,className:o=""}){const[s,l]=w.useState(!1),[c,u]=w.useState(!1),d=w.useRef(null),h=w.useRef(null),p={controlledOpen:e,isOpen:s,setIsOpen:l,animating:c,setAnimating:u,targetRef:d,contentRef:h,trigger:t,onChange:n,delayMs:r,offset:a};return f.jsx(Bg.Provider,{value:p,children:f.jsx("div",{className:`obi-popout ${o}`,children:i})})}fi.Target=GL,fi.Content=WL;function Gk(t,e){const n=w.useRef(null),i=w.useRef(null),r=w.useRef(!0),a=w.useCallback(o=>{if(t.current=o,!o){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function s(){if(r.current){r.current=!1;return}n.current?clearTimeout(n.current):e(!0),n.current=setTimeout(()=>{e(!1),n.current=null},200)}i.current=new ResizeObserver(s),i.current.observe(o,{box:"border-box"})},[]);return w.useEffect(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),a}function Qo({type:t,size:e=24}){return f.jsx("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:YL(t)})}function YL(t){switch(t){case"pause":return f.jsxs(f.Fragment,{children:[f.jsx("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),f.jsx("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return f.jsx(f.Fragment,{children:f.jsx("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 f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]});case"message":return f.jsx(f.Fragment,{children:f.jsx("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 f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"m14 10 7-7"}),f.jsx("path",{d:"M20 10h-6V4"}),f.jsx("path",{d:"m3 21 7-7"}),f.jsx("path",{d:"M4 14h6v6"})]});case"voice":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M2 10v3"}),f.jsx("path",{d:"M6 6v11"}),f.jsx("path",{d:"M10 3v18"}),f.jsx("path",{d:"M14 8v7"}),f.jsx("path",{d:"M18 5v13"}),f.jsx("path",{d:"M22 10v3"})]});case"open":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M12 7v14"}),f.jsx("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"})]})}}function pr({className:t,onClick:e,type:n,disabled:i,title:r}){const a={cancel:f.jsx(Qo,{type:"close",size:16}),pause:f.jsx(Qo,{type:"pause",size:16}),play:f.jsx(Qo,{type:"play",size:16}),message:f.jsx(Qo,{type:"message",size:16}),minimize:f.jsx(Qo,{type:"minimize",size:16}),voice:f.jsx(Qo,{type:"voice",size:16}),open:f.jsx(Qo,{type:"open",size:16})}[n],o={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[n],s=f.jsx("button",{className:`obi-button obi-round-button ${o} ${t}`,onClick:i?void 0:e,disabled:i,children:a});return r?f.jsxs(fi,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[f.jsx(fi.Target,{children:s}),f.jsx(fi.Content,{children:f.jsx("div",{className:"obi-round-button-title",children:r})})]}):s}function KL(t){const{disabled:e,inPlan:n,isPaused:i}=t,[r,a]=w.useState(null),[o,s]=w.useState(t.isActive??t.defaultIsActive??!1),[l,c]=w.useState(!1),[u,d]=w.useState(t.cancelling??!1),[h,p]=w.useState(t.messaging??!1),[b,m]=w.useState(!1),[S,g]=w.useState(h),[y,x]=w.useState(!1);function v(){s(!0),c(!1),x(!0)}function k(){}function T(){r&&(clearTimeout(r),a(null))}function C(){a(setTimeout(()=>{s(t.defaultIsActive??!1),x(!1)},400))}function R(be){var qe;m(!1),(qe=t.onMessage)==null||qe.call(t,be)}function A(){var be;p(!1),m(!1),s(!1),c(!0),(be=t.onMinimize)==null||be.call(t)}function N(){var be;p(!1),d(!0),m(!1),(be=t.onCancelClick)==null||be.call(t)}function O(){var be;n||((be=t.onOpen)==null||be.call(t))}function B(be){var qe,bt,Je,cn,tn,Mt;switch(be){case"need-help":(qe=t.onMessage)==null||qe.call(t,"I'm struggling, can you look at my screen and help me out."),(bt=t.onOneClickAction)==null||bt.call(t,"need-help");break;case"continue":(Je=t.onMessage)==null||Je.call(t,"Okay, let's continue."),(cn=t.onOneClickAction)==null||cn.call(t,"continue");break;case"say-again":(tn=t.onMessage)==null||tn.call(t,"Please say that again."),(Mt=t.onOneClickAction)==null||Mt.call(t,"say-again");break}}function W(be){var qe,bt;t.messaging===void 0?((qe=t.onMessagingChange)==null||qe.call(t,be),p(be)):((bt=t.onMessagingChange)==null||bt.call(t,!t.messaging),p(!t.messaging)),be||m(!1)}const L=t.isActive??((o||n)&&!l&&!e),K=L&&n,P=L&&n&&!b,V=t.speakingStatus==="user-speaking",X=t.speakingStatus==="thinking",te=t.speakingStatus==="busy",$=L&&!n&&!u&&y,z=L&&n&&i&&!V&&!u,Z=L&&n&&!z&&!V&&h!==S&&!u,Q=L&&n&&i&&V&&!u,ce=L&&n&&!i&&V&&!u,j=L&&n&&!i&&te&&!u,ge=t.messaging!==void 0?t.messaging:h,U=ge&&V,fe=$||z||Q||ce||Z||u,me=400,Rt=!!t.courseProgress&&!l,en=$?5:10;return w.useLayoutEffect(()=>{g(h)},[V]),!n&&!u?f.jsx(XL,{...t}):!n&&u?f.jsx($L,{onOtherSelect:()=>{var be;(be=t.onCancelReasonOther)==null||be.call(t)},onCancelReason:be=>{var qe;s(t.defaultIsActive??!1),d(!1),(qe=t.onCancelReason)==null||qe.call(t,be)},onClose:()=>{s(t.defaultIsActive??!1),d(!1)}}):f.jsxs(jg,{className:`obi-widget-panel ${K?"expanded":""} ${b?"maximized":""} ${ge?"messaging":""} ${te?"tool-usage":""}`,children:[f.jsxs("div",{className:`obi-widget ${L?"active":""} ${n?"in-plan":""}`,onMouseEnter:T,onMouseLeave:C,children:[P&&f.jsx(pr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),P&&!i&&f.jsx(pr,{type:"pause",onClick:t.onPause,title:"Pause session"}),P&&i&&f.jsx(pr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsxs(fi,{className:"obi-widget-popout",open:fe,trigger:null,delayMs:me,offset:en,children:[f.jsxs(fi.Target,{children:[U&&f.jsx(VL,{value:t.message,onCancel:()=>W(!1),onSend:R,onExpand:m,onChange:t.onMessageChange,children:f.jsxs("div",{className:"obi-widget-buttons",children:[f.jsx(pr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),!i&&f.jsx(pr,{type:"pause",onClick:t.onPause,title:"Pause session"}),i&&f.jsx(pr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsx(pr,{type:ge?"voice":"message",onClick:()=>W(!ge),title:ge?"Voice input":"Text input"}),f.jsx(pr,{type:"minimize",onClick:A,title:"Minimize widget"})]})}),!U&&f.jsxs(Nh,{className:L&&!n?"button":"",isActive:L,speakingStatus:t.speakingStatus,onClick:O,onMouseEnter:v,onMouseLeave:k,children:[L&&!n&&!j&&f.jsx("span",{className:"obi-widget-pill-text",children:"Tutorials"}),L&&n&&j&&f.jsx("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),L&&n&&!X&&!j&&f.jsx(qk,{getBands:t.spectrum}),L&&X&&!j&&f.jsx(Vk,{})]})]}),f.jsx(fi.Content,{children:f.jsxs("div",{onMouseLeave:C,children:[$&&f.jsx(oa,{onClick:O,children:"Click to see all"}),z&&f.jsx(oa,{children:"Session will pause shortly"}),Z&&f.jsxs(oa,{children:["Switched to ",ge?"chat":"voice"]}),Q&&f.jsx(oa,{children:"Paused"}),ce&&f.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[f.jsx(oa,{onClick:()=>B("need-help"),children:"Need help"}),f.jsx(oa,{onClick:()=>B("continue"),children:"Continue"}),f.jsx(oa,{onClick:()=>B("say-again"),children:"Say again"})]}),u&&f.jsx(BL,{onContinue:()=>{var be;(be=t.onCancelAbort)==null||be.call(t),d(!1),t.messaging!==void 0&&p(t.messaging)},onWrapUp:()=>{var be;(be=t.onCancel)==null||be.call(t)}})]})})]}),P&&f.jsx(pr,{type:ge?"voice":"message",onClick:()=>W(!ge),title:ge?"Voice input":"Text input"}),P&&f.jsx(pr,{type:"minimize",onClick:A,title:"Minimize widget"})]}),Rt&&t.courseProgress&&f.jsx("div",{className:`obi-widget-course-progress ${ge?"expanded":""}`,children:f.jsx(jL,{currentStep:t.courseProgress.currentStep,totalSteps:t.courseProgress.totalSteps,stepNames:t.courseProgress.stepNames,onStepClick:(be,qe)=>{var Je;const bt=`Can we please jump to the steps related to: ${qe}`;(Je=t.onMessage)==null||Je.call(t,bt)}})})]})}function XL(t){const{disabled:e,completedTutorials:n,totalTutorials:i,agentName:r}=t,[a,o]=w.useState(null),[s,l]=w.useState(t.isActive??t.defaultIsActive??!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.hovered??!1),[p,b]=w.useState(null),[m,S]=w.useState(null);function g(){m&&(clearTimeout(m),S(null)),p&&b(null)}function y(){var W;l(!0),u(!1),h(!0),(W=t.onHover)==null||W.call(t,!0)}function x(){}function v(){a&&(clearTimeout(a),o(null))}function k(){s&&o(setTimeout(()=>{var W;l(t.defaultIsActive??!1),h(!1),(W=t.onHover)==null||W.call(t,!1)},400))}function T(){g(),l(!1),u(!0)}function C(){var W;g(),(W=t.onOpen)==null||W.call(t)}const R=t.hovered??(d&&!c),A=t.isActive??(s&&!e&&!c),N=A&&R||!!p,O=`round-button ${A?"active":""}`;let B=`${r||"Obi"}`;return n!==void 0&&i!==void 0&&n>=0&&i>0&&(B=`${n}/${i} completed`),w.useLayoutEffect(()=>{if(t.toastMessage&&t.toastMessage.text){m&&clearTimeout(m);const W=t.toastMessage.autoCloseMs??3e3;b({text:t.toastMessage.text,autoCloseMs:W});const L=setTimeout(()=>{b(null)},W);S(L)}else t.toastMessage===null&&(m&&clearTimeout(m),b(null))},[t.toastMessage]),f.jsx("div",{className:"obi-widget-out-of-plan-container",children:f.jsxs("div",{className:`obi-widget-out-of-plan ${R?"hover":""} ${A?"active":""}`,onMouseEnter:v,onMouseLeave:k,onClickCapture:g,children:[f.jsx("div",{className:O,style:{width:"30px",height:"30px"}}),f.jsxs(fi,{className:"obi-widget-popout",open:N,trigger:null,delayMs:400,offset:5,children:[f.jsx(fi.Target,{children:f.jsx(LL,{className:A?"button":"",active:A,onClick:C,onMouseEnter:y,onMouseLeave:x,children:f.jsxs("span",{className:"text",children:[f.jsx(Hk,{size:16}),B]})})}),f.jsxs(fi.Content,{children:[!!p&&f.jsx(oa,{onClick:()=>{g(),C()},children:p.text}),!p&&f.jsx("div",{onMouseLeave:k,children:f.jsx(oa,{className:"message",onClick:C,children:"Click to see all"})})]})]}),f.jsx(pr,{className:O,type:"minimize",onClick:T,title:"Minimize widget"})]})})}function $L(t){return f.jsx("div",{className:"obi-widget-out-of-plan-container",children:f.jsx("div",{className:"obi-widget-out-of-plan",children:f.jsxs(fi,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[f.jsx(fi.Target,{children:f.jsx(PL,{active:!1})}),f.jsx(fi.Content,{children:f.jsx(UL,{onOtherSelect:()=>{var e;(e=t.onOtherSelect)==null||e.call(t)},onReasonSelect:(e,n)=>{var i;(i=t.onCancelReason)==null||i.call(t,e,n)},onClose:()=>{var e;(e=t.onClose)==null||e.call(t)}})})]})})})}function JL({open:t=!1,children:e,onClose:n,preventOutsideClick:i=!1}){return f.jsx(zk,{open:t,onClose:n,preventOutsideClick:i,size:"medium",children:f.jsx("div",{className:"tour content-area",children:t?typeof e=="function"?e():e:null})})}function QL({logoUrl:t="",appName:e="App"}){const[n,i]=w.useState(!1),[r,a]=w.useState(!1),o=()=>{i(!0)},s=()=>{a(!0),i(!1)},l={container:{display:"block"},logoContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden"},backgroundPattern:{position:"absolute",inset:0,zIndex:0,background:"#F5F5F5",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='277' height='195' viewBox='0 0 277 195' fill='none'%3E%3Cpath opacity='0.4' d='M341.308 0.75C380.279 0.750001 411.872 24.3772 411.872 53.5229C411.872 82.6685 380.279 106.296 341.308 106.296H215.792C176.964 108.335 145.691 130.837 141.128 159.475V256.616C145.912 286.659 180.089 309.954 221.548 309.954H330.872C375.607 309.954 411.872 282.833 411.872 249.377V159.069C411.872 129.923 443.465 106.296 482.436 106.296C521.407 106.296 553 129.923 553 159.069V257.181C553 285.058 524.099 307.88 487.483 309.815C489.264 309.902 491.061 309.954 492.871 309.954C448.137 309.954 411.872 337.076 411.872 370.532C411.872 369.177 411.803 367.834 411.686 366.502C409.098 393.885 378.582 415.5 341.308 415.5H210.118C171.147 415.5 139.554 391.873 139.554 362.727C139.554 362.204 139.565 361.683 139.585 361.163C133.564 332.156 100.023 309.954 59.5488 309.954C61.4544 309.954 63.3441 309.9 65.2169 309.803C28.7434 307.76 -8.57239e-07 284.982 0 257.181V159.069C1.64632e-06 130.901 29.5078 107.89 66.6662 106.377C64.3207 106.224 61.9472 106.141 59.5488 106.141C100.012 106.141 133.54 83.951 139.575 54.9552C139.558 54.4793 139.554 54.0018 139.554 53.5229C139.554 24.3772 171.147 0.75 210.118 0.75H341.308Z' fill='white'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"190px 60px",backgroundSize:"300px 225px"},logoWrapper:{background:"#888888",width:"120px",height:"120px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",zIndex:10,overflow:"hidden"},appLogo:{width:"120px",height:"120px",objectFit:"cover",display:t&&!n&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!t||n||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return f.jsx("div",{style:l.container,children:f.jsxs("div",{style:l.logoContainer,children:[f.jsx("div",{style:l.backgroundPattern}),f.jsxs("div",{style:l.logoWrapper,children:[t&&f.jsx("img",{style:l.appLogo,src:t,alt:`${e} logo`,onError:o,onLoad:s}),f.jsx("div",{style:l.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function Js({className:t,title:e="",agentName:n="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:a=!1,footer:o,href:s=null,glow:l=!1,centerVisual:c,description:u,button:d,onAction:h}){const[p,b]=w.useState(a),[m,S]=w.useState(!1),[g,y]=w.useState(r);w.useEffect(()=>{m||(r==="listening"&&g!=="listening"&&p&&b(!1),r!=="listening"&&!p&&b(!0)),y(r)},[r,p]),w.useEffect(()=>{b(a)},[a]);const x=()=>{p||(b(!0),S(!0),h==null||h())},v=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${n} is speaking`;default:return i}},k=s?"a":"button",T=s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return f.jsx("div",{className:Rh("tour-content",t),children:f.jsxs("div",{className:"container",children:[f.jsx("div",{className:`visual ${l?"glow":""}`,children:c}),f.jsxs("div",{className:"header",children:[f.jsx("h1",{className:"title",children:e}),f.jsx("div",{className:"description",children:u})]}),f.jsx("div",{className:"button-container",children:d||f.jsx(k,{className:`action-button ${p?"disabled":""}`,onClick:x,disabled:p,...T,children:f.jsx("span",{className:"button-text",children:v()})})}),o&&f.jsx("div",{className:"tour-footer",children:o})]})})}function ZL({session:t,speakingState:e,onAction:n}){const i=t.appName?`Navigate to ${t.appName}`:"Navigate to app",r=t.appName?`Open ${t.appName}`:"Open app",a=t.appName?`Enjoy the tutorial in ${t.appName}`:"Enjoy the tutorial";return f.jsx(Js,{title:i,subtitle:"Click the button below to open the app",agentName:t.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:t.url,description:a,centerVisual:f.jsx(QL,{logoUrl:t.appLogoUrl,appName:t.appName}),onAction:n})}const{entries:Wk,setPrototypeOf:Yk,isFrozen:eI,getPrototypeOf:tI,getOwnPropertyDescriptor:nI}=Object;let{freeze:Xn,seal:Vi,create:Ug}=Object,{apply:zg,construct:Fg}=typeof Reflect<"u"&&Reflect;Xn||(Xn=function(t){return t}),Vi||(Vi=function(t){return t}),zg||(zg=function(t,e){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return t.apply(e,i)}),Fg||(Fg=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];return new t(...n)});const Oh=Jn(Array.prototype.forEach),iI=Jn(Array.prototype.lastIndexOf),Kk=Jn(Array.prototype.pop),Rc=Jn(Array.prototype.push),rI=Jn(Array.prototype.splice),Mh=Jn(String.prototype.toLowerCase),qg=Jn(String.prototype.toString),Hg=Jn(String.prototype.match),Ac=Jn(String.prototype.replace),aI=Jn(String.prototype.indexOf),oI=Jn(String.prototype.trim),mr=Jn(Object.prototype.hasOwnProperty),$n=Jn(RegExp.prototype.test),Nc=sI(TypeError);function Jn(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return zg(t,e,i)}}function sI(t){return function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return Fg(t,n)}}function Me(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Mh;Yk&&Yk(t,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const a=n(r);a!==r&&(eI(e)||(e[i]=a),r=a)}t[r]=!0}return t}function lI(t){for(let e=0;e<t.length;e++)mr(t,e)||(t[e]=null);return t}function jr(t){const e=Ug(null);for(const[n,i]of Wk(t))mr(t,n)&&(Array.isArray(i)?e[n]=lI(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=jr(i):e[n]=i);return e}function Oc(t,e){for(;t!==null;){const i=nI(t,e);if(i){if(i.get)return Jn(i.get);if(typeof i.value=="function")return Jn(i.value)}t=tI(t)}function n(){return null}return n}const Xk=Xn(["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","search","section","select","shadow","slot","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"]),Vg=Xn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Gg=Xn(["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"]),cI=Xn(["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"]),Wg=Xn(["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"]),uI=Xn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),$k=Xn(["#text"]),Jk=Xn(["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","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","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","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Yg=Xn(["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","mask-type","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"]),Qk=Xn(["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"]),Dh=Xn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),dI=Vi(/\{\{[\w\W]*|[\w\W]*\}\}/gm),hI=Vi(/<%[\w\W]*|[\w\W]*%>/gm),fI=Vi(/\$\{[\w\W]*/gm),pI=Vi(/^data-[\-\w.\u00B7-\uFFFF]+$/),mI=Vi(/^aria-[\-\w]+$/),Zk=Vi(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),gI=Vi(/^(?:\w+script|data):/i),vI=Vi(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),eT=Vi(/^html$/i),bI=Vi(/^[a-z][.\w]*(-[.\w]+)+$/i);var tT=Object.freeze({__proto__:null,ARIA_ATTR:mI,ATTR_WHITESPACE:vI,CUSTOM_ELEMENT:bI,DATA_ATTR:pI,DOCTYPE_NAME:eT,ERB_EXPR:hI,IS_ALLOWED_URI:Zk,IS_SCRIPT_OR_DATA:gI,MUSTACHE_EXPR:dI,TMPLIT_EXPR:fI});const Mc={element:1,text:3,progressingInstruction:7,comment:8,document:9},yI=function(){return typeof window>"u"?null:window},_I=function(t,e){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(n=e.getAttribute(i));const r="dompurify"+(n?"#"+n:"");try{return t.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},nT=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function iT(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:yI();const e=_=>iT(_);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==Mc.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const i=n,r=i.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:l,NodeFilter:c,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:p}=t,b=l.prototype,m=Oc(b,"cloneNode"),S=Oc(b,"remove"),g=Oc(b,"nextSibling"),y=Oc(b,"childNodes"),x=Oc(b,"parentNode");if(typeof o=="function"){const _=n.createElement("template");_.content&&_.content.ownerDocument&&(n=_.content.ownerDocument)}let v,k="";const{implementation:T,createNodeIterator:C,createDocumentFragment:R,getElementsByTagName:A}=n,{importNode:N}=i;let O=nT();e.isSupported=typeof Wk=="function"&&typeof x=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:B,ERB_EXPR:W,TMPLIT_EXPR:L,DATA_ATTR:K,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:V,ATTR_WHITESPACE:X,CUSTOM_ELEMENT:te}=tT;let{IS_ALLOWED_URI:$}=tT,z=null;const Z=Me({},[...Xk,...Vg,...Gg,...Wg,...$k]);let Q=null;const ce=Me({},[...Jk,...Yg,...Qk,...Dh]);let j=Object.seal(Ug(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,U=null;const fe=Object.seal(Ug(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let me=!0,Rt=!0,en=!1,be=!0,qe=!1,bt=!0,Je=!1,cn=!1,tn=!1,Mt=!1,bn=!1,yn=!1,In=!0,Si=!1;const de="user-content-";let We=!0,Ce=!1,Qe={},ot=null;const ki=Me({},["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 Ii=null;const Wr=Me({},["audio","video","img","source","image","track"]);let q=null;const ae=Me({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),he="http://www.w3.org/1998/Math/MathML",Ye="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let it=Pe,jn=!1,Ti=null;const Bn=Me({},[he,Ye,Pe],qg);let Un=Me({},["mi","mo","mn","ms","mtext"]),Wt=Me({},["annotation-xml"]);const ai=Me({},["title","style","font","a","script"]);let zn=null;const Vl=["application/xhtml+xml","text/html"],ks="text/html";let Se=null,Fn=null;const Gl=n.createElement("form"),Ao=function(_){return _ instanceof RegExp||_ instanceof Function},Yr=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Fn&&Fn===_)){if((!_||typeof _!="object")&&(_={}),_=jr(_),zn=Vl.indexOf(_.PARSER_MEDIA_TYPE)===-1?ks:_.PARSER_MEDIA_TYPE,Se=zn==="application/xhtml+xml"?qg:Mh,z=mr(_,"ALLOWED_TAGS")?Me({},_.ALLOWED_TAGS,Se):Z,Q=mr(_,"ALLOWED_ATTR")?Me({},_.ALLOWED_ATTR,Se):ce,Ti=mr(_,"ALLOWED_NAMESPACES")?Me({},_.ALLOWED_NAMESPACES,qg):Bn,q=mr(_,"ADD_URI_SAFE_ATTR")?Me(jr(ae),_.ADD_URI_SAFE_ATTR,Se):ae,Ii=mr(_,"ADD_DATA_URI_TAGS")?Me(jr(Wr),_.ADD_DATA_URI_TAGS,Se):Wr,ot=mr(_,"FORBID_CONTENTS")?Me({},_.FORBID_CONTENTS,Se):ki,ge=mr(_,"FORBID_TAGS")?Me({},_.FORBID_TAGS,Se):jr({}),U=mr(_,"FORBID_ATTR")?Me({},_.FORBID_ATTR,Se):jr({}),Qe=mr(_,"USE_PROFILES")?_.USE_PROFILES:!1,me=_.ALLOW_ARIA_ATTR!==!1,Rt=_.ALLOW_DATA_ATTR!==!1,en=_.ALLOW_UNKNOWN_PROTOCOLS||!1,be=_.ALLOW_SELF_CLOSE_IN_ATTR!==!1,qe=_.SAFE_FOR_TEMPLATES||!1,bt=_.SAFE_FOR_XML!==!1,Je=_.WHOLE_DOCUMENT||!1,Mt=_.RETURN_DOM||!1,bn=_.RETURN_DOM_FRAGMENT||!1,yn=_.RETURN_TRUSTED_TYPE||!1,tn=_.FORCE_BODY||!1,In=_.SANITIZE_DOM!==!1,Si=_.SANITIZE_NAMED_PROPS||!1,We=_.KEEP_CONTENT!==!1,Ce=_.IN_PLACE||!1,$=_.ALLOWED_URI_REGEXP||Zk,it=_.NAMESPACE||Pe,Un=_.MATHML_TEXT_INTEGRATION_POINTS||Un,Wt=_.HTML_INTEGRATION_POINTS||Wt,j=_.CUSTOM_ELEMENT_HANDLING||{},_.CUSTOM_ELEMENT_HANDLING&&Ao(_.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=_.CUSTOM_ELEMENT_HANDLING.tagNameCheck),_.CUSTOM_ELEMENT_HANDLING&&Ao(_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(j.attributeNameCheck=_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),_.CUSTOM_ELEMENT_HANDLING&&typeof _.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(j.allowCustomizedBuiltInElements=_.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),qe&&(Rt=!1),bn&&(Mt=!0),Qe&&(z=Me({},$k),Q=[],Qe.html===!0&&(Me(z,Xk),Me(Q,Jk)),Qe.svg===!0&&(Me(z,Vg),Me(Q,Yg),Me(Q,Dh)),Qe.svgFilters===!0&&(Me(z,Gg),Me(Q,Yg),Me(Q,Dh)),Qe.mathMl===!0&&(Me(z,Wg),Me(Q,Qk),Me(Q,Dh))),_.ADD_TAGS&&(typeof _.ADD_TAGS=="function"?fe.tagCheck=_.ADD_TAGS:(z===Z&&(z=jr(z)),Me(z,_.ADD_TAGS,Se))),_.ADD_ATTR&&(typeof _.ADD_ATTR=="function"?fe.attributeCheck=_.ADD_ATTR:(Q===ce&&(Q=jr(Q)),Me(Q,_.ADD_ATTR,Se))),_.ADD_URI_SAFE_ATTR&&Me(q,_.ADD_URI_SAFE_ATTR,Se),_.FORBID_CONTENTS&&(ot===ki&&(ot=jr(ot)),Me(ot,_.FORBID_CONTENTS,Se)),_.ADD_FORBID_CONTENTS&&(ot===ki&&(ot=jr(ot)),Me(ot,_.ADD_FORBID_CONTENTS,Se)),We&&(z["#text"]=!0),Je&&Me(z,["html","head","body"]),z.table&&(Me(z,["tbody"]),delete ge.tbody),_.TRUSTED_TYPES_POLICY){if(typeof _.TRUSTED_TYPES_POLICY.createHTML!="function")throw Nc('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof _.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Nc('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=_.TRUSTED_TYPES_POLICY,k=v.createHTML("")}else v===void 0&&(v=_I(p,r)),v!==null&&typeof k=="string"&&(k=v.createHTML(""));Xn&&Xn(_),Fn=_}},No=Me({},[...Vg,...Gg,...cI]),Oo=Me({},[...Wg,...uI]),Wl=function(_){let I=x(_);(!I||!I.tagName)&&(I={namespaceURI:it,tagName:"template"});const M=Mh(_.tagName),pe=Mh(I.tagName);return Ti[_.namespaceURI]?_.namespaceURI===Ye?I.namespaceURI===Pe?M==="svg":I.namespaceURI===he?M==="svg"&&(pe==="annotation-xml"||Un[pe]):!!No[M]:_.namespaceURI===he?I.namespaceURI===Pe?M==="math":I.namespaceURI===Ye?M==="math"&&Wt[pe]:!!Oo[M]:_.namespaceURI===Pe?I.namespaceURI===Ye&&!Wt[pe]||I.namespaceURI===he&&!Un[pe]?!1:!Oo[M]&&(ai[M]||!No[M]):!!(zn==="application/xhtml+xml"&&Ti[_.namespaceURI]):!1},_n=function(_){Rc(e.removed,{element:_});try{x(_).removeChild(_)}catch{S(_)}},xn=function(_,I){try{Rc(e.removed,{attribute:I.getAttributeNode(_),from:I})}catch{Rc(e.removed,{attribute:null,from:I})}if(I.removeAttribute(_),_==="is")if(Mt||bn)try{_n(I)}catch{}else try{I.setAttribute(_,"")}catch{}},Mo=function(_){let I=null,M=null;if(tn)_="<remove></remove>"+_;else{const ve=Hg(_,/^[\r\n\t ]+/);M=ve&&ve[0]}zn==="application/xhtml+xml"&&it===Pe&&(_='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+_+"</body></html>");const pe=v?v.createHTML(_):_;if(it===Pe)try{I=new h().parseFromString(pe,zn)}catch{}if(!I||!I.documentElement){I=T.createDocument(it,"template",null);try{I.documentElement.innerHTML=jn?k:pe}catch{}}const Le=I.body||I.documentElement;return _&&M&&Le.insertBefore(n.createTextNode(M),Le.childNodes[0]||null),it===Pe?A.call(I,Je?"html":"body")[0]:Je?I.documentElement:Le},Do=function(_){return C.call(_.ownerDocument||_,_,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Kr=function(_){return _ instanceof d&&(typeof _.nodeName!="string"||typeof _.textContent!="string"||typeof _.removeChild!="function"||!(_.attributes instanceof u)||typeof _.removeAttribute!="function"||typeof _.setAttribute!="function"||typeof _.namespaceURI!="string"||typeof _.insertBefore!="function"||typeof _.hasChildNodes!="function")},Po=function(_){return typeof s=="function"&&_ instanceof s};function Ut(_,I,M){Oh(_,pe=>{pe.call(e,I,M,Fn)})}const Lo=function(_){let I=null;if(Ut(O.beforeSanitizeElements,_,null),Kr(_))return _n(_),!0;const M=Se(_.nodeName);if(Ut(O.uponSanitizeElement,_,{tagName:M,allowedTags:z}),bt&&_.hasChildNodes()&&!Po(_.firstElementChild)&&$n(/<[/\w!]/g,_.innerHTML)&&$n(/<[/\w!]/g,_.textContent)||_.nodeType===Mc.progressingInstruction||bt&&_.nodeType===Mc.comment&&$n(/<[/\w]/g,_.data))return _n(_),!0;if(!(fe.tagCheck instanceof Function&&fe.tagCheck(M))&&(!z[M]||ge[M])){if(!ge[M]&&jo(M)&&(j.tagNameCheck instanceof RegExp&&$n(j.tagNameCheck,M)||j.tagNameCheck instanceof Function&&j.tagNameCheck(M)))return!1;if(We&&!ot[M]){const pe=x(_)||_.parentNode,Le=y(_)||_.childNodes;if(Le&&pe){const ve=Le.length;for(let zt=ve-1;zt>=0;--zt){const _t=m(Le[zt],!0);_t.__removalCount=(_.__removalCount||0)+1,pe.insertBefore(_t,g(_))}}}return _n(_),!0}return _ instanceof l&&!Wl(_)||(M==="noscript"||M==="noembed"||M==="noframes")&&$n(/<\/no(script|embed|frames)/i,_.innerHTML)?(_n(_),!0):(qe&&_.nodeType===Mc.text&&(I=_.textContent,Oh([B,W,L],pe=>{I=Ac(I,pe," ")}),_.textContent!==I&&(Rc(e.removed,{element:_.cloneNode()}),_.textContent=I)),Ut(O.afterSanitizeElements,_,null),!1)},Io=function(_,I,M){if(In&&(I==="id"||I==="name")&&(M in n||M in Gl))return!1;if(!(Rt&&!U[I]&&$n(K,I))&&!(me&&$n(P,I))&&!(fe.attributeCheck instanceof Function&&fe.attributeCheck(I,_))){if(!Q[I]||U[I]){if(!(jo(_)&&(j.tagNameCheck instanceof RegExp&&$n(j.tagNameCheck,_)||j.tagNameCheck instanceof Function&&j.tagNameCheck(_))&&(j.attributeNameCheck instanceof RegExp&&$n(j.attributeNameCheck,I)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(I,_))||I==="is"&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&$n(j.tagNameCheck,M)||j.tagNameCheck instanceof Function&&j.tagNameCheck(M))))return!1}else if(!q[I]&&!$n($,Ac(M,X,""))&&!((I==="src"||I==="xlink:href"||I==="href")&&_!=="script"&&aI(M,"data:")===0&&Ii[_])&&!(en&&!$n(V,Ac(M,X,"")))&&M)return!1}return!0},jo=function(_){return _!=="annotation-xml"&&Hg(_,te)},Bo=function(_){Ut(O.beforeSanitizeAttributes,_,null);const{attributes:I}=_;if(!I||Kr(_))return;const M={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Q,forceKeepAttr:void 0};let pe=I.length;for(;pe--;){const Le=I[pe],{name:ve,namespaceURI:zt,value:_t}=Le,xt=Se(ve),Xr=_t;let Ie=ve==="value"?Xr:oI(Xr);if(M.attrName=xt,M.attrValue=Ie,M.keepAttr=!0,M.forceKeepAttr=void 0,Ut(O.uponSanitizeAttribute,_,M),Ie=M.attrValue,Si&&(xt==="id"||xt==="name")&&(xn(ve,_),Ie=de+Ie),bt&&$n(/((--!?|])>)|<\/(style|title|textarea)/i,Ie)){xn(ve,_);continue}if(xt==="attributename"&&Hg(Ie,"href")){xn(ve,_);continue}if(M.forceKeepAttr)continue;if(!M.keepAttr){xn(ve,_);continue}if(!be&&$n(/\/>/i,Ie)){xn(ve,_);continue}qe&&Oh([B,W,L],Kl=>{Ie=Ac(Ie,Kl," ")});const Uo=Se(_.nodeName);if(!Io(Uo,xt,Ie)){xn(ve,_);continue}if(v&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!zt)switch(p.getAttributeType(Uo,xt)){case"TrustedHTML":{Ie=v.createHTML(Ie);break}case"TrustedScriptURL":{Ie=v.createScriptURL(Ie);break}}if(Ie!==Xr)try{zt?_.setAttributeNS(zt,ve,Ie):_.setAttribute(ve,Ie),Kr(_)?_n(_):Kk(e.removed)}catch{xn(ve,_)}}Ut(O.afterSanitizeAttributes,_,null)},Yl=function _(I){let M=null;const pe=Do(I);for(Ut(O.beforeSanitizeShadowDOM,I,null);M=pe.nextNode();)Ut(O.uponSanitizeShadowNode,M,null),Lo(M),Bo(M),M.content instanceof a&&_(M.content);Ut(O.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(_){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,pe=null,Le=null,ve=null;if(jn=!_,jn&&(_="<!-->"),typeof _!="string"&&!Po(_))if(typeof _.toString=="function"){if(_=_.toString(),typeof _!="string")throw Nc("dirty is not a string, aborting")}else throw Nc("toString is not a function");if(!e.isSupported)return _;if(cn||Yr(I),e.removed=[],typeof _=="string"&&(Ce=!1),Ce){if(_.nodeName){const xt=Se(_.nodeName);if(!z[xt]||ge[xt])throw Nc("root node is forbidden and cannot be sanitized in-place")}}else if(_ instanceof s)M=Mo("<!---->"),pe=M.ownerDocument.importNode(_,!0),pe.nodeType===Mc.element&&pe.nodeName==="BODY"||pe.nodeName==="HTML"?M=pe:M.appendChild(pe);else{if(!Mt&&!qe&&!Je&&_.indexOf("<")===-1)return v&&yn?v.createHTML(_):_;if(M=Mo(_),!M)return Mt?null:yn?k:""}M&&tn&&_n(M.firstChild);const zt=Do(Ce?_:M);for(;Le=zt.nextNode();)Lo(Le),Bo(Le),Le.content instanceof a&&Yl(Le.content);if(Ce)return _;if(Mt){if(bn)for(ve=R.call(M.ownerDocument);M.firstChild;)ve.appendChild(M.firstChild);else ve=M;return(Q.shadowroot||Q.shadowrootmode)&&(ve=N.call(i,ve,!0)),ve}let _t=Je?M.outerHTML:M.innerHTML;return Je&&z["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&$n(eT,M.ownerDocument.doctype.name)&&(_t="<!DOCTYPE "+M.ownerDocument.doctype.name+`>
@@ -130,4 +130,4 @@ ${t}</tr>
130
130
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
131
131
  `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${Ea(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let i=this.parser.parseInline(n),r=v3(t);if(r===null)return i;t=r;let a='<a href="'+t+'"';return e&&(a+=' title="'+Ea(e)+'"'),a+=">"+i+"</a>",a}image({href:t,title:e,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let r=v3(t);if(r===null)return Ea(n);t=r;let a=`<img src="${t}" alt="${n}"`;return e&&(a+=` title="${Ea(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Ea(t.text)}},Gb=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},xr=class ry{constructor(e){vt(this,"options"),vt(this,"renderer"),vt(this,"textRenderer"),this.options=e||xs,this.options.renderer=this.options.renderer||new vp,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Gb}static parse(e,n){return new ry(n).parse(e)}static parseInline(e,n){return new ry(n).parseInline(e)}parse(e){var i,r;let n="";for(let a=0;a<e.length;a++){let o=e[a];if((r=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&r[o.type]){let l=o,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){n+=c||"";continue}}let s=o;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let l='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return n}parseInline(e,n=this.renderer){var r,a;let i="";for(let o=0;o<e.length;o++){let s=e[o];if((a=(r=this.options.extensions)==null?void 0:r.renderers)!=null&&a[s.type]){let c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){i+=c||"";continue}}let l=s;switch(l.type){case"escape":{i+=n.text(l);break}case"html":{i+=n.html(l);break}case"link":{i+=n.link(l);break}case"image":{i+=n.image(l);break}case"checkbox":{i+=n.checkbox(l);break}case"strong":{i+=n.strong(l);break}case"em":{i+=n.em(l);break}case"codespan":{i+=n.codespan(l);break}case"br":{i+=n.br(l);break}case"del":{i+=n.del(l);break}case"text":{i+=n.text(l);break}default:{let c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return i}},bp,zu=(bp=class{constructor(t){vt(this,"options"),vt(this,"block"),this.options=t||xs}preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?_r.lex:_r.lexInline}provideParser(){return this.block?xr.parse:xr.parseInline}},vt(bp,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),vt(bp,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),bp),Jz=class{constructor(...t){vt(this,"defaults",Ib()),vt(this,"options",this.setOptions),vt(this,"parse",this.parseMarkdown(!0)),vt(this,"parseInline",this.parseMarkdown(!1)),vt(this,"Parser",xr),vt(this,"Renderer",vp),vt(this,"TextRenderer",Gb),vt(this,"Lexer",_r),vt(this,"Tokenizer",gp),vt(this,"Hooks",zu),this.use(...t)}walkTokens(t,e){var i,r;let n=[];for(let a of t)switch(n=n.concat(e.call(this,a)),a.type){case"table":{let o=a;for(let s of o.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of o.rows)for(let l of s)n=n.concat(this.walkTokens(l.tokens,e));break}case"list":{let o=a;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=a;(r=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&r[o.type]?this.defaults.extensions.childTokens[o.type].forEach(s=>{let l=o[s].flat(1/0);n=n.concat(this.walkTokens(l,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let a=e.renderers[r.name];a?e.renderers[r.name]=function(...o){let s=r.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[r.level];a?a.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),i.extensions=e),n.renderer){let r=this.defaults.renderer||new vp(this.defaults);for(let a in n.renderer){if(!(a in r))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=n.renderer[o],l=r[o];r[o]=(...c)=>{let u=s.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}i.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new gp(this.defaults);for(let a in n.tokenizer){if(!(a in r))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=n.tokenizer[o],l=r[o];r[o]=(...c)=>{let u=s.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}i.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new zu;for(let a in n.hooks){if(!(a in r))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=n.hooks[o],l=r[o];zu.passThroughHooks.has(a)?r[o]=c=>{if(this.defaults.async&&zu.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(r,c);return l.call(r,d)})();let u=s.call(r,c);return l.call(r,u)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(r,c);return d===!1&&(d=await l.apply(r,c)),d})();let u=s.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}i.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,a=n.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),r&&(s=s.concat(r.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return _r.lex(t,e??this.defaults)}parser(t,e){return xr.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let i={...n},r={...this.defaults,...i},a=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=t),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(e):e,s=await(r.hooks?await r.hooks.provideLexer():t?_r.lex:_r.lexInline)(o,r),l=r.hooks?await r.hooks.processAllTokens(s):s;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser():t?xr.parse:xr.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(a);try{r.hooks&&(e=r.hooks.preprocess(e));let o=(r.hooks?r.hooks.provideLexer():t?_r.lex:_r.lexInline)(e,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let s=(r.hooks?r.hooks.provideParser():t?xr.parse:xr.parseInline)(o,r);return r.hooks&&(s=r.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(t,e){return n=>{if(n.message+=`
132
132
  Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+Ea(n.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(n);throw n}}},Ss=new Jz;function at(t,e){return Ss.parse(t,e)}at.options=at.setOptions=function(t){return Ss.setOptions(t),at.defaults=Ss.defaults,i3(at.defaults),at},at.getDefaults=Ib,at.defaults=xs,at.use=function(...t){return Ss.use(...t),at.defaults=Ss.defaults,i3(at.defaults),at},at.walkTokens=function(t,e){return Ss.walkTokens(t,e)},at.parseInline=Ss.parseInline,at.Parser=xr,at.parser=xr.parse,at.Renderer=vp,at.TextRenderer=Gb,at.Lexer=_r,at.lexer=_r.lex,at.Tokenizer=gp,at.Hooks=zu,at.parse=at,at.options,at.setOptions,at.use,at.walkTokens,at.parseInline,xr.parse,_r.lex;const Qz="_base_1ne03_1",Zz={base:Qz},eF=["p","br","strong","em","u","a","ul","ol","li","h1","h2","h3","h4","h5","h6","code","pre","blockquote","hr"],tF=["href","title","target","rel"];at.setOptions({breaks:!0,gfm:!0});function nF(t){const{content:e,className:n,...i}=t,r=w.useMemo(()=>{if(!e)return"";const a=at.parse(e,{async:!1});return pz.sanitize(a,{ALLOWED_TAGS:[...eF],ALLOWED_ATTR:[...tF],ALLOW_DATA_ATTR:!1})},[e]);return r?f.jsx("div",{className:se(Zz.base,n),dangerouslySetInnerHTML:{__html:r},...i}):null}const iF="_controlBar_6shmw_1",rF="_popoverAnchor_6shmw_11",aF="_confirmationPopover_6shmw_15",oF="_confirmationPopoverAlignRight_6shmw_30",sF="_confirmationPopoverAlignCenter_6shmw_33",lF="_confirmationMessage_6shmw_53",cF="_confirmationActions_6shmw_60",uF="_confirmationButton_6shmw_65",dF="_confirmationButtonCancel_6shmw_83",hF="_confirmationButtonNeutral_6shmw_91",fF="_confirmationButtonDanger_6shmw_99",pF="_controlButton_6shmw_108",mF="_controlButtonIconOnly_6shmw_130",gF="_controlButtonDisabled_6shmw_135",vF="_controlButtonDanger_6shmw_162",bF="_controlButtonContent_6shmw_178",yF="_controlButtonIcon_6shmw_130",_F="_controlButtonLabel_6shmw_194",xF="_controlButtonChevron_6shmw_201",SF="_controlButtonNotificationDot_6shmw_210",kF="_deviceSplitButton_6shmw_222",TF="_deviceSplitButtonEnabled_6shmw_226",wF="_dualButtonContent_6shmw_307",CF="_dualButtonIcon_6shmw_317",EF="_dualButtonLabel_6shmw_326",RF="_screenShareButton_6shmw_340",AF="_screenShareButtonCompact_6shmw_351",Ge={controlBar:iF,popoverAnchor:rF,confirmationPopover:aF,confirmationPopoverAlignRight:oF,confirmationPopoverAlignCenter:sF,confirmationMessage:lF,confirmationActions:cF,confirmationButton:uF,confirmationButtonCancel:dF,confirmationButtonNeutral:hF,confirmationButtonDanger:fF,controlButton:pF,controlButtonIconOnly:mF,controlButtonDisabled:gF,controlButtonDanger:vF,controlButtonContent:bF,controlButtonIcon:yF,controlButtonLabel:_F,controlButtonChevron:xF,controlButtonNotificationDot:SF,deviceSplitButton:kF,deviceSplitButtonEnabled:TF,dualButtonContent:wF,dualButtonIcon:CF,dualButtonLabel:EF,screenShareButton:RF,screenShareButtonCompact:AF},NF="_inline_1gpyx_1",OF="_vertical_1gpyx_6",MF="_divider_1gpyx_10",DF="_dividerVertical_1gpyx_16",PF="_customDivider_1gpyx_21",Fu={inline:NF,vertical:OF,divider:MF,dividerVertical:DF,customDivider:PF},_3={none:"0px",xxs:"var(--space-xxs)",xs:"var(--space-xs)",sm:"var(--space-sm)",md:"var(--space-md)",lg:"var(--space-lg)",xl:"var(--space-xl)","2xl":"var(--space-2xl)","3xl":"var(--space-3xl)","4xl":"var(--space-4xl)","5xl":"var(--space-5xl)"};function Sr(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in _3)return _3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function LF(t,e){const{as:n,direction:i="horizontal",gap:r,align:a="center",justify:o,wrap:s=!1,divider:l,className:c,style:u,children:d,...h}=t,p=n??"div",b={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=Sr(r);y&&(b.gap=y)}const m=hi.Children.toArray(d).filter(y=>y!=null&&typeof y!="boolean"),S=y=>!l||y===0?null:l===!0||l==="line"?f.jsx("span",{"aria-hidden":"true",className:se(Fu.divider,i==="vertical"&&Fu.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:Fu.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const v=S(x);v&&g.push(v)}g.push(y)}),f.jsx(p,{ref:e,className:se(Fu.inline,i==="vertical"&&Fu.vertical,c),style:b,...h,children:g})}const Wb=hi.forwardRef(LF);Wb.displayName="Inline";function IF(){const[t,e]=w.useState(()=>typeof window>"u"?!1:window.innerWidth<768);return w.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(max-width: 767px)"),i=()=>{e(n.matches)};return i(),typeof n.addEventListener=="function"?(n.addEventListener("change",i),()=>n.removeEventListener("change",i)):(n.addListener(i),()=>n.removeListener(i))},[]),t}function Yb(t){const{icon:e,label:n,showChevron:i=!1,variant:r="default",disabled:a,className:o="",size:s="md",iconOnly:l=!1,showNotificationDot:c=!1,isOn:u,"aria-label":d,...h}=t,p=se(Ge.controlButton,a&&Ge.controlButtonDisabled,l&&Ge.controlButtonIconOnly,r==="danger"&&Ge.controlButtonDanger,o),b=Number.parseInt(Tb[s],10),m=r==="danger"?"outline":"primary",S=r==="danger"?"danger":"default",g=f.jsxs(f.Fragment,{children:[f.jsxs("span",{className:Ge.controlButtonContent,children:[e?f.jsx("span",{className:Ge.controlButtonIcon,children:hi.isValidElement(e)&&e.props.size===void 0?hi.cloneElement(e,{size:b}):e}):null,l?null:f.jsx("span",{className:Ge.controlButtonLabel,children:n}),l||!i?null:f.jsx("span",{className:Ge.controlButtonChevron,"aria-hidden":"true",children:f.jsx(wb,{size:16})})]}),c?f.jsx("span",{className:Ge.controlButtonNotificationDot,"aria-hidden":"true"}):null]});return typeof u=="boolean"?f.jsx(sp,{...h,type:"button",disabled:a,variant:m,color:S,isOn:u,"aria-label":d||n,className:p,"data-has-notification":c?"true":void 0,children:g}):f.jsx(_s,{...h,type:"button",disabled:a,variant:m,color:S,"aria-label":d||n,className:p,"data-has-notification":c?"true":void 0,children:g})}function jF(t){const{audioDevices:e,currentMicrophoneId:n,isMicrophoneEnabled:i,isScreenShareActive:r,widgetState:a,canPublishData:o,browserSupportsScreenSharing:s,screenShareButtonVariant:l="default",onMicDeviceSelect:c,onMicToggle:u,onChatToggle:d,onLeave:h,onScreenShareToggle:p,showChatNotification:b=!1,isLanguageSelectorEnabled:m=!0,languages:S=[],selectedLanguage:g=null,defaultLanguageCode:y=null,isMultilingual:x=!1,onLanguageChange:v,isChatOpen:k=a==="chat"}=t,T=S.length,C=!m||T===0,R=IF(),A=R?"xs":"sm",N=R,[O,B]=w.useState(!1),[W,L]=w.useState(!1),K=w.useRef(null),P=w.useRef(null);w.useEffect(()=>{const U=me=>{const Rt=me.composedPath();O&&K.current&&!Rt.includes(K.current)&&B(!1),W&&P.current&&!Rt.includes(P.current)&&L(!1)},fe=me=>{me.key==="Escape"&&(O&&B(!1),W&&L(!1))};if(O||W)return document.addEventListener("mousedown",U),document.addEventListener("keydown",fe),()=>{document.removeEventListener("mousedown",U),document.removeEventListener("keydown",fe)}},[O,W]),w.useEffect(()=>{r||B(!1)},[r]);const V=w.useMemo(()=>e.map(U=>({label:U.label||`Microphone ${U.deviceId.slice(0,8)}`,value:U.deviceId})),[e]),X=w.useMemo(()=>n?V.find(U=>U.value===n)??null:null,[n,V]),te=w.useCallback(U=>{U.value,c(U.value)},[c]),$={microphone:!0,screenShare:s,chat:o},z=w.useCallback(()=>{if(r){B(!0);return}p()},[r,p]),Z=w.useCallback(()=>{B(!1),p()},[p]),Q=w.useCallback(()=>{B(!1)},[]),ce=w.useCallback(()=>{L(!0)},[]),j=w.useCallback(()=>{L(!1),h()},[h]),ge=w.useCallback(()=>{L(!1)},[]);return f.jsx("div",{className:Ge.controlBar,"data-testid":"control-bar","data-controls":JSON.stringify($),"data-language-option-count":T>0?String(T):void 0,"data-default-language-code":y??void 0,children:f.jsxs(Wb,{gap:A,align:"center",justify:"center",wrap:N,children:[f.jsx(k7,{onClick:u,buttonAriaLabel:i?"Mute microphone":"Unmute microphone",options:V,value:X,onChange:te,variant:"primary",menuPlacement:"top",menuDisabled:V.length===0,menuAriaLabel:"Select microphone device",listboxAriaLabel:"Microphone devices",ariaPressed:i,className:se(Ge.deviceSplitButton,i&&Ge.deviceSplitButtonEnabled),children:f.jsxs("span",{className:Ge.dualButtonContent,children:[f.jsx("span",{className:Ge.dualButtonIcon,children:i?f.jsx(NE,{}):f.jsx(OE,{})}),f.jsx("span",{className:Ge.dualButtonLabel,children:"Microphone"})]})}),o?f.jsx(Yb,{icon:f.jsx(CE,{}),label:"Chat",onClick:d,isOn:k,"aria-label":"Toggle chat",showNotificationDot:b}):null,s?f.jsxs("div",{ref:K,className:Ge.popoverAnchor,children:[f.jsx(Yb,{icon:f.jsx(ME,{}),label:r?"Share screen off":"Share screen",className:l==="compact"?Ge.screenShareButtonCompact:Ge.screenShareButton,iconOnly:l==="compact",onClick:z,isOn:r,"aria-label":r?"Stop screen sharing":"Start screen sharing"}),O?f.jsxs("div",{className:se(Ge.confirmationPopover,Ge.confirmationPopoverAlignCenter),role:"dialog","aria-label":"Stop screen sharing confirmation","data-testid":"confirm-stop-share",children:[f.jsx("p",{className:Ge.confirmationMessage,children:"Stop screen sharing?"}),f.jsxs("div",{className:Ge.confirmationActions,children:[f.jsx("button",{type:"button",className:se(Ge.confirmationButton,Ge.confirmationButtonCancel),onClick:Q,children:"Cancel"}),f.jsx("button",{type:"button",className:se(Ge.confirmationButton,Ge.confirmationButtonNeutral),onClick:Z,children:"Stop"})]})]}):null]}):null,f.jsx(zE,{languages:S,value:g,onChange:v,defaultLanguageCode:y,variant:"control-bar",disabled:C}),f.jsxs("div",{ref:P,className:Ge.popoverAnchor,children:[f.jsx(Yb,{icon:f.jsx(AE,{}),label:"Leave",variant:"danger",onClick:ce,"aria-label":"Leave meeting"}),W?f.jsxs("div",{className:se(Ge.confirmationPopover,Ge.confirmationPopoverAlignRight),role:"dialog","aria-label":"Leave meeting confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:Ge.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:Ge.confirmationActions,children:[f.jsx("button",{type:"button",className:se(Ge.confirmationButton,Ge.confirmationButtonCancel),onClick:ge,children:"Cancel"}),f.jsx("button",{type:"button",className:se(Ge.confirmationButton,Ge.confirmationButtonDanger),onClick:j,children:"Leave"})]})]}):null]})]})})}function BF(t){return f.jsx(jF,{...t})}const UF="_controlBar_1n8jn_1",zF="_controlButton_1n8jn_12",FF="_controlButtonDisabled_1n8jn_35",qF="_controlButtonDanger_1n8jn_62",HF="_controlButtonIconOnly_1n8jn_78",VF="_screenShareButton_1n8jn_83",GF="_controlButtonContent_1n8jn_88",WF="_controlButtonIcon_1n8jn_78",YF="_controlButtonLabel_1n8jn_103",KF="_controlButtonNotificationDot_1n8jn_108",XF="_popoverAnchor_1n8jn_198",$F="_confirmationPopover_1n8jn_202",JF="_confirmationMessage_1n8jn_216",QF="_confirmationActions_1n8jn_223",ZF="_confirmationButton_1n8jn_228",eq="_confirmationButtonCancel_1n8jn_246",tq="_confirmationButtonDanger_1n8jn_254",vn={controlBar:UF,controlButton:zF,controlButtonDisabled:FF,controlButtonDanger:qF,controlButtonIconOnly:HF,screenShareButton:VF,controlButtonContent:GF,controlButtonIcon:WF,controlButtonLabel:YF,controlButtonNotificationDot:KF,popoverAnchor:XF,confirmationPopover:$F,confirmationMessage:JF,confirmationActions:QF,confirmationButton:ZF,confirmationButtonCancel:eq,confirmationButtonDanger:tq};function yp(t){const{icon:e,label:n,variant:i="default",disabled:r,className:a="",iconOnly:o=!1,showNotificationDot:s=!1,isOn:l,"aria-label":c,...u}=t,d=se(vn.controlButton,r&&vn.controlButtonDisabled,o&&vn.controlButtonIconOnly,i==="danger"&&vn.controlButtonDanger,a),h=i==="danger"?"outline":"primary",p=i==="danger"?"danger":"default",b=f.jsxs(f.Fragment,{children:[f.jsxs("span",{className:vn.controlButtonContent,children:[e?f.jsx("span",{className:vn.controlButtonIcon,children:hi.isValidElement(e)&&e.props.size===void 0?hi.cloneElement(e,{size:20}):e}):null,o?null:f.jsx("span",{className:vn.controlButtonLabel,children:n})]}),s?f.jsx("span",{className:vn.controlButtonNotificationDot,"aria-hidden":"true"}):null]});return typeof l=="boolean"?f.jsx(sp,{...u,type:"button",disabled:r,variant:h,color:p,size:"xs",isOn:l,"aria-label":c||n,className:d,"data-has-notification":s?"true":void 0,children:b}):f.jsx(_s,{...u,type:"button",disabled:r,variant:h,color:p,size:"xs","aria-label":c||n,className:d,"data-has-notification":s?"true":void 0,children:b})}function nq(t){const{isMicrophoneEnabled:e,isChatOpen:n,isScreenShareActive:i,showChatNotification:r=!1,onMicToggle:a,onChatToggle:o,onScreenShareToggle:s,onLeave:l,languages:c=[],selectedLanguage:u=null,defaultLanguageCode:d=null,isMultilingual:h=!1,onLanguageChange:p,isLanguageSelectorEnabled:b=!0,className:m,testId:S,...g}=t,y=!b||c.length===0,[x,v]=w.useState(!1),k=w.useRef(null);w.useEffect(()=>{const O=W=>{const L=W.composedPath();x&&k.current&&!L.includes(k.current)&&v(!1)},B=W=>{W.key==="Escape"&&x&&v(!1)};if(x)return document.addEventListener("mousedown",O),document.addEventListener("keydown",B),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",B)}},[x]);const T=w.useCallback(()=>{a()},[a]),C=w.useCallback(()=>{s()},[s]),R=w.useCallback(()=>{v(!0)},[]),A=w.useCallback(()=>{v(!1),l()},[l]),N=w.useCallback(()=>{v(!1)},[]);return f.jsx("div",{...g,className:se(vn.controlBar,m),"data-testid":S,children:f.jsxs(Wb,{gap:"xs",align:"center",justify:"center",wrap:!1,children:[f.jsx(yp,{icon:e?f.jsx(NE,{size:18}):f.jsx(OE,{size:18}),label:"Microphone",iconOnly:!0,isOn:e,onClick:T,"aria-label":e?"Mute microphone":"Unmute microphone"}),f.jsx(yp,{icon:f.jsx(CE,{}),label:"Chat",iconOnly:!0,isOn:n,onClick:o,"aria-label":"Toggle chat",showNotificationDot:r}),f.jsx(yp,{icon:f.jsx(ME,{}),label:"Screen share",iconOnly:!0,className:vn.screenShareButton,isOn:i,onClick:C,"aria-label":i?"Stop screen sharing":"Start screen sharing"}),f.jsx(zE,{languages:c,value:u,onChange:p,defaultLanguageCode:d,variant:"pip",disabled:y}),f.jsxs("div",{ref:k,className:vn.popoverAnchor,children:[f.jsx(yp,{icon:f.jsx(AE,{size:16}),label:"Hang up",iconOnly:!0,variant:"danger",onClick:R,"aria-label":"Hang up"}),x?f.jsxs("div",{className:vn.confirmationPopover,role:"dialog","aria-label":"Hang up confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:vn.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:vn.confirmationActions,children:[f.jsx("button",{type:"button",className:se(vn.confirmationButton,vn.confirmationButtonCancel),onClick:N,children:"Cancel"}),f.jsx("button",{type:"button",className:se(vn.confirmationButton,vn.confirmationButtonDanger),onClick:A,children:"Leave"})]})]}):null]})]})})}function iq(t){return f.jsx(nq,{...t})}const rq="_container_zht0b_1",aq="_containerGradient_zht0b_14",oq="_containerFlat_zht0b_24",sq="_halo_zht0b_28",lq="_outerRing_zht0b_38",cq="_circle_zht0b_42",uq="_image_zht0b_72",dq="_captionContainer_zht0b_88",hq="_captionRegion_zht0b_99",Ra={container:rq,containerGradient:aq,containerFlat:oq,halo:sq,outerRing:lq,circle:cq,image:uq,captionContainer:dq,captionRegion:hq},fq="_statusText_1dkze_6",pq={statusText:fq},mq={idle:null,thinking:"Thinking...",searching:"Searching..."};function gq(t){const{status:e,size:n="md"}=t,i=e?mq[e]:null,r=i!==null;return f.jsx("div",{className:pq.statusText,"data-visible":r,"data-size":n,"aria-live":"polite",children:i})}const vq="https://obi-static.s3.ap-southeast-2.amazonaws.com/images/obi-avatar.png",bq={sm:{haloSize:"4.5rem",maxBorderWidth:5,outerRingScalePower:.55,glowSize:"20px"},md:{haloSize:"8rem",maxBorderWidth:8,outerRingScalePower:.7,glowSize:"35px"},lg:{haloSize:"10rem",maxBorderWidth:10,outerRingScalePower:.75,glowSize:"42px"}};function x3(t){const{audioPower:e,size:n="md",background:i="gradient",imageSrc:r=vq,accentColor:a,ariaLabel:o="Avatar placeholder",status:s,captionsText:l,className:c,style:u,...d}=t,h=bq[n],p=Math.min(1,Math.max(0,e)),b=p>.01,m=b?Math.min(1,p/.5):0,S=b?Math.max(1,m*h.maxBorderWidth):0,g=1.02,y=b?g+p*h.outerRingScalePower:g,x=b?.2+p*.35:0,v={...u??{},...a?{"--avatar-fallback-accent":a}:{}},k={"--avatar-fallback-halo-size":h.haloSize,"--avatar-fallback-border-width":`${S}px`,"--avatar-fallback-secondary-border-scale":y.toString(),"--avatar-fallback-secondary-border-opacity":x.toString(),"--avatar-fallback-glow-size":h.glowSize},T=l!=null&&l!=="";return f.jsxs("div",{...d,className:se(Ra.container,i==="gradient"?Ra.containerGradient:Ra.containerFlat,c),style:v,"data-testid":"avatar-fallback","aria-label":o,role:"img",children:[f.jsxs("div",{className:Ra.halo,style:k,children:[f.jsx("div",{className:Ra.outerRing,"aria-hidden":"true"}),f.jsx("div",{className:Ra.circle,children:f.jsx("img",{className:Ra.image,src:r,alt:"","aria-hidden":"true"})}),f.jsx(gq,{status:s,size:n})]}),T&&f.jsx("div",{className:Ra.captionContainer,children:f.jsx("div",{className:Ra.captionRegion,"data-size":n,role:"status","aria-live":"polite","aria-atomic":"true",children:l})})]})}const yq="_container_1k3qg_11",_q="_screenshot_1k3qg_20",xq="_flash_1k3qg_30",Kb={container:yq,screenshot:_q,flash:xq};function Sq(t){const{isActive:e,imageUrl:n,onComplete:i,duration:r=2e3}=t,[a,o]=w.useState(!1),s=w.useRef(null),l=w.useRef(i);return w.useEffect(()=>{l.current=i},[i]),w.useEffect(()=>{if(!e){o(!1),s.current&&(clearTimeout(s.current),s.current=null);return}if(!s.current)return o(!0),s.current=setTimeout(()=>{var c;o(!1),s.current=null,(c=l.current)==null||c.call(l)},r),()=>{s.current&&(clearTimeout(s.current),s.current=null)}},[e,r]),a?f.jsxs("div",{className:Kb.container,"aria-live":"polite","aria-label":"Screenshot captured",children:[n&&f.jsx("img",{src:n,alt:"Captured screenshot",className:Kb.screenshot}),f.jsx("div",{className:Kb.flash})]}):null}const kq="_container_13ukq_1",Tq="_dragging_13ukq_5",wq="_placeholder_13ukq_9",Cq="_handleButton_13ukq_15",Eq="_customHandle_13ukq_105",ql={container:kq,dragging:Tq,placeholder:wq,handleButton:Cq,"handle-top":"_handle-top_13ukq_65","handle-bottom":"_handle-bottom_13ukq_75","handle-left":"_handle-left_13ukq_85","handle-right":"_handle-right_13ukq_95",customHandle:Eq};function Rq(t){const{disabled:e,lingerMs:n,isDragging:i}=t,[r,a]=w.useState(!1),o=w.useRef(null),s=w.useCallback(()=>{o.current!==null&&(window.clearTimeout(o.current),o.current=null)},[]),l=w.useCallback(()=>{e||(s(),a(!0))},[s,e]),c=w.useCallback(()=>{e||i||(s(),o.current=window.setTimeout(()=>{a(!1),o.current=null},n))},[s,e,i,n]);return w.useEffect(()=>{i&&l()},[i,l]),w.useEffect(()=>s,[s]),{isHandleVisible:r,showHandle:l,scheduleHideHandle:c}}function Aq(t){const{initialPosition:e,preserveSpace:n,onPositionChange:i}=t,r=w.useRef(null),[a,o]=w.useState(!!e),[s,l]=w.useState(!1),[c,u]=w.useState(null),[d,h]=w.useState(()=>e??{x:0,y:0}),p=w.useRef(d);s||(p.current=d);const b=w.useRef(null),m=w.useRef(!1),S=w.useRef(!1);w.useEffect(()=>{e&&(S.current||(o(!0),h(e),p.current=e))},[e==null?void 0:e.x,e==null?void 0:e.y]),w.useEffect(()=>{if(e||m.current)return;const v=r.current;if(!v)return;const k=v.getBoundingClientRect(),T={x:k.left,y:k.top};m.current=!0,o(!0),h(T),p.current=T,u(n?{width:k.width,height:k.height}:null)},[e,n]);const g=w.useCallback(v=>{const k=b.current;if(!(!k||v.pointerId!==k.pointerId)){b.current=null,S.current=!0,h(p.current),l(!1);try{v.currentTarget.releasePointerCapture(k.pointerId)}catch{}}},[]),y=w.useCallback(v=>{v.button===0&&(v.preventDefault(),v.currentTarget.setPointerCapture(v.pointerId),b.current={pointerId:v.pointerId,startClientX:v.clientX,startClientY:v.clientY,startX:p.current.x,startY:p.current.y},l(!0))},[]),x=w.useCallback(v=>{const k=b.current;if(!k||v.pointerId!==k.pointerId)return;const T={x:k.startX+(v.clientX-k.startClientX),y:k.startY+(v.clientY-k.startClientY)};p.current=T,r.current&&(r.current.style.transform=`translate3d(${T.x}px, ${T.y}px, 0)`),i==null||i(T)},[i]);return{containerRef:r,isFixed:a,isDragging:s,position:d,placeholderSize:c,onPointerDown:y,onPointerMove:x,endDrag:g}}function Nq(t){const{children:e,className:n,handle:i="top",initialPosition:r,disabled:a=!1,preserveSpace:o=!0,zIndex:s=1e3,onPositionChange:l,handleAriaLabel:c="Drag",handleLingerMs:u=350,style:d,...h}=t,{containerRef:p,isFixed:b,isDragging:m,position:S,placeholderSize:g,onPointerDown:y,onPointerMove:x,endDrag:v}=Aq({initialPosition:r,preserveSpace:o,onPositionChange:l}),{isHandleVisible:k,showHandle:T,scheduleHideHandle:C}=Rq({disabled:a,lingerMs:u,isDragging:m}),R=typeof e=="function",A=w.useMemo(()=>{const O=B=>f.jsx("div",{className:se(ql.customHandle,B.className),onPointerDown:y,onPointerMove:x,onPointerUp:v,onPointerCancel:v,children:B.children});return O.displayName="Draggable.Handle",O},[y,x,v]),N={...d,position:b?"fixed":"relative",top:b?0:d==null?void 0:d.top,left:b?0:d==null?void 0:d.left,transform:b?`translate3d(${S.x}px, ${S.y}px, 0)`:d==null?void 0:d.transform,zIndex:b?s:d==null?void 0:d.zIndex};return f.jsxs(f.Fragment,{children:[o&&b&&g?f.jsx("div",{className:ql.placeholder,style:{width:g.width,height:g.height}}):null,f.jsxs("div",{ref:p,className:se(ql.container,m?ql.dragging:null,n),"data-handle-visible":R?void 0:a?"false":k||m?"true":"false",style:N,onMouseEnter:R?void 0:T,onMouseLeave:R?void 0:C,...h,children:[!R&&!a?f.jsx("button",{type:"button",className:se(ql.handleButton,ql[`handle-${i}`]),"aria-label":c,onMouseEnter:T,onMouseLeave:C,onPointerDown:O=>{T(),y(O)},onPointerMove:x,onPointerUp:v,onPointerCancel:v}):null,R?e({Handle:A}):e]})]})}const Oq="_container_gzwdo_1",Mq="_captionRegion_gzwdo_14",Dq="_status_gzwdo_22",Pq="_captionText_gzwdo_29",_p={container:Oq,captionRegion:Mq,status:Dq,captionText:Pq},Lq={idle:null,thinking:"Thinking...",searching:"Searching..."};function Iq(t){const{text:e,status:n,className:i,...r}=t,a=n?Lq[n]:null;return f.jsx("div",{...r,className:se(_p.container,i),"data-testid":"pip-captions-panel",children:f.jsxs("div",{className:_p.captionRegion,role:"status","aria-live":"polite","aria-atomic":"true",children:[a?f.jsx("div",{className:_p.status,children:a}):null,f.jsx("div",{className:_p.captionText,children:e})]})})}const jq="_panel_1laxg_1",Bq="_row_1laxg_22",Uq="_stepContent_1laxg_29",zq="_stepLabel_1laxg_37",Fq="_currentStep_1laxg_44",qq="_nextStep_1laxg_51",Hq="_skipButtonContainer_1laxg_65",Vq="_circleButton_1laxg_73",Gq="_arrowPlaceholder_1laxg_100",Wq="_skipButton_1laxg_65",nr={panel:jq,row:Bq,stepContent:Uq,stepLabel:zq,currentStep:Fq,nextStep:qq,skipButtonContainer:Hq,circleButton:Vq,arrowPlaceholder:Gq,skipButton:Wq},Yq="_truncatedText_1u580_1",Kq={truncatedText:Yq};function S3(t){const{children:e,maxLines:n=2,className:i,"data-testid":r}=t;return f.jsx("div",{className:`${Kq.truncatedText} ${i||""}`,style:{WebkitLineClamp:n},"data-testid":r,children:e})}function Xq(t,e,n){var c;const i=t.length,r=n&&i>0&&((c=t[i-1])==null?void 0:c.title)==="Conclusion",a=r?t.slice(0,-1):t.slice(),o=a.length;if(o===0)return{visibleSteps:a,currentIndex:null};const s=typeof e=="number"&&Number.isFinite(e)?e:1;if(r&&s===i)return{visibleSteps:a,currentIndex:null};const l=Math.min(Math.max(s,1),o)-1;return{visibleSteps:a,currentIndex:l}}function Xb(t,e){return e<=0||typeof t!="number"||!Number.isFinite(t)?0:Math.min(Math.max(Math.trunc(t),1),e)-1}function $q(t){var C;const{steps:e,currentStep:n,onStepClick:i,hideTrailingConclusionStep:r=!0,className:a,testId:o,...s}=t,{visibleSteps:l,currentIndex:c}=w.useMemo(()=>Xq(e,n,r),[n,r,e]),[u,d]=w.useState(()=>Xb(n,l.length)),h=w.useRef(!1);w.useEffect(()=>{if(!h.current)d(Xb(n,l.length));else{const R=Xb(n,l.length);u===R&&(h.current=!1)}},[n,l,u]);const p=l.length,b=l[u],m=u>0,S=u<p-1,g=S?(C=l[u+1])==null?void 0:C.title:void 0,y=p===0?0:u+1,x=c!==null&&b&&u!==c,v=()=>{m&&(h.current=!0,d(R=>Math.max(R-1,0)))},k=()=>{S&&(h.current=!0,d(R=>Math.min(R+1,p-1)))},T=()=>{!x||!b||!i||(h.current=!1,i(u,b))};return f.jsxs("div",{...s,className:se(nr.panel,a),"data-testid":o,role:"group","aria-label":"Course progress",children:[f.jsxs("div",{className:nr.row,children:[m?f.jsx("button",{type:"button",className:nr.circleButton,"aria-label":"Previous step",onClick:v,children:f.jsx(EE,{size:14})}):f.jsx("span",{className:nr.arrowPlaceholder,"aria-hidden":"true"}),f.jsxs("div",{className:nr.stepContent,children:[f.jsxs(xi,{className:nr.stepLabel,"aria-live":"polite",children:["Step ",y,"/",p]}),f.jsx(S3,{maxLines:2,children:f.jsx(xi,{className:nr.currentStep,"data-testid":"pip-outline-current-step",children:(b==null?void 0:b.title)??"No steps available"})}),g?f.jsx(S3,{maxLines:2,children:f.jsxs(xi,{variant:"muted",className:nr.nextStep,children:["Next: ",g]})}):null]}),S?f.jsx("button",{type:"button",className:nr.circleButton,"aria-label":"Next step",onClick:k,children:f.jsx(VB,{size:14})}):f.jsx("span",{className:nr.arrowPlaceholder,"aria-hidden":"true"})]}),x?f.jsx("div",{className:nr.skipButtonContainer,children:f.jsx("button",{type:"button",className:nr.skipButton,"aria-label":"Skip to this step",onClick:T,children:f.jsx(XB,{size:14})})}):null]})}const Jq="_window_zm5au_1",Qq="_exitButton_zm5au_14",Zq="_content_zm5au_47",eH="_contentTopOverlay_zm5au_58",tH="_dragHandle_zm5au_68",nH="_contentBottomOverlay_zm5au_78",iH="_controls_zm5au_87",rH="_messagesPanelWrapper_zm5au_95",Eo={window:Jq,exitButton:Qq,content:Zq,contentTopOverlay:eH,dragHandle:tH,contentBottomOverlay:nH,controls:iH,messagesPanelWrapper:rH};function aH(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function oH(t){const{onExit:e,controlBarProps:n,isCourseOutlineSelected:i,onCourseOutlineToggle:r,isCaptionsEnabled:a=!1,onCaptionsToggle:o,courseOutline:s,messagesPanel:l,avatarFallbackProps:c,contentTopOverlaySlot:u,screenshotUrl:d,cameraShotTrigger:h,className:p,testId:b,...m}=t,S=i,g=n.isChatOpen&&!S&&l,y=c==null?void 0:c.captionsText,x=a&&aH(y),[v,k]=w.useState(!1),T=w.useRef(h),C=w.useCallback(()=>{k(!1)},[]);w.useEffect(()=>{h&&h>0&&h!==T.current&&k(!0),T.current=h},[h]);const R=w.useCallback(()=>f.jsx(x3,{audioPower:(c==null?void 0:c.audioPower)??0,size:"sm",background:"flat",imageSrc:c==null?void 0:c.imageSrc,ariaLabel:c==null?void 0:c.ariaLabel,status:c==null?void 0:c.status}),[c]),A=S?s?f.jsx($q,{steps:s.steps,currentStep:s.currentStep,onStepClick:s.onStepClick,hideTrailingConclusionStep:s.hideTrailingConclusionStep}):R():g?f.jsx("div",{className:Eo.messagesPanelWrapper,children:l}):x?f.jsx(Iq,{text:y}):R();return f.jsxs("div",{...m,className:se(Eo.window,p),"data-testid":b,role:"group","aria-label":"Picture-in-Picture",children:[f.jsxs("div",{className:Eo.content,children:[f.jsx("div",{className:Eo.contentTopOverlay,children:u}),f.jsx("button",{type:"button",className:Eo.exitButton,onClick:e,"aria-label":"Exit PiP",children:f.jsx(WB,{size:14})}),A,!g&&f.jsxs("div",{className:Eo.contentBottomOverlay,children:[f.jsx(sp,{isOn:i,onClick:r,variant:"primary",size:"xs","aria-label":"Toggle course outline",children:f.jsx($B,{size:18})}),f.jsx(sp,{isOn:a,onClick:o,variant:"primary",size:"xs","aria-label":"Toggle captions",children:f.jsx(HB,{size:18})})]}),f.jsx(Sq,{isActive:v,imageUrl:d??null,onComplete:C})]}),f.jsx("div",{className:Eo.controls,children:f.jsx(iq,{...n})})]})}function sH(t){const{initialPosition:e,onPositionChange:n,zIndex:i=1e3,...r}=t;return f.jsx(Nq,{initialPosition:e,onPositionChange:n,zIndex:i,preserveSpace:!1,children:({Handle:a})=>f.jsx(oH,{...r,contentTopOverlaySlot:f.jsx(a,{className:Eo.dragHandle})})})}const lH="_root_ygi3o_1",cH="_overlay_ygi3o_7",uH="_caption_ygi3o_17",$b={root:lH,overlay:cH,caption:uH};function dH(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function hH(t){const{children:e,className:n,text:i}=t,r=dH(i);return f.jsxs("div",{className:se($b.root,n),children:[e,r?f.jsx("div",{className:$b.overlay,role:"status","aria-live":"polite","aria-atomic":"true",children:f.jsx("div",{className:$b.caption,children:i})}):null]})}const fH="_box_dc9yv_1",pH={box:fH},k3={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},T3={surface:"var(--color-surface)",surfaceMuted:"var(--color-surface-muted)",surfaceAlt:"var(--color-surface-alt)",primarySoft:"var(--color-primary-soft)",primarySofter:"var(--color-primary-softer)",dangerSurface:"var(--color-danger-surface)"};function mH(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in k3)return k3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function gH(t){if(t!==void 0){if(t in T3)return T3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function vH(t,e){const{as:n,className:i,padding:r,paddingX:a,paddingY:o,paddingTop:s,paddingBottom:l,paddingLeft:c,paddingRight:u,paddingSm:d,paddingMd:h,paddingLg:p,paddingXl:b,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:v,marginRight:k,radius:T,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:B,radiusBottomLeft:W,radiusBottomRight:L,background:K,gap:P,style:V,...X}=t,te=n??"div",$={...V},z=$,Z={},Q=(U,fe)=>{if(fe===void 0)return;const me=Sr(fe);me&&($[U]=me)},ce=(U,fe)=>{if(fe===void 0)return;const me=Sr(fe);me&&($[U]=me)},j=(U,fe)=>{if(fe===void 0)return;const me=mH(fe);me&&($[U]=me)},ge={sm:d,md:h,lg:p,xl:b};if(r!==void 0){const U=Sr(r);U&&(z["--box-padding"]=U)}for(const[U,fe]of Object.entries(ge)){if(fe===void 0)continue;const me=Sr(fe);me&&(z[`--box-padding-${U}`]=me,Z[`data-padding-${U}`]="")}if(a!==void 0){const U=Sr(a);U&&($.paddingLeft=U,$.paddingRight=U)}if(o!==void 0){const U=Sr(o);U&&($.paddingTop=U,$.paddingBottom=U)}if(Q("paddingTop",s),Q("paddingBottom",l),Q("paddingLeft",c),Q("paddingRight",u),m!==void 0){const U=Sr(m);U&&($.margin=U)}if(S!==void 0){const U=Sr(S);U&&($.marginLeft=U,$.marginRight=U)}if(g!==void 0){const U=Sr(g);U&&($.marginTop=U,$.marginBottom=U)}if(ce("marginTop",y),ce("marginBottom",x),ce("marginLeft",v),ce("marginRight",k),P!==void 0){const U=Sr(P);U&&($.gap=U)}if(j("borderRadius",T),C!==void 0&&(j("borderTopLeftRadius",C),j("borderTopRightRadius",C)),R!==void 0&&(j("borderBottomLeftRadius",R),j("borderBottomRightRadius",R)),A!==void 0&&(j("borderTopLeftRadius",A),j("borderBottomLeftRadius",A)),N!==void 0&&(j("borderTopRightRadius",N),j("borderBottomRightRadius",N)),j("borderTopLeftRadius",O),j("borderTopRightRadius",B),j("borderBottomLeftRadius",W),j("borderBottomRightRadius",L),K!==void 0){const U=gH(K);U&&($.background=U)}return f.jsx(te,{ref:e,className:se(pH.box,i),style:$,...Z,...X})}const xp=hi.forwardRef(vH);xp.displayName="Box";const bH="_panel_eawk4_1",yH="_selected_eawk4_10",w3={panel:bH,selected:yH};function qu(t){const{children:e,className:n,selected:i,...r}=t;return f.jsx("div",{className:se(w3.panel,i?w3.selected:null,n),...r,children:e})}const _H="_root_yccm8_1",xH="_header_yccm8_8",SH="_icon_yccm8_15",kH="_text_yccm8_26",TH="_heading_yccm8_33",wH="_description_yccm8_41",CH="_body_yccm8_47",EH="_footer_yccm8_54",Ro={root:_H,header:xH,icon:SH,text:kH,heading:TH,description:wH,body:CH,footer:EH};function C3(t){const{className:e,...n}=t;return f.jsx("div",{className:se(Ro.icon,e),...n})}function E3(t){const{className:e,...n}=t;return f.jsx("h3",{className:se(Ro.heading,e),...n})}function R3(t){const{className:e,...n}=t;return f.jsx("p",{className:se(Ro.description,e),...n})}function A3(t){const{className:e,...n}=t;return f.jsx("div",{className:se(Ro.footer,e),...n})}function RH(t){const e=w.Children.toArray(t),n=[];let i,r,a,o;for(const s of e){if(w.isValidElement(s)&&s.type===C3&&i===void 0){i=s;continue}if(w.isValidElement(s)&&s.type===E3&&r===void 0){r=s;continue}if(w.isValidElement(s)&&s.type===R3&&a===void 0){a=s;continue}if(w.isValidElement(s)&&s.type===A3&&o===void 0){o=s;continue}n.push(s)}return{icon:i,heading:r,description:a,footer:o,body:n}}function AH(t){const{children:e,className:n,...i}=t,r=RH(e),a=r.icon||r.heading||r.description;return f.jsxs(qu,{className:se(Ro.root,n),...i,children:[a?f.jsxs("div",{className:Ro.header,children:[r.icon,r.heading||r.description?f.jsxs("div",{className:Ro.text,children:[r.heading,r.description]}):null]}):null,r.body.length?f.jsx("div",{className:Ro.body,children:r.body}):null,r.footer]})}const Jb=Object.assign(AH,{Icon:C3,Heading:E3,Description:R3,Footer:A3}),NH="_panel_f4a69_1",OH="_header_f4a69_10",MH="_title_f4a69_19",DH="_scrollArea_f4a69_29",PH="_scrollable_f4a69_34",LH="_list_f4a69_39",IH="_courseButton_f4a69_45",jH="_courseCard_f4a69_61",BH="_loading_f4a69_65",UH="_spinnerWrapper_f4a69_69",zH="_spinner_f4a69_69",FH="_contentHidden_f4a69_92",qH="_courseHeading_f4a69_101",HH="_courseDescription_f4a69_107",VH="_empty_f4a69_116",Ln={panel:NH,header:OH,title:MH,scrollArea:DH,scrollable:PH,list:LH,courseButton:IH,courseCard:jH,loading:BH,spinnerWrapper:UH,spinner:zH,contentHidden:FH,courseHeading:qH,courseDescription:HH,empty:VH};function GH(t){const{selectionMode:e,selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r}=t,a=n!==void 0,[o,s]=w.useState(()=>i??[]),l=a?n:o,c=w.useCallback(d=>{a||s(d),r==null||r(d)},[a,r]),u=w.useCallback(d=>{const h=l.includes(d);if(e==="single"){c(h?[]:[d]);return}if(h){c(l.filter(p=>p!==d));return}c([...l,d])},[l,e,c]);return{selectedCourseIds:l,toggleCourseId:u}}function WH(t){const{title:e="Courses",ariaLabel:n,className:i,courses:r,selectionMode:a="multiple",selectedCourseIds:o,onCourseToggle:s,loadingCourseId:l,emptyMessage:c="No courses available",testId:u,...d}=t;return f.jsxs(qu,{...d,className:se(Ln.panel,i),role:"region","aria-label":n??e,"data-testid":u,children:[f.jsx("div",{className:Ln.header,children:f.jsx(xi,{as:"h2",className:Ln.title,children:e})}),f.jsx("div",{className:Ln.scrollArea,children:f.jsx(zl,{className:Ln.scrollable,children:r.length===0?f.jsx(xi,{variant:"muted",className:Ln.empty,"data-testid":"course-panel-empty",children:c}):f.jsx("div",{className:Ln.list,"data-testid":"course-panel-list",children:r.map(h=>{const p=o.includes(h.id),b=l!=null&&h.id===l,m=h.disabled===!0||l!=null,S=se(Ln.courseButton,b&&Ln.loading);return f.jsxs("button",{type:"button",className:S,"aria-pressed":p,"aria-disabled":m,"aria-busy":b||void 0,disabled:m,onClick:()=>s==null?void 0:s(h.id,h),"data-testid":`course-panel-item-${h.id}`,children:[b?f.jsx("span",{className:Ln.spinnerWrapper,"aria-hidden":"true","data-testid":`course-panel-item-spinner-${h.id}`,children:f.jsx("span",{className:Ln.spinner})}):null,f.jsxs(Jb,{selected:p,className:Ln.courseCard,children:[f.jsx(Jb.Heading,{className:se(Ln.courseHeading,b&&Ln.contentHidden),children:h.title}),h.description?f.jsx(Jb.Description,{className:se(Ln.courseDescription,b&&Ln.contentHidden),children:h.description}):null]})]},h.id)})})})})]})}function YH(t){const{selectionMode:e="multiple",selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r,onCourseToggle:a,...o}=t,{selectedCourseIds:s,toggleCourseId:l}=GH({selectionMode:e,selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r}),c=w.useCallback((u,d)=>{l(u),a==null||a(u,d)},[a,l]);return f.jsx(WH,{...o,selectionMode:e,selectedCourseIds:s,onCourseToggle:c})}const KH="_panel_1je0q_1",XH="_header_1je0q_10",$H="_headerActions_1je0q_19",JH="_popoverAnchor_1je0q_27",QH="_backButton_1je0q_31",ZH="_divider_1je0q_38",eV="_title_1je0q_44",tV="_scrollArea_1je0q_54",nV="_scrollable_1je0q_59",iV="_list_1je0q_64",rV="_section_1je0q_70",aV="_sectionHeader_1je0q_76",oV="_sectionTitle_1je0q_80",sV="_sectionTitleCompact_1je0q_88",lV="_item_1je0q_92",cV="_itemClickable_1je0q_106",uV="_itemCompleted_1je0q_110",dV="_itemCurrent_1je0q_114",hV="_itemFuture_1je0q_118",fV="_itemDisabled_1je0q_123",pV="_row_1je0q_137",mV="_stepHeader_1je0q_144",gV="_stepNumber_1je0q_153",vV="_stepTitle_1je0q_159",bV="_checkIcon_1je0q_171",yV="_empty_1je0q_175",_V="_confirmationPopover_1je0q_180",xV="_confirmationMessage_1je0q_204",SV="_confirmationActions_1je0q_211",kV="_confirmationButton_1je0q_216",TV="_confirmationButtonCancel_1je0q_234",wV="_confirmationButtonNeutral_1je0q_242",Re={panel:KH,header:XH,headerActions:$H,popoverAnchor:JH,backButton:QH,divider:ZH,title:eV,scrollArea:tV,scrollable:nV,list:iV,section:rV,sectionHeader:aV,sectionTitle:oV,sectionTitleCompact:sV,item:lV,itemClickable:cV,itemCompleted:uV,itemCurrent:dV,itemFuture:hV,itemDisabled:fV,row:pV,stepHeader:mV,stepNumber:gV,stepTitle:vV,checkIcon:bV,empty:yV,confirmationPopover:_V,confirmationMessage:xV,confirmationActions:SV,confirmationButton:kV,confirmationButtonCancel:TV,confirmationButtonNeutral:wV};function CV(t){var p;const{steps:e,currentStep:n,hideTrailingConclusionStep:i}=t,r=e.length,a=i&&r>0&&((p=e[r-1])==null?void 0:p.title)==="Conclusion",o=a?e.slice(0,-1):e.slice(),s=o.length,l=typeof n=="number"&&isFinite(n)?n:1;if(s===0)return{visibleSteps:o,completedIndices:[],currentIndex:null,futureIndices:[]};if(a&&l===r)return{visibleSteps:o,completedIndices:Array.from({length:s},(b,m)=>m),currentIndex:null,futureIndices:[]};const c=Math.min(Math.max(l,1),s)-1,u=Array.from({length:Math.max(0,c)},(b,m)=>m),d=Math.min(c,s-1),h=Array.from({length:Math.max(0,s-(d+1))},(b,m)=>d+1+m);return{visibleSteps:o,completedIndices:u,currentIndex:d,futureIndices:h}}function EV(t){const{title:e="Course Outline",ariaLabel:n,className:i,steps:r,currentStep:a,onStepClick:o,hideTrailingConclusionStep:s=!0,emptyMessage:l="No steps available",density:c="default",testId:u,onBackToCoursesConfirm:d,backToCoursesDisabled:h=!1,backToCoursesLabel:p="Back to courses",backToCoursesConfirmMessage:b="Going back will end this course. You can start another course from the list.",backToCoursesConfirmLabel:m="Back",backToCoursesCancelLabel:S="Cancel",showBackToCourses:g=!0,...y}=t,[x,v]=w.useState(!1),k=w.useRef(null),T=h||!d,C=w.useCallback(V=>(V+1).toString().padStart(2,"0"),[]),{visibleSteps:R,completedIndices:A,currentIndex:N,futureIndices:O}=w.useMemo(()=>CV({steps:r,currentStep:a,hideTrailingConclusionStep:s}),[a,s,r]),B=c==="compact"?"md":"lg",W=w.useCallback(()=>{T||v(V=>!V)},[T]),L=w.useCallback(()=>{v(!1)},[]),K=w.useCallback(()=>{v(!1),d&&d()},[d]);w.useEffect(()=>{if(!x)return;const V=te=>{const $=te.composedPath();k.current&&!$.includes(k.current)&&v(!1)},X=te=>{te.key==="Escape"&&v(!1)};return document.addEventListener("mousedown",V),document.addEventListener("keydown",X),()=>{document.removeEventListener("mousedown",V),document.removeEventListener("keydown",X)}},[x]),w.useEffect(()=>{T&&x&&v(!1)},[T,x]);const P=w.useCallback((V,X)=>{const te=R[V];if(!te)return null;const $=typeof o=="function",z=$&&te.disabled===!0,Z=$&&!z,Q=se(Re.item,{[Re.itemClickable]:Z,[Re.itemCompleted]:X==="completed",[Re.itemCurrent]:X==="current",[Re.itemFuture]:X==="future",[Re.itemDisabled]:z}),ce=f.jsxs("div",{className:Re.row,children:[f.jsxs("div",{className:Re.stepHeader,children:[f.jsx("span",{className:Re.stepNumber,children:C(V)}),f.jsx("span",{className:Re.stepTitle,children:te.title})]}),X==="completed"?f.jsx(ap,{size:20,className:Re.checkIcon}):null]});return $?f.jsx(xp,{as:"button",type:"button",className:Q,onClick:()=>{Z&&o(V,te)},disabled:z,"aria-current":X==="current"?"step":void 0,"aria-label":`Step ${C(V)}: ${te.title}`,"data-testid":`course-outline-item-${te.id}`,padding:B,radius:"panel",gap:"sm",children:ce},te.id):f.jsx(xp,{className:Q,"aria-current":X==="current"?"step":void 0,"aria-label":`Step ${C(V)}: ${te.title}`,"data-testid":`course-outline-item-${te.id}`,padding:B,radius:"panel",gap:"sm",children:ce},te.id)},[C,B,o,R]);return f.jsxs(qu,{...y,className:se(Re.panel,i),role:"region","aria-label":n??e,"data-testid":u,children:[f.jsxs("div",{className:Re.header,children:[f.jsx(xi,{as:"h2",className:Re.title,children:e}),g?f.jsx("div",{className:Re.headerActions,children:f.jsxs("div",{ref:k,className:Re.popoverAnchor,children:[f.jsxs(_s,{type:"button",variant:"secondary",color:"default",size:"sm",className:Re.backButton,onClick:W,disabled:T,"aria-label":p,"data-testid":"course-outline-back-button",children:[f.jsx(EE,{size:16,"aria-hidden":"true"}),f.jsx("span",{children:p})]}),x?f.jsxs("div",{className:Re.confirmationPopover,role:"dialog","aria-label":"Back to courses confirmation","data-testid":"course-outline-back-confirm",children:[f.jsx("p",{className:Re.confirmationMessage,children:b}),f.jsxs("div",{className:Re.confirmationActions,children:[f.jsx("button",{type:"button",className:se(Re.confirmationButton,Re.confirmationButtonCancel),onClick:L,"data-testid":"course-outline-back-cancel",children:S}),f.jsx("button",{type:"button",className:se(Re.confirmationButton,Re.confirmationButtonNeutral),onClick:K,"data-testid":"course-outline-back-confirm-action",children:m})]})]}):null]})}):null]}),f.jsx("div",{className:Re.divider,"aria-hidden":"true"}),f.jsx("div",{className:Re.scrollArea,children:f.jsx(zl,{className:Re.scrollable,children:R.length===0?f.jsx(xi,{variant:"muted",className:Re.empty,"data-testid":"course-outline-empty",children:l}):f.jsxs("div",{className:Re.list,"data-testid":"course-outline-list",children:[A.length>0?f.jsxs("div",{className:Re.section,"data-testid":"course-outline-section-completed",children:[f.jsx("div",{className:Re.sectionHeader,children:f.jsx("span",{className:se(Re.sectionTitle,c==="compact"?Re.sectionTitleCompact:null),children:"Completed"})}),A.map(V=>P(V,"completed"))]}):null,N!==null?f.jsxs("div",{className:Re.section,"data-testid":"course-outline-section-current",children:[f.jsx("div",{className:Re.sectionHeader,children:f.jsx("span",{className:se(Re.sectionTitle,c==="compact"?Re.sectionTitleCompact:null),children:"Current"})}),P(N,"current")]}):null,O.length>0?f.jsxs("div",{className:Re.section,"data-testid":"course-outline-section-upcoming",children:[f.jsx("div",{className:Re.sectionHeader,children:f.jsx("span",{className:se(Re.sectionTitle,c==="compact"?Re.sectionTitleCompact:null),children:"Upcoming"})}),O.map(V=>P(V,"future"))]}):null]})})})]})}function RV(t){return f.jsx(EV,{...t})}const AV="_panel_h7cuf_1",NV="_messagesArea_h7cuf_20",OV="_messagesList_h7cuf_46",MV="_messageItem_h7cuf_53",DV="_messageMetadata_h7cuf_59",PV="_senderName_h7cuf_67",LV="_timestamp_h7cuf_71",IV="_messageBubble_h7cuf_75",jV="_agentMessage_h7cuf_85",BV="_agentActions_h7cuf_89",UV="_copyButton_h7cuf_95",zV="_copyButtonCopied_h7cuf_129",FV="_empty_h7cuf_133",qV="_composer_h7cuf_140",HV="_composerDisabled_h7cuf_160",VV="_composerInput_h7cuf_165",GV="_sendButton_h7cuf_180",Mn={panel:AV,messagesArea:NV,messagesList:OV,messageItem:MV,messageMetadata:DV,senderName:PV,timestamp:LV,messageBubble:IV,agentMessage:jV,agentActions:BV,copyButton:UV,copyButtonCopied:zV,empty:FV,composer:qV,composerDisabled:HV,composerInput:VV,sendButton:GV};function WV(t){const e=new Date(t),n=e.getHours(),i=e.getMinutes(),r=n>=12?"PM":"AM",a=n%12||12,o=i.toString().padStart(2,"0");return`${a}:${o}${r}`}function YV(t,e){var i,r;if(typeof t.isAgent=="boolean")return t.isAgent;const n=((i=t.from)==null?void 0:i.identity)??void 0;return n&&e&&n===e?!1:((r=t.attributes)==null?void 0:r.source)==="agent-rpc"?!0:n?n==="agent-avatar"||n.startsWith("agent-"):!1}function KV(t,e){var i,r,a;const n=(i=t.from)==null?void 0:i.identity;return n&&e&&n===e?"You":((r=t.from)==null?void 0:r.name)??((a=t.attributes)==null?void 0:a.senderName)??n??"Unknown"}async function XV(t){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText)){await navigator.clipboard.writeText(t);return}if(typeof document>"u")throw new Error("Clipboard unavailable");const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-9999px",e.style.top="0",e.setAttribute("readonly","true"),document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}function $V(t){const{messages:e,localIdentity:n,onSend:i,isSending:r=!1,inputPlaceholder:a="Type a message...",className:o,testId:s,...l}=t,[c,u]=w.useState(""),[d,h]=w.useState(null),p=w.useRef(null),b=w.useRef(null),m=w.useMemo(()=>{const v=e[e.length-1];return v?v.id??`${v.timestamp}-${e.length-1}`:null},[e]);w.useEffect(()=>{var v,k;(k=(v=p.current)==null?void 0:v.scrollIntoView)==null||k.call(v,{behavior:"smooth"})},[m]),w.useEffect(()=>()=>{b.current&&(window.clearTimeout(b.current),b.current=null)},[]);const S=w.useCallback(async()=>{const v=c.trim();v.length!==0&&(await i(v),u(""))},[c,i]),g=w.useCallback(v=>{v.key==="Enter"&&(v.preventDefault(),S())},[S]),y=w.useCallback(async(v,k)=>{try{await XV(v.message??""),h(k),b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{h(null),b.current=null},2e3)}catch(T){console.warn("[PiPChatPanel] Failed to copy message",T)}},[]),x=c.trim().length>0&&!r;return f.jsxs("div",{...l,className:se(Mn.panel,o),"data-testid":s,role:"region","aria-label":"Chat",children:[f.jsx("div",{className:Mn.messagesArea,children:e.length===0?f.jsx("div",{className:Mn.empty,"data-testid":"pip-chat-panel-empty",children:"No messages yet"}):f.jsxs("div",{className:Mn.messagesList,"data-testid":"pip-chat-panel-list",children:[e.map((v,k)=>{const T=v.id??`${v.timestamp}-${k}`,C=YV(v,n),R=d===T;return f.jsxs("div",{className:se(Mn.messageItem,C&&Mn.agentMessage),"data-testid":`pip-chat-panel-message-${T}`,children:[f.jsxs("div",{className:Mn.messageMetadata,children:[f.jsx("span",{className:Mn.senderName,children:KV(v,n)}),f.jsx("span",{className:Mn.timestamp,children:WV(v.timestamp)})]}),f.jsx("div",{className:Mn.messageBubble,children:v.message}),C?f.jsx("div",{className:Mn.agentActions,children:f.jsx("button",{type:"button",className:se(Mn.copyButton,R&&Mn.copyButtonCopied),onClick:()=>void y(v,T),"aria-label":R?"Copied":"Copy message",title:R?"Copied":"Copy message","data-testid":"pip-copy-agent-message","data-copied":R?"true":"false",children:f.jsx(RE,{size:14})})}):null]},T)}),f.jsx("div",{ref:p})]})}),f.jsxs("div",{className:se(Mn.composer,r&&Mn.composerDisabled),children:[f.jsx("input",{type:"text",className:Mn.composerInput,value:c,onChange:v=>u(v.target.value),onKeyDown:g,placeholder:a,disabled:r,"aria-label":"Message"}),f.jsx("button",{type:"button",className:Mn.sendButton,onClick:()=>void S(),disabled:!x,"aria-label":"Send message",children:f.jsx(DE,{size:16})})]})]})}const JV="_panel_k5ick_1",QV="_header_k5ick_11",ZV="_title_k5ick_19",eG="_titleCompact_k5ick_29",tG="_headerActions_k5ick_33",nG="_closeButton_k5ick_39",iG="_divider_k5ick_67",rG="_body_k5ick_73",aG="_messagesArea_k5ick_81",oG="_scrollable_k5ick_86",sG="_messagesList_k5ick_90",lG="_messageItem_k5ick_98",cG="_messageMetadata_k5ick_104",uG="_senderName_k5ick_112",dG="_timestamp_k5ick_116",hG="_messageBubble_k5ick_120",fG="_messageText_k5ick_124",pG="_agentMessage_k5ick_130",mG="_agentActions_k5ick_134",gG="_copyButton_k5ick_140",vG="_copyButtonCopied_k5ick_174",bG="_inputRow_k5ick_178",yG="_empty_k5ick_182",_G="_composer_k5ick_188",xG="_composerDefault_k5ick_203",SG="_composerCompact_k5ick_208",kG="_composerDisabled_k5ick_218",TG="_composerInputWrapper_k5ick_223",wG="_composerInput_k5ick_223",CG="_sendButton_k5ick_240",EG="_sendButtonCompact_k5ick_257",nt={panel:JV,header:QV,title:ZV,titleCompact:eG,headerActions:tG,closeButton:nG,divider:iG,body:rG,messagesArea:aG,scrollable:oG,messagesList:sG,messageItem:lG,messageMetadata:cG,senderName:uG,timestamp:dG,messageBubble:hG,messageText:fG,agentMessage:pG,agentActions:mG,copyButton:gG,copyButtonCopied:vG,inputRow:bG,empty:yG,composer:_G,composerDefault:xG,composerCompact:SG,composerDisabled:kG,composerInputWrapper:TG,composerInput:wG,sendButton:CG,sendButtonCompact:EG};function RG(t){const e=new Date(t),n=e.getHours(),i=e.getMinutes(),r=n>=12?"PM":"AM",a=n%12||12,o=i.toString().padStart(2,"0");return`${a}:${o}${r}`}function AG(t,e){var i,r;if(typeof t.isAgent=="boolean")return t.isAgent;const n=((i=t.from)==null?void 0:i.identity)??void 0;return n&&e&&n===e?!1:((r=t.attributes)==null?void 0:r.source)==="agent-rpc"?!0:n?n==="agent-avatar"||n.startsWith("agent-"):!1}function NG(t,e){var i,r,a;const n=(i=t.from)==null?void 0:i.identity;return n&&e&&n===e?"You":((r=t.from)==null?void 0:r.name)??((a=t.attributes)==null?void 0:a.senderName)??n??"Unknown"}async function OG(t){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText)){await navigator.clipboard.writeText(t);return}if(typeof document>"u")throw new Error("Clipboard unavailable");const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-9999px",e.style.top="0",e.setAttribute("readonly","true"),document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}function MG(t){const{disabled:e,placeholder:n,size:i="md",autoFocus:r,onSend:a}=t,[o,s]=w.useState(""),l=w.useCallback(async()=>{const p=o.trim();p.length!==0&&(await a(p),s(""))},[a,o]),c=w.useCallback(p=>{p.key==="Enter"&&(p.preventDefault(),l())},[l]),u=i==="sm"||i==="xs",d=u?18:24,h=o.trim().length>0&&e!==!0;return f.jsxs("div",{className:se(nt.composer,u?nt.composerCompact:nt.composerDefault,e?nt.composerDisabled:null),children:[f.jsx("div",{className:nt.composerInputWrapper,children:f.jsx(LE,{value:o,onChange:s,onKeyDown:c,className:nt.composerInput,placeholder:n??"Send a message ...",disabled:e,size:i,autoFocus:r,"aria-label":"Message"})}),f.jsx("button",{type:"button",className:se(nt.sendButton,u?nt.sendButtonCompact:null),onClick:()=>void l(),disabled:!h,"aria-label":"Send message",children:f.jsx(DE,{size:d})})]})}function N3(t){const{title:e="Messages",ariaLabel:n,className:i,messages:r,isSending:a=!1,localIdentity:o,onSend:s,onClose:l,showCloseButton:c=!0,emptyMessage:u="No messages yet",density:d="default",testId:h,formatTimestamp:p=RG,getSenderName:b,isAgentMessage:m,copyResetDelayMs:S=2e3,showAgentCopyButton:g=!0,inputPlaceholder:y,inputAutoFocus:x,...v}=t,k=w.useRef(null),[T,C]=w.useState(null),R=w.useRef(null),A=w.useCallback(K=>b?b(K):NG(K,o),[b,o]),N=w.useCallback(K=>m?m(K,o):AG(K,o),[m,o]),O=w.useMemo(()=>{const K=r[r.length-1];return K?K.id??`${K.timestamp}-${r.length-1}`:null},[r]);w.useEffect(()=>{var K,P;(P=(K=k.current)==null?void 0:K.scrollIntoView)==null||P.call(K,{behavior:"smooth"})},[O]),w.useEffect(()=>()=>{R.current&&(window.clearTimeout(R.current),R.current=null)},[]);const B=w.useCallback(K=>{C(K),R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{C(null),R.current=null},S)},[S]),W=w.useCallback(async(K,P)=>{try{await OG(K.message??""),B(P)}catch(V){console.warn("[ChatPanel] Failed to copy message",V)}},[B]),L=d==="compact"?"sm":"md";return f.jsxs(qu,{...v,className:se(nt.panel,i),role:"region","aria-label":n??e,"data-testid":h,children:[f.jsxs("div",{className:nt.header,children:[f.jsx(xi,{as:"h2",className:se(nt.title,d==="compact"?nt.titleCompact:null),children:e}),l&&c?f.jsx("div",{className:nt.headerActions,children:f.jsx("button",{type:"button",className:nt.closeButton,onClick:l,"aria-label":`Close ${e}`,children:f.jsx(op,{size:d==="compact"?18:20})})}):null]}),f.jsx("div",{className:nt.divider,"aria-hidden":"true"}),f.jsxs("div",{className:nt.body,children:[f.jsx("div",{className:nt.messagesArea,children:f.jsx(zl,{className:nt.scrollable,children:r.length===0?f.jsx(xi,{variant:"muted",className:nt.empty,"data-testid":"chat-panel-empty",children:u}):f.jsxs("div",{className:nt.messagesList,"data-testid":"chat-panel-list",children:[r.map((K,P)=>{const V=K.id??`${K.timestamp}-${P}`,X=N(K),te=T===V;return f.jsxs("div",{className:se(nt.messageItem,X?nt.agentMessage:null),"data-testid":`chat-panel-message-${V}`,children:[f.jsxs("div",{className:nt.messageMetadata,children:[f.jsx("span",{className:nt.senderName,children:A(K)}),f.jsx("span",{className:nt.timestamp,children:p(K.timestamp)})]}),f.jsx(xp,{className:nt.messageBubble,padding:"md",radius:"panel",background:X?"surfaceMuted":"surface",children:f.jsx("div",{className:nt.messageText,children:K.message})}),X&&g?f.jsx("div",{className:nt.agentActions,children:f.jsx("button",{type:"button",className:se(nt.copyButton,te?nt.copyButtonCopied:null),onClick:()=>void W(K,V),"aria-label":te?"Copied":"Copy agent message",title:te?"Copied":"Copy agent message","data-testid":"copy-agent-message","data-copied":te?"true":"false",children:f.jsx(RE,{size:18})})}):null]},V)}),f.jsx("div",{ref:k})]})})}),f.jsx("div",{className:nt.inputRow,children:f.jsx(MG,{onSend:s,disabled:a,placeholder:y,size:L,autoFocus:x})})]})]})}const DG="_responsive_14d0j_2",Hu={responsive:DG,"showAboveWidth-sm":"_showAboveWidth-sm_14d0j_15","showAboveWidth-md":"_showAboveWidth-md_14d0j_24","showAboveWidth-lg":"_showAboveWidth-lg_14d0j_33","showAboveWidth-xl":"_showAboveWidth-xl_14d0j_42","hideAboveWidth-sm":"_hideAboveWidth-sm_14d0j_53","hideAboveWidth-md":"_hideAboveWidth-md_14d0j_59","hideAboveWidth-lg":"_hideAboveWidth-lg_14d0j_65","hideAboveWidth-xl":"_hideAboveWidth-xl_14d0j_71","showAboveHeight-short":"_showAboveHeight-short_14d0j_84","showAboveHeight-medium":"_showAboveHeight-medium_14d0j_93","hideAboveHeight-short":"_hideAboveHeight-short_14d0j_104","hideAboveHeight-medium":"_hideAboveHeight-medium_14d0j_110"};function PG(t){const{as:e,children:n,showAboveWidth:i,hideAboveWidth:r,showAboveHeight:a,hideAboveHeight:o,className:s,...l}=t,c=[Hu.responsive];return i&&c.push(Hu[`showAboveWidth-${i}`]),r&&c.push(Hu[`hideAboveWidth-${r}`]),a&&c.push(Hu[`showAboveHeight-${a}`]),o&&c.push(Hu[`hideAboveHeight-${o}`]),f.jsx(e??"div",{...l,className:se(c,s),children:n})}w.createContext("vertical");const LG="_container_1v6ko_1",IG="_video_1v6ko_7",jG="_chip_1v6ko_16",BG="_logo_1v6ko_34",Sp={container:LG,video:IG,chip:jG,logo:BG},UG="https://obi-static.s3.ap-southeast-2.amazonaws.com/videos/greeting.mp4";function zG(t){const{agentName:e="Obi",greetingVideoSrc:n,className:i,...r}=t,a=w.useRef(null),o=()=>{var s;try{(s=a.current)==null||s.pause()}catch{}};return f.jsxs("div",{className:se(Sp.container,i),...r,children:[f.jsx("video",{ref:a,className:Sp.video,src:n??UG,autoPlay:!0,muted:!0,playsInline:!0,onEnded:o}),f.jsxs("div",{className:Sp.chip,children:[f.jsx(YB,{size:12,className:Sp.logo}),f.jsx("span",{children:e})]})]})}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const O3=50,Hl="?",M3=/\(error: (.*)\)/,D3=/captureMessage|captureException/;function FG(...t){const e=t.sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0,r=0)=>{const a=[],o=n.split(`
133
- `);for(let s=i;s<o.length;s++){const l=o[s];if(l.length>1024)continue;const c=M3.test(l)?l.replace(M3,"$1"):l;if(!c.match(/\S*Error: /)){for(const u of e){const d=u(c);if(d){a.push(d);break}}if(a.length>=O3+r)break}}return qG(a.slice(r))}}function qG(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(kp(e).function||"")&&e.pop(),e.reverse(),D3.test(kp(e).function||"")&&(e.pop(),D3.test(kp(e).function||"")&&e.pop()),e.slice(0,O3).map(n=>({...n,filename:n.filename||kp(e).filename,function:n.function||Hl}))}function kp(t){return t[t.length-1]||{}}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const HG=30,VG=50;function Qb(t,e,n,i){const r={filename:t,function:e==="<anonymous>"?Hl:e,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const GG=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,WG=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,YG=/\((\S*)(?::(\d+))(?::(\d+))\)/,KG=t=>{const e=GG.exec(t);if(e){const[,i,r,a]=e;return Qb(i,Hl,+r,+a)}const n=WG.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){const a=YG.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}const[i,r]=P3(n[1]||Hl,n[2]);return Qb(r,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},XG=[HG,KG],$G=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,JG=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;FG(...[XG,[VG,t=>{const e=$G.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=JG.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let n=e[3],i=e[1]||Hl;return[i,n]=P3(i,n),Qb(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const P3=(t,e)=>{const n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:Hl,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const ir={shell:"_shell_8bsnr_1",layout:"_layout_8bsnr_11",layoutThree:"_layoutThree_8bsnr_23",leftPanel:"_leftPanel_8bsnr_27",middlePanel:"_middlePanel_8bsnr_36",rightPanel:"_rightPanel_8bsnr_37",videoFrame:"_videoFrame_8bsnr_41",captions:"_captions_8bsnr_52",controls:"_controls_8bsnr_58",coursePanel:"_coursePanel_8bsnr_71",returnToPiPOverlay:"_returnToPiPOverlay_8bsnr_82",returnToPiPButton:"_returnToPiPButton_8bsnr_94"};function Zb(...t){return t.filter(Boolean).join(" ")}function QG(t){const{captionsText:e,avatarAudioPower:n=0,avatarImageSrc:i,avatarAriaLabel:r,avatarStatus:a,controlBarProps:o,courses:s,coursePanelProps:l,middlePanel:c,rightPanel:u,isCourseOutlineOpen:d,onReturnToPiP:h,className:p}=t;return f.jsx("div",{className:Zb(ir.shell,p),"data-testid":"course-dialog-content",children:f.jsxs("div",{className:Zb(ir.layout,u?ir.layoutThree:null),children:[f.jsxs("div",{className:ir.leftPanel,children:[f.jsxs("div",{className:ir.videoFrame,children:[d&&h&&f.jsx("div",{className:ir.returnToPiPOverlay,children:f.jsx("button",{type:"button",className:ir.returnToPiPButton,onClick:h,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(GB,{size:14})})}),f.jsx(hH,{className:ir.captions,text:e,children:f.jsx(x3,{audioPower:n,size:"lg",background:"flat",imageSrc:i,ariaLabel:r??"Agent avatar placeholder",status:a})})]}),f.jsx("div",{className:ir.controls,children:f.jsx(BF,{...o})})]}),u?f.jsx("div",{className:ir.rightPanel,"data-testid":"course-dialog-right-panel",children:u}):null,f.jsx("div",{className:ir.middlePanel,"data-testid":"course-dialog-middle-panel",children:c??f.jsx(YH,{...l,courses:s,className:Zb(ir.coursePanel,l==null?void 0:l.className)})})]})})}function L3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(HE,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(QG,{...r})})}const ZG=80,eW=500,tW=1e3;function nW(t,e){const{delayMs:n=0}=e??{},r=t.filter(m=>{var g;const S=(g=m.participantInfo)==null?void 0:g.identity;return(S==null?void 0:S.startsWith("agent-"))??!1}).map(m=>m.text??"").join(" ").trim(),[a,o]=w.useState(""),[s,l]=w.useState(!1),c=w.useRef(""),u=w.useRef(null),d=w.useRef(null),h=w.useRef(null),p=m=>{h.current&&(clearTimeout(h.current),h.current=null),n>0?h.current=setTimeout(()=>{o(m)},n):o(m)},b=(m,S)=>m.startsWith(S)?m.slice(S.length).trim():m.trim();return w.useEffect(()=>{if(d.current&&(clearTimeout(d.current),d.current=null),s)return;const m=b(r,c.current);p(m),m.length>ZG?(l(!0),u.current=setTimeout(()=>{l(!1),c.current=r},eW+n)):m.length>0&&(d.current=setTimeout(()=>{c.current=r,p("")},tW+n))},[r,s,n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current)},[]),{caption:a,hasCaption:a.length>0}}const kr={layout:"_layout_k1q6c_1",left:"_left_k1q6c_10",copy:"_copy_k1q6c_17",description:"_description_k1q6c_25",descriptionScroller:"_descriptionScroller_k1q6c_31",cta:"_cta_k1q6c_36",disclaimer:"_disclaimer_k1q6c_43",right:"_right_k1q6c_47",mediaPanel:"_mediaPanel_k1q6c_56",agentStill:"_agentStill_k1q6c_63",dialogWithSmallClose:"_dialogWithSmallClose_k1q6c_88"};function iW(t){const{open:e,onClose:n,onStart:i,agentName:r,agentSubtitle:a,description:o,startLabel:s="Start Now",disclaimer:l="Sessions are securely recorded for quality improvement purposes.",showCloseButton:c=!1,isStarting:u=!1,greetingVideoSrc:d}=t;return f.jsx(HE,{open:e,onClose:n,size:"large",showCloseButton:c,className:kr.dialogWithSmallClose,children:f.jsxs("div",{className:kr.layout,children:[f.jsxs("div",{className:kr.left,children:[f.jsxs("div",{className:kr.copy,children:[f.jsx(xi,{variant:"heading",children:r}),f.jsx(xi,{variant:"subheading",children:a}),f.jsx(xi,{variant:"muted",as:"div",className:kr.description,children:f.jsx(zl,{className:kr.descriptionScroller,children:f.jsx(nF,{content:o})})})]}),f.jsxs("div",{className:kr.cta,children:[f.jsx(_s,{type:"button",size:"lg",fullWidth:!0,onClick:i,isLoading:u,children:s}),f.jsx(xi,{variant:"subscript",as:"p",className:kr.disclaimer,children:l})]})]}),f.jsx(PG,{showAboveWidth:"md",children:f.jsx("div",{className:kr.right,children:f.jsx(qu,{className:kr.mediaPanel,children:f.jsx(zG,{agentName:r,greetingVideoSrc:d,className:kr.agentStill})})})})]})})}const rW={launcherPill:"_launcherPill_1fhyr_1"};function aW(t){const{label:e,onClick:n}=t;return f.jsx("button",{type:"button",className:rW.launcherPill,onClick:n,"data-testid":"ai-coach-pill",children:e})}const I3="__ama_course__",oW="ama_course",sW=3e4;function lW(t){var No,Oo,Wl,_n,xn,Mo,Do,Kr,Po,Ut,Lo,Io,jo,Bo,Yl,_,I,M,pe,Le,ve,zt,_t,xt,Xr,Ie,Uo,Kl,K3;const{sdk:e,shadowHost:n}=t,i=!!e.passivePlanUuid,r=i?((No=e.client)==null?void 0:No.selectedPlanUuid)??null:null,a=((Oo=e.client)==null?void 0:Oo.session)??null,o=!!a&&(i&&!!r||!!((Wl=e.client)!=null&&Wl.selectedPlanUuid)),[s,l]=w.useState(()=>a),[c,u]=w.useState(()=>a!=null&&a.sessionUuid?uW(a.sessionUuid):null),d=(()=>{var Y;return a?((Y=a.roomId)==null?void 0:Y.startsWith("obs-"))&&!c?"course-selection":"pip":r?"start-session":"hidden"})(),[h,p]=w.useState(()=>d),b=w.useRef(d),[m,S]=w.useState(!1),[g,y]=w.useState(!1),[x,v]=w.useState(!1),[k,T]=w.useState([]),[C,R]=w.useState(null),[A,N]=w.useState(null),[O,B]=w.useState(0),[W,L]=w.useState(!1),[K,P]=w.useState(!1),[V,X]=w.useState(0),[te,$]=w.useState(null),[z,Z]=w.useState([]),[Q,ce]=w.useState(!1),[j,ge]=w.useState(!1),[U,fe]=w.useState(()=>o),me=w.useRef(o),Rt=w.useRef(null),en=w.useRef(null),be=w.useRef(!1),qe=()=>{p(Y=>{const ne=Y==="course-selection",Te=Y==="course-outline"&&be.current;return ne||Te?(be.current=!1,L(!1),"pip"):Y})};w.useEffect(()=>{b.current=h},[h]),w.useEffect(()=>()=>{Rt.current&&clearTimeout(Rt.current)},[]);const bt=()=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null)},Je=()=>{bt(),en.current=null,N(Y=>Y===null?Y:null)},cn=Y=>{bt(),en.current=Y,N(Y),Rt.current=setTimeout(()=>{const ne=en.current===Y,Te=b.current==="course-selection";ne&&Te&&(en.current=null,N(null)),Rt.current=null},sW)},tn=dW((xn=(_n=e.client)==null?void 0:_n.product)==null?void 0:xn.widget_url_blacklist),Mt=hW(s),{audioDevices:bn}=fW();w.useEffect(()=>{s!=null&&s.sessionUuid&&j3(s.sessionUuid,c)},[c,s==null?void 0:s.sessionUuid]);const{caption:yn}=nW(z,{delayMs:0}),In=typeof navigator<"u"&&!!((Mo=navigator.mediaDevices)!=null&&Mo.getDisplayMedia),Si=((Kr=(Do=s==null?void 0:s.room)==null?void 0:Do.localParticipant)==null?void 0:Kr.isScreenShareEnabled)??!1,de=Y=>{var Ae;const ne=((Ae=e.client)==null?void 0:Ae.identity)??Y.identity,Te=typeof(ne==null?void 0:ne.first_name)=="string"?ne.first_name.trim():"",st=typeof(ne==null?void 0:ne.last_name)=="string"?ne.last_name.trim():"",xe=typeof(ne==null?void 0:ne.email)=="string"&&ne.email.trim().length>0?ne.email.trim():"";return{firstName:Te,lastName:st,email:xe}},We=Y=>{const{firstName:ne,lastName:Te,email:st}=de(Y),xe=[ne,Te,st].map(pt=>pt.trim());return xe.some(pt=>pt.length>0)?xe.join(":"):""},Ce=Y=>{const{firstName:ne,lastName:Te,email:st}=de(Y),xe=[ne,Te].filter(Boolean).join(" ").trim();return{name:xe.length>0?xe:void 0,email:st.length>0?st:void 0,screenShareSupported:In}},Qe=(()=>{if(s!=null&&s.speakingState){if(s.speakingState==="thinking")return"thinking";if(s.speakingState==="busy")return"searching"}})(),ot=((Ut=(Po=e.client)==null?void 0:Po.product)==null?void 0:Ut.avatar_image_url)||((Io=(Lo=e.client)==null?void 0:Lo.product)==null?void 0:Io.logo_url)||void 0,ki=((Bo=(jo=e.client)==null?void 0:jo.product)==null?void 0:Bo.greeting_video_url)||void 0,Ii=cW({sdk:e,session:s,isBlacklisted:tn}),Wr=!i&&Ii,q=!!(s??((Yl=e.client)==null?void 0:Yl.session)??null),ae=(s==null?void 0:s.clientType)==="meet"?We(s):"",he=(I=(_=e.client)==null?void 0:_.product)==null?void 0:I.assistant_subtitle,Pe=typeof he=="string"&&he.trim().length>0?he:"Onboarding Assistant",it=()=>B(Y=>Y+1),jn=async()=>{var ne,Te;if(!s)return;const Y=((Te=(ne=s.room)==null?void 0:ne.localParticipant)==null?void 0:Te.isScreenShareEnabled)??!1;try{Y?await s.setScreenShareEnabled(!1):await s.shareScreen()}catch(st){console.error("[obi-sdk] failed to toggle screen share",st)}finally{it()}},Ti=w.useRef(null),Bn=w.useRef(null),Un=w.useRef(!1),Wt=w.useRef({session:null,sessionUuid:null,started:!1}),ai=w.useRef(null),zn=w.useRef(new WeakMap),Vl=(Y,ne)=>{if(!ne)return;let Te=zn.current.get(Y);Te||(Te=new Set,zn.current.set(Y,Te)),Te.add(ne)},ks=Y=>{if(!Y||Ti.current===Y)return;Bn.current&&(Bn.current(),Bn.current=null);const ne=()=>it(),Te=ie=>{u(ie),Je(),Y!=null&&Y.sessionUuid&&j3(Y.sessionUuid,ie),p(Ne=>Ne==="pip"||Ne==="course-outline"?Ne:Ne==="course-selection"?(be.current=!0,"course-outline"):Ne)},st=ie=>{Je(),T(ie.courses),p("course-selection"),be.current=!1,u(null),Y!=null&&Y.sessionUuid&&B3(Y.sessionUuid),R(null),P(!1)},xe=(ie,Ne)=>{},Ae=ie=>{ie.isAgent},pt=ie=>{$(ie),X(Date.now())},nn=ie=>{if(!ie){$(null);return}$(ie),X(Date.now())};Y.on("stateChanged",ne),Y.on("speakingStateChanged",ne),Y.on("paused",ne),Y.on("unpaused",ne),Y.on("chatMessagesChanged",ne),Y.on("chatMessageReceived",Ae),Y.on("courseProgress",Te),Y.on("courseSelection",st),Y.on("transcript",xe),Y.on("screenCaptured",pt),Y.on("screenCaptureNotification",nn),Y.on("captions",Z),Y.on("introductionComplete",qe),Ti.current=Y,Bn.current=()=>{Y.off("stateChanged",ne),Y.off("speakingStateChanged",ne),Y.off("paused",ne),Y.off("unpaused",ne),Y.off("chatMessagesChanged",ne),Y.off("chatMessageReceived",Ae),Y.off("courseProgress",Te),Y.off("courseSelection",st),Y.off("transcript",xe),Y.off("screenCaptured",pt),Y.off("screenCaptureNotification",nn),Y.off("captions",Z),Y.off("introductionComplete",qe)}},Se=Y=>{var Te;return Y?((Te=Y.roomId)==null?void 0:Te.startsWith("obs-"))&&!c?"course-selection":"pip":"hidden"};w.useEffect(()=>{const Y=()=>{ai.current&&(ai.current(),ai.current=null)},ne=xe=>{if(xe.clientType!=="meet")return;if(Wt.current.session&&Wt.current.session===xe||!!Wt.current.sessionUuid&&!!xe.sessionUuid&&Wt.current.sessionUuid===xe.sessionUuid){if(Wt.current.started||ai.current)return}else Wt.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!1},Y();const pt=async()=>{Wt.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!0};const Ne=We(xe);Ne&&Vl(xe,Ne);try{await xe.sendHumanJoined(Ce(xe))}catch(Yt){console.error("[obi-sdk] failed to send human_joined handshake",Yt)}},nn=(Ne,Yt)=>{Ne==="connecting"||Ne==="error"||(Y(),pt())},ie=xe.state;if(ie&&ie!=="connecting"&&ie!=="error"){pt();return}xe.on("stateChanged",nn),ai.current=()=>{xe.off("stateChanged",nn)}},Te=xe=>{var Ae,pt,nn,ie;if(xe)if((Ae=e.client)!=null&&Ae.session)p(Se(((nn=e.client)==null?void 0:nn.session)??null));else{const Yt=!!e.passivePlanUuid,qn=Yt&&!!((pt=e.client)!=null&&pt.selectedPlanUuid);if(Yt&&!qn)return;p("start-session")}else(ie=e.client)!=null&&ie.session||p("hidden")},st=()=>it();if(e.on("showMenu",Te),e.on("configUpdated",st),e.client){e.client.session&&(l(e.client.session),ks(e.client.session),p(Se(e.client.session))),e.client.on("sessionStarted",Ae=>{l(Ae),ks(Ae),Un.current=!1,S(!1),y(!1),v(!1),P(!1);const pt=me.current;me.current=!1,pt?(be.current=!0,p("course-outline")):(be.current=!1,p(Se(Ae))),sa().track("session-started",{planId:Ae.planId}),ne(Ae)}),e.client.on("sessionResumed",Ae=>{l(Ae),ks(Ae),Un.current=!1,S(!1),y(!1),v(!1),P(!1),be.current=!1,p(Se(Ae)),ne(Ae)});const xe=()=>{var nn;const Ae=(nn=e.client)==null?void 0:nn.session;Ae!=null&&Ae.sessionUuid&&B3(Ae.sessionUuid);const pt=Ti.current;Bn.current&&(Bn.current(),Bn.current=null),l(null),Ti.current=null,S(!1),y(!1),v(!1),P(!1),fe(!1),me.current=!1,Je(),be.current=!1,Y(),Wt.current={session:null,sessionUuid:null,started:!1},pt&&zn.current.delete(pt),Un.current||p("hidden")};e.client.on("sessionStopped",xe),e.client.on("sessionShutdown",xe),e.client.on("stateChanged",it)}return()=>{e.off("showMenu",Te),e.off("configUpdated",st),Bn.current&&Bn.current(),Y()}},[e]),w.useEffect(()=>{const Y=s;if(!Y||Y.clientType!=="meet")return;const ne=Y.state;if(!ne||ne==="connecting"||ne==="error"||!ae)return;const Te=zn.current.get(Y);Te!=null&&Te.has(ae)||(Vl(Y,ae),Y.sendHumanJoined(Ce(Y)).catch(st=>console.error("[obi-sdk] failed to send human_joined update",st)))},[In,ae,s,s==null?void 0:s.state]),w.useLayoutEffect(()=>{var Y,ne;(ne=(Y=e.client)==null?void 0:Y.product)!=null&&ne.primary_color&&n.style.setProperty("--obi-color-primary",e.client.product.primary_color)},[(pe=(M=e.client)==null?void 0:M.product)==null?void 0:pe.primary_color,n]),w.useEffect(()=>{if(i&&!tn&&!q){if(!r){p("hidden");return}p("start-session")}},[q,i,tn,r]),w.useEffect(()=>{var nn,ie;ge(!1);const Y=(nn=e.client)==null?void 0:nn.api,ne=(ie=e.client)==null?void 0:ie.product;if(!Y||!ne)return;const Te=(ne==null?void 0:ne.uuid)??(ne==null?void 0:ne.product_uuid),st=(ne==null?void 0:ne.slug)??(ne==null?void 0:ne.product_slug),xe=(ne==null?void 0:ne.id)??(ne==null?void 0:ne.product_id),Ae={};if(Te?Ae.product_uuid=Te:st?Ae.product_slug=st:xe!=null&&(Ae.product_id=String(xe)),Object.keys(Ae).length===0)return;let pt=!1;return Y.getFeatureFlags(Ae).then(Ne=>{if(pt)return;const qn=((Ne==null?void 0:Ne.data)??[]).find(ny=>(ny==null?void 0:ny.slug)===oW);if(!qn)return;const{user_enabled:oi,product_enabled:Hn,global_enabled:Tr}=qn;let ty=!!Tr;Hn!=null&&(ty=!!Hn),oi!=null&&(ty=!!oi),ge(ty)}).catch(Ne=>{console.error("[obi-sdk] failed to load AMA feature flag",Ne)}),()=>{pt=!0}},[(Le=e.client)==null?void 0:Le.api,(ve=e.client)==null?void 0:ve.product]);const Fn=(c==null?void 0:c.stepNames.map((Y,ne)=>({id:`step-${ne+1}`,title:Y})))??[],Gl=(c==null?void 0:c.currentStep)??null,Ao=!0,Yr=(Y,ne)=>{s==null||s.say(`Can we jump to the section about ${ne.title}?`)};if(tn||i&&!r&&!q)return null;if(h==="hidden")return Wr?f.jsx(aW,{label:Pe,onClick:()=>{e.updateShowMenu(!0)}}):null;if(h==="start-session"){const Y=(zt=e.client)==null?void 0:zt.product,ne=(_t=e.client)==null?void 0:_t.selectedPlan,Te=i&&!!r,st=i&&!!r||!!((xt=e.client)!=null&&xt.selectedPlanUuid),xe=(Y==null?void 0:Y.agent_name)||"Obi",Ae=(Y==null?void 0:Y.assistant_subtitle)||"AI Assistant",pt=Te&&(ne==null?void 0:ne.description)||(Y==null?void 0:Y.assistant_description)||"";return f.jsx(iW,{open:!0,onClose:()=>{S(!1),p("hidden")},onStart:()=>{me.current=st,fe(st),S(!0),e.startSession({withMicrophone:!0})},agentName:xe,agentSubtitle:Ae,description:pt,showCloseButton:!1,startLabel:"Start Session",isStarting:m,greetingVideoSrc:ki})}if(h==="course-selection"){const Y=(Xr=s==null?void 0:s.roomId)==null?void 0:Xr.startsWith("obs-"),ne=((Ie=e.client)==null?void 0:Ie.plans)||[],Te=Y&&k.length>0,st=Te?k.slice().sort((ie,Ne)=>ie.order!==void 0&&Ne.order!==void 0?ie.order-Ne.order:ie.order!==void 0?-1:Ne.order!==void 0?1:ie.name.localeCompare(Ne.name)).map(ie=>({id:ie.uuid,title:ie.name,description:ie.description||ie.overview||"",status:ie.completed?"completed":"available",duration:typeof ie.duration=="number"?`${ie.duration} min`:ie.duration})):ne.map(ie=>{var Ne,Yt;return{id:ie.uuid,title:ie.name,description:ie.description,status:(Yt=(Ne=e.client)==null?void 0:Ne.planIsCompleted)!=null&&Yt[ne.indexOf(ie)]?"completed":"available",duration:ie.estimated_duration?`${ie.estimated_duration} min`:void 0}});Te&&j&&st.push({id:I3,title:"Ask me anything",description:"Ask questions before choosing a course.",status:"available"});const xe=(s==null?void 0:s.languageCodes)||[],Ae=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,pt={audioDevices:bn,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:Si,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:In,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),it()},onMicToggle:async()=>{s!=null&&s.isMicShared?g?(await s.unmuteMicrophone(),y(!1)):(await s.muteMicrophone(),y(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{v(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:jn,languages:xe,selectedLanguage:Ae,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...x?{screenShareButtonVariant:"compact"}:{}},nn=x?f.jsx(N3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((Uo=s==null?void 0:s.room)==null?void 0:Uo.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ne,Yt,qn,oi;if(s){const Hn=Date.now();s.appendChatMessage({timestamp:Hn,message:ie,from:{identity:((Yt=(Ne=s.room)==null?void 0:Ne.localParticipant)==null?void 0:Yt.identity)??null,name:((oi=(qn=s.room)==null?void 0:qn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>v(!1)}):void 0;return f.jsx(L3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:st,controlBarProps:pt,coursePanelProps:{selectedCourseIds:C?[C]:void 0,loadingCourseId:A,onCourseToggle:async ie=>{var Ne,Yt,qn,oi;if(!en.current)if(Te){if(ie===I3){cn(ie),R(ie);try{await((Ne=s==null?void 0:s.say)==null?void 0:Ne.call(s,"Please start an AMA session."))}catch(Tr){console.error("[obi-sdk] failed to start AMA course",Tr),Je(),R(null)}return}const Hn=k.find(Tr=>Tr.uuid===ie);if(Hn){cn(ie),R(ie);try{await((Yt=s==null?void 0:s.say)==null?void 0:Yt.call(s,`I'd like to take the ${Hn.name} course.`))}catch(Tr){console.error("[obi-sdk] failed to send course selection",Tr),Je(),R(null)}}}else{const Hn=ne.find(Tr=>Tr.uuid===ie);if(Hn){cn(ie),(qn=e.client)==null||qn.selectPlan(Hn),p("pip");try{await((oi=s==null?void 0:s.say)==null?void 0:oi.call(s,`I'd like to take the ${Hn.name} course.`))}catch(Tr){console.error("[obi-sdk] failed to send course selection",Tr),p("course-selection"),Je()}}}}},rightPanel:nn,avatarImageSrc:ot,avatarAudioPower:Mt,avatarStatus:Qe,captionsText:yn})}if(h==="course-outline"){const Y=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Te={audioDevices:bn,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:Si,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:In,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),it()},onMicToggle:async()=>{s!=null&&s.isMicShared?g?(await s.unmuteMicrophone(),y(!1)):(await s.muteMicrophone(),y(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{v(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:jn,languages:Y,selectedLanguage:ne,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...x?{screenShareButtonVariant:"compact"}:{}},st=x?f.jsx(N3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((Kl=s==null?void 0:s.room)==null?void 0:Kl.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ne,Yt,qn,oi;if(s){const Hn=Date.now();s.appendChatMessage({timestamp:Hn,message:ie,from:{identity:((Yt=(Ne=s.room)==null?void 0:Ne.localParticipant)==null?void 0:Yt.identity)??null,name:((oi=(qn=s.room)==null?void 0:qn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>v(!1)}):void 0,xe=!!c,Ae=!U,pt=async()=>{if(!(!(s!=null&&s.endCourse)||K)){P(!0);try{await s.endCourse("back_to_courses")}catch(ie){console.error("[obi-sdk] failed to end course",ie),P(!1)}}},nn=f.jsx(RV,{steps:Fn,currentStep:Gl,hideTrailingConclusionStep:Ao,onStepClick:Yr,showBackToCourses:Ae,...Ae?{onBackToCoursesConfirm:pt,backToCoursesDisabled:K}:{}});return f.jsx(L3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:Te,middlePanel:nn,rightPanel:st,isCourseOutlineOpen:xe,onReturnToPiP:xe?()=>p("pip"):void 0,avatarImageSrc:ot,avatarAudioPower:Mt,avatarStatus:Qe,captionsText:yn})}if(h==="pip"){const Y=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Te=280,st=250,xe=16,Ae={x:window.innerWidth-Te-xe,y:window.innerHeight-st-xe},pt={isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isChatOpen:x,isScreenShareActive:Si,onMicToggle:async()=>{s!=null&&s.isMicShared?g?(await s.unmuteMicrophone(),y(!1)):(await s.muteMicrophone(),y(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>v(ie=>!ie),onScreenShareToggle:jn,onLeave:()=>{s==null||s.stop()},languages:Y,selectedLanguage:ne,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0},nn=x?f.jsx($V,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((K3=s==null?void 0:s.room)==null?void 0:K3.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ne,Yt,qn,oi;if(s){const Hn=Date.now();s.appendChatMessage({timestamp:Hn,message:ie,from:{identity:((Yt=(Ne=s.room)==null?void 0:Ne.localParticipant)==null?void 0:Yt.identity)??null,name:((oi=(qn=s.room)==null?void 0:qn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(ie)}},testId:"pip-chat-panel"}):void 0;return f.jsx(sH,{initialPosition:Ae,onExit:()=>{be.current=!1,p("course-outline")},controlBarProps:pt,isCourseOutlineSelected:W&&!!c,onCourseOutlineToggle:c?()=>{L(ie=>!ie)}:void 0,isCaptionsEnabled:Q,onCaptionsToggle:()=>ce(ie=>!ie),courseOutline:c?{steps:Fn,currentStep:Gl,onStepClick:Yr,hideTrailingConclusionStep:Ao}:void 0,messagesPanel:nn,avatarFallbackProps:{audioPower:Mt,imageSrc:ot,status:Qe,captionsText:yn},screenshotUrl:te,cameraShotTrigger:V})}return null}function cW(t){var l,c;const{sdk:e,session:n,isBlacklisted:i}=t;if(i)return!1;const r=e.client;if(!r||r.state!=="ready"||(n??r.session??null))return!1;let o=e.isActive;return((l=r.product)==null?void 0:l.name)==="Canibuild"&&(o=!0),!(!o||(e.widgetDisplay??((c=r.product)==null?void 0:c.widget_display))==="invisible")}function j3(t,e){if(!t)return;const n=`obi-widget-course-progress-${t}`;if(e===null){localStorage.removeItem(n);return}try{const i={...e,timestamp:Date.now()};localStorage.setItem(n,JSON.stringify(i))}catch(i){console.error("[obi-sdk] failed to save course progress",i)}}function uW(t){if(!t)return null;const e=`obi-widget-course-progress-${t}`;try{const n=localStorage.getItem(e);if(!n)return null;const i=JSON.parse(n);if(typeof i.currentStep!="number"||typeof i.totalSteps!="number"||!Array.isArray(i.stepNames))return console.warn("[obi-sdk] invalid course progress data, clearing",i),localStorage.removeItem(e),null;const r=24*60*60*1e3;return i.timestamp&&Date.now()-i.timestamp>r?(localStorage.removeItem(e),null):{currentStep:i.currentStep,totalSteps:i.totalSteps,stepNames:i.stepNames}}catch(n){return console.error("[obi-sdk] failed to load course progress",n),localStorage.removeItem(e),null}}function B3(t){if(!t)return;const e=`obi-widget-course-progress-${t}`;try{localStorage.removeItem(e)}catch(n){console.error("[obi-sdk] failed to clear course progress",n)}}function dW(t){const[e,n]=w.useState(()=>ys(t));return w.useEffect(()=>{n(ys(t))},[t]),w.useEffect(()=>{const i=()=>{n(ys(t))};return window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[t]),e}function hW(t){const[e,n]=w.useState(0),i=w.useRef(null),r=w.useRef(0),a=w.useRef(0);return w.useEffect(()=>{if(!t){n(0),r.current=0,a.current=0;return}const o=()=>{const s=t.audioSpectrum();let l=0;if(s&&s.length>0){let b=0;for(let m=0;m<s.length;m++)b+=s[m];l=Math.min(1,Math.max(0,b/s.length))}const c=r.current,d=l>=c?.7:.15,h=c*d+l*(1-d);r.current=h;const p=h<.05?0:Math.min(1,h);Math.abs(p-a.current)>.01&&(a.current=p,n(p)),i.current=requestAnimationFrame(o)};return i.current=requestAnimationFrame(o),()=>{i.current&&cancelAnimationFrame(i.current)}},[t]),e}function fW(){const[t,e]=w.useState({audioDevices:[]});return w.useEffect(()=>{var i;if(typeof navigator>"u"||!((i=navigator.mediaDevices)!=null&&i.enumerateDevices))return;const n=()=>{navigator.mediaDevices.enumerateDevices().then(r=>{e({audioDevices:r.filter(a=>a.kind==="audioinput")})})};return n(),navigator.mediaDevices.addEventListener("devicechange",n),()=>navigator.mediaDevices.removeEventListener("devicechange",n)},[]),t}function U3(){const t=window.location.hostname;return t.endsWith(".getcor.ai")||t.endsWith(".getcor.io")||t.endsWith(".clinic1.com")||t==="getcor.ai"||t==="getcor.io"||t==="localhost"||t==="127.0.0.1"||t==="::1"}const z3=U3();function pW(t){if(document.querySelector("#obi-host")||document.querySelector("obi-widget"))return;mW();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const n=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",n.appendChild(i);const r=new CSSStyleSheet;r.replaceSync(MB);const a=[r];if(z3){const s=new CSSStyleSheet;s.replaceSync(AB),a.push(s);const l=new CSSStyleSheet;l.replaceSync(OB),a.push(l)}else{const s=new CSSStyleSheet;s.replaceSync(NB),a.push(s)}n.adoptedStyleSheets=a;const o=RB.createRoot(i);z3?o.render(f.jsx(lW,{sdk:t,shadowHost:e})):o.render(f.jsx(LB,{sdk:t,shadowHost:e})),console.log("[obi-sdk] widget mounted")}function mW(){F3("https://fonts.cdnfonts.com/css/satoshi"),F3("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function F3(t){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}const q3="49206C6F7665204F6269_session",H3="obi-url-params",ey="obi-client-heartbeat",gW=5e3,V3=4e4,G3=15e3;function vW(){return U3()?"meet":"sdk"}class bW extends Ep{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.heartbeatInterval=null,this.dispatchCommand=(n,i)=>{var r,a,o,s,l;switch(this.commandLog.push({commandType:n,args:i}),n){case"update":this.updateConfig(i);break;case"startSession":{if(i!=null&&i.planUuid){const c=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",i);return}(o=(a=this.client)==null?void 0:a.selectPlan)==null||o.call(a,c)}this.updateActive(!0);break}case"stopSession":(l=(s=this.client)==null?void 0:s.stopSession)==null||l.call(s);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:n,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 n=null;const i=vW(),r=this.load();if(r)try{const a=this.parsePersistedSessionMetadata(r),o=a&&this.isPersistedSessionStale(a);o!=null&&o.stale&&a?(this.trackStaleSessionDiscard(a.sessionUuid,o.ageMs,o.reason),this.clearCachedClient()):(n=wh.deserialise(r,e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),n?this._resumed=!0:this.clearCachedClient())}catch(a){console.error("[obi] error loading cached client",a),this.clearCachedClient()}n||(n=new wh(e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=n,this.client.session&&this.startHeartbeat(this.client.session.sessionUuid),this.client.on("stateChanged",a=>{var o,s,l,c,u,d,h,p,b,m;a==="ready"&&this.updateConfig({isActive:((o=window==null?void 0:window.obiWidgetConfig)==null?void 0:o.isActive)??((s=this.client)==null?void 0:s.showWidget),primaryColour:((c=(l=this.client)==null?void 0:l.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((u=window==null?void 0:window.obiWidgetConfig)==null?void 0:u.widgetDisplay)||((h=(d=this.client)==null?void 0:d.product)==null?void 0:h.widget_display)||"regular",completedWidgetDisplay:((p=window==null?void 0:window.obiWidgetConfig)==null?void 0:p.completedWidgetDisplay)||((m=(b=this.client)==null?void 0:b.product)==null?void 0:m.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{var a,o;this.save(),this.startHeartbeat(((o=(a=this.client)==null?void 0:a.session)==null?void 0:o.sessionUuid)||null),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{this.clearCachedClient(),this.passivePlanUuid=null}),this.client.on("sessionShutdown",()=>{this.clearCachedClient()}),this.client.on("trackEvent",(a,o)=>{}),this.client.session&&(this.client.session.isPaused,this.client.resumeSession(a=>{a.on("stateChanged",o=>{o!=="disconnecting"&&o!=="disconnected"&&o!=="error"&&o!=="connecting"&&this.save()}),a.on("paused",()=>{this.save()}),a.on("unpaused",()=>{this.save()})}))}_maybeActOnServerEngagement(){var s;const e=this.client;if(!e||e.state!=="ready")return;const n=e.product,i=(s=e.engagement)==null?void 0:s.style;if(!i||n&&ys(n.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],a=e.planIsCompleted||[],o=r.length>0&&a.filter(Boolean).length===r.length;if(!(r.length===0||o)){if(i==="modal"){const l=a.findIndex(u=>!u),c=l>=0?r[l]:null;c&&e.selectPlan(c)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{sa().track("engagement-prompt-shown",{style:i})}catch{}}}async initialise(e={}){var n;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((n=window==null?void 0:window.obiWidgetConfig)==null?void 0:n.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){e.apiKey!==void 0&&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),e.user!==void 0&&await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var n;e===void 0||e==((n=this.client)==null?void 0:n.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 n=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:n,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(a=>{console.error("[obi] error initialising client",a),this.emit("error",a)}),e!=null&&e.email&&sa().identify((e==null?void 0:e.email)||"",n)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var n,i,r;await((r=(i=(n=this.client)==null?void 0:n.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(e){await this.client.startSession(this.client.selectedPlanUuid||null,n=>{n.on("stateChanged",i=>{i!=="disconnecting"&&i!=="disconnected"&&i!=="error"&&i!=="connecting"&&this.save()}),n.on("paused",()=>{this.save()}),n.on("unpaused",()=>{this.save()})},e)}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(n=>{try{this.dispatchCommand(n[0],n[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(H3)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((a,o)=>{e[o]=a});const n=e[q3];if(!n)return null;const i=new URL(window.location.href);i.searchParams.delete(q3),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(H3),this.passivePlanUuid=n}mountWidget(){pW(this)}showMessage(e,n){try{this.emit("showMessage",{text:e,autoCloseMs:n==null?void 0:n.autoCloseMs})}catch{}}async captureScreen(){try{await xO(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await mR(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 ZN(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var n;const e=((n=this.client)==null?void 0:n.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}parsePersistedSessionMetadata(e){const n=JSON.parse(e),i=this.parseTimestampMs(n.serialisedAt);if(!n.session)return null;let r=null;if(typeof n.session=="string")try{r=JSON.parse(n.session)}catch{return null}else typeof n.session=="object"&&(r=n.session);return r?{sessionUuid:typeof r.sessionUuid=="string"?r.sessionUuid:null,startedAtMs:this.parseTimestampMs(r.startedAt),serialisedAtMs:i}:null}isPersistedSessionStale(e){const n=Date.now(),i=this.readHeartbeat();if(i&&i.sessionUuid&&e.sessionUuid&&i.sessionUuid===e.sessionUuid){const s=Math.max(0,n-i.updatedAtMs);return{stale:s>V3,reason:s>V3?"heartbeat-stale":"heartbeat-fresh",ageMs:s}}const r=[e.serialisedAtMs,e.startedAtMs].filter(s=>typeof s=="number"&&Number.isFinite(s));if(r.length===0)return{stale:!0,reason:"fallback-missing-timestamps",ageMs:null};const a=Math.max(...r),o=Math.max(0,n-a);return{stale:o>G3,reason:o>G3?"fallback-too-old":"fallback-recent",ageMs:o}}parseTimestampMs(e){if(typeof e=="number")return e;if(typeof e=="string"){const n=Number(e);if(!Number.isNaN(n))return n;const i=Date.parse(e);return Number.isFinite(i)?i:null}return null}readHeartbeat(){const e=localStorage.getItem(ey);if(!e)return null;try{return JSON.parse(e)}catch{return null}}trackStaleSessionDiscard(e,n,i){try{sa().track("stale-session-discarded",{sessionUuid:e||void 0,ageMs:n??void 0,reason:i})}catch{}}startHeartbeat(e){if(!e){this.clearHeartbeat();return}this.stopHeartbeat(),this.writeHeartbeat(e),this.heartbeatInterval=setInterval(()=>{this.writeHeartbeat(e)},gW)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}writeHeartbeat(e){const n={sessionUuid:e,updatedAtMs:Date.now()};localStorage.setItem(ey,JSON.stringify(n))}clearHeartbeat(){this.stopHeartbeat(),localStorage.removeItem(ey)}clearCachedClient(){this.clearHeartbeat(),localStorage.removeItem("obi-client")}}async function W3(t,e){let n;try{n=window}catch{console.warn("[obi] no window object found"),n={}}return yW({appToken:t,window:n,init:e})}async function yW({appToken:t,window:e,init:n}){var a,o;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}n&&n(),t||(t=(a=e==null?void 0:e.obiWidgetConfig)==null?void 0:a.apiKey);let i;try{i=((o=e.ObiSDK)==null?void 0:o.q)||[]}catch{i=[]}const r=new bW(t);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function Y3(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{W3(void 0,Y3)}):W3(void 0,Y3)})();
133
+ `);for(let s=i;s<o.length;s++){const l=o[s];if(l.length>1024)continue;const c=M3.test(l)?l.replace(M3,"$1"):l;if(!c.match(/\S*Error: /)){for(const u of e){const d=u(c);if(d){a.push(d);break}}if(a.length>=O3+r)break}}return qG(a.slice(r))}}function qG(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(kp(e).function||"")&&e.pop(),e.reverse(),D3.test(kp(e).function||"")&&(e.pop(),D3.test(kp(e).function||"")&&e.pop()),e.slice(0,O3).map(n=>({...n,filename:n.filename||kp(e).filename,function:n.function||Hl}))}function kp(t){return t[t.length-1]||{}}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const HG=30,VG=50;function Qb(t,e,n,i){const r={filename:t,function:e==="<anonymous>"?Hl:e,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const GG=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,WG=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,YG=/\((\S*)(?::(\d+))(?::(\d+))\)/,KG=t=>{const e=GG.exec(t);if(e){const[,i,r,a]=e;return Qb(i,Hl,+r,+a)}const n=WG.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){const a=YG.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}const[i,r]=P3(n[1]||Hl,n[2]);return Qb(r,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},XG=[HG,KG],$G=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,JG=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;FG(...[XG,[VG,t=>{const e=$G.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=JG.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let n=e[3],i=e[1]||Hl;return[i,n]=P3(i,n),Qb(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const P3=(t,e)=>{const n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:Hl,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const ir={shell:"_shell_8bsnr_1",layout:"_layout_8bsnr_11",layoutThree:"_layoutThree_8bsnr_23",leftPanel:"_leftPanel_8bsnr_27",middlePanel:"_middlePanel_8bsnr_36",rightPanel:"_rightPanel_8bsnr_37",videoFrame:"_videoFrame_8bsnr_41",captions:"_captions_8bsnr_52",controls:"_controls_8bsnr_58",coursePanel:"_coursePanel_8bsnr_71",returnToPiPOverlay:"_returnToPiPOverlay_8bsnr_82",returnToPiPButton:"_returnToPiPButton_8bsnr_94"};function Zb(...t){return t.filter(Boolean).join(" ")}function QG(t){const{captionsText:e,avatarAudioPower:n=0,avatarImageSrc:i,avatarAriaLabel:r,avatarStatus:a,controlBarProps:o,courses:s,coursePanelProps:l,middlePanel:c,rightPanel:u,isCourseOutlineOpen:d,onReturnToPiP:h,className:p}=t;return f.jsx("div",{className:Zb(ir.shell,p),"data-testid":"course-dialog-content",children:f.jsxs("div",{className:Zb(ir.layout,u?ir.layoutThree:null),children:[f.jsxs("div",{className:ir.leftPanel,children:[f.jsxs("div",{className:ir.videoFrame,children:[d&&h&&f.jsx("div",{className:ir.returnToPiPOverlay,children:f.jsx("button",{type:"button",className:ir.returnToPiPButton,onClick:h,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(GB,{size:14})})}),f.jsx(hH,{className:ir.captions,text:e,children:f.jsx(x3,{audioPower:n,size:"lg",background:"flat",imageSrc:i,ariaLabel:r??"Agent avatar placeholder",status:a})})]}),f.jsx("div",{className:ir.controls,children:f.jsx(BF,{...o})})]}),u?f.jsx("div",{className:ir.rightPanel,"data-testid":"course-dialog-right-panel",children:u}):null,f.jsx("div",{className:ir.middlePanel,"data-testid":"course-dialog-middle-panel",children:c??f.jsx(YH,{...l,courses:s,className:Zb(ir.coursePanel,l==null?void 0:l.className)})})]})})}function L3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(HE,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(QG,{...r})})}const ZG=80,eW=500,tW=1e3;function nW(t,e){const{delayMs:n=0}=e??{},r=t.filter(m=>{var g;const S=(g=m.participantInfo)==null?void 0:g.identity;return(S==null?void 0:S.startsWith("agent-"))??!1}).map(m=>m.text??"").join(" ").trim(),[a,o]=w.useState(""),[s,l]=w.useState(!1),c=w.useRef(""),u=w.useRef(null),d=w.useRef(null),h=w.useRef(null),p=m=>{h.current&&(clearTimeout(h.current),h.current=null),n>0?h.current=setTimeout(()=>{o(m)},n):o(m)},b=(m,S)=>m.startsWith(S)?m.slice(S.length).trim():m.trim();return w.useEffect(()=>{if(d.current&&(clearTimeout(d.current),d.current=null),s)return;const m=b(r,c.current);p(m),m.length>ZG?(l(!0),u.current=setTimeout(()=>{l(!1),c.current=r},eW+n)):m.length>0&&(d.current=setTimeout(()=>{c.current=r,p("")},tW+n))},[r,s,n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current)},[]),{caption:a,hasCaption:a.length>0}}const kr={layout:"_layout_k1q6c_1",left:"_left_k1q6c_10",copy:"_copy_k1q6c_17",description:"_description_k1q6c_25",descriptionScroller:"_descriptionScroller_k1q6c_31",cta:"_cta_k1q6c_36",disclaimer:"_disclaimer_k1q6c_43",right:"_right_k1q6c_47",mediaPanel:"_mediaPanel_k1q6c_56",agentStill:"_agentStill_k1q6c_63",dialogWithSmallClose:"_dialogWithSmallClose_k1q6c_88"};function iW(t){const{open:e,onClose:n,onStart:i,agentName:r,agentSubtitle:a,description:o,startLabel:s="Start Now",disclaimer:l="Sessions are securely recorded for quality improvement purposes.",showCloseButton:c=!1,isStarting:u=!1,greetingVideoSrc:d}=t;return f.jsx(HE,{open:e,onClose:n,size:"large",showCloseButton:c,className:kr.dialogWithSmallClose,children:f.jsxs("div",{className:kr.layout,children:[f.jsxs("div",{className:kr.left,children:[f.jsxs("div",{className:kr.copy,children:[f.jsx(xi,{variant:"heading",children:r}),f.jsx(xi,{variant:"subheading",children:a}),f.jsx(xi,{variant:"muted",as:"div",className:kr.description,children:f.jsx(zl,{className:kr.descriptionScroller,children:f.jsx(nF,{content:o})})})]}),f.jsxs("div",{className:kr.cta,children:[f.jsx(_s,{type:"button",size:"lg",fullWidth:!0,onClick:i,isLoading:u,children:s}),f.jsx(xi,{variant:"subscript",as:"p",className:kr.disclaimer,children:l})]})]}),f.jsx(PG,{showAboveWidth:"md",children:f.jsx("div",{className:kr.right,children:f.jsx(qu,{className:kr.mediaPanel,children:f.jsx(zG,{agentName:r,greetingVideoSrc:d,className:kr.agentStill})})})})]})})}const rW={launcherPill:"_launcherPill_1fhyr_1"};function aW(t){const{label:e,onClick:n}=t;return f.jsx("button",{type:"button",className:rW.launcherPill,onClick:n,"data-testid":"ai-coach-pill",children:e})}const I3="__ama_course__",oW="ama_course",sW=3e4;function lW(t){var No,Oo,Wl,_n,xn,Mo,Do,Kr,Po,Ut,Lo,Io,jo,Bo,Yl,_,I,M,pe,Le,ve,zt,_t,xt,Xr,Ie,Uo,Kl,K3;const{sdk:e,shadowHost:n}=t,i=!!e.passivePlanUuid,r=i?((No=e.client)==null?void 0:No.selectedPlanUuid)??null:null,a=((Oo=e.client)==null?void 0:Oo.session)??null,o=!!a&&(i&&!!r||!!((Wl=e.client)!=null&&Wl.selectedPlanUuid)),[s,l]=w.useState(()=>a),[c,u]=w.useState(()=>a!=null&&a.sessionUuid?uW(a.sessionUuid):null),d=(()=>{var Y;return a?((Y=a.roomId)==null?void 0:Y.startsWith("obs-"))&&!c?"course-selection":"pip":r?"start-session":"hidden"})(),[h,p]=w.useState(()=>d),b=w.useRef(d),[m,S]=w.useState(!1),[g,y]=w.useState(!1),[x,v]=w.useState(!1),[k,T]=w.useState([]),[C,R]=w.useState(null),[A,N]=w.useState(null),[O,B]=w.useState(0),[W,L]=w.useState(!1),[K,P]=w.useState(!1),[V,X]=w.useState(0),[te,$]=w.useState(null),[z,Z]=w.useState([]),[Q,ce]=w.useState(!1),[j,ge]=w.useState(!1),[U,fe]=w.useState(()=>o),me=w.useRef(o),Rt=w.useRef(null),en=w.useRef(null),be=w.useRef(!1),qe=()=>{p(Y=>{const ne=Y==="course-selection",Te=Y==="course-outline"&&be.current;return ne||Te?(be.current=!1,L(!1),"pip"):Y})};w.useEffect(()=>{b.current=h},[h]),w.useEffect(()=>()=>{Rt.current&&clearTimeout(Rt.current)},[]);const bt=()=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null)},Je=()=>{bt(),en.current=null,N(Y=>Y===null?Y:null)},cn=Y=>{bt(),en.current=Y,N(Y),Rt.current=setTimeout(()=>{const ne=en.current===Y,Te=b.current==="course-selection";ne&&Te&&(en.current=null,N(null)),Rt.current=null},sW)},tn=dW((xn=(_n=e.client)==null?void 0:_n.product)==null?void 0:xn.widget_url_blacklist),Mt=hW(s),{audioDevices:bn}=fW();w.useEffect(()=>{s!=null&&s.sessionUuid&&j3(s.sessionUuid,c)},[c,s==null?void 0:s.sessionUuid]);const{caption:yn}=nW(z,{delayMs:0}),In=typeof navigator<"u"&&!!((Mo=navigator.mediaDevices)!=null&&Mo.getDisplayMedia),Si=((Kr=(Do=s==null?void 0:s.room)==null?void 0:Do.localParticipant)==null?void 0:Kr.isScreenShareEnabled)??!1,de=Y=>{var Ae;const ne=((Ae=e.client)==null?void 0:Ae.identity)??Y.identity,Te=typeof(ne==null?void 0:ne.first_name)=="string"?ne.first_name.trim():"",st=typeof(ne==null?void 0:ne.last_name)=="string"?ne.last_name.trim():"",xe=typeof(ne==null?void 0:ne.email)=="string"&&ne.email.trim().length>0?ne.email.trim():"";return{firstName:Te,lastName:st,email:xe}},We=Y=>{const{firstName:ne,lastName:Te,email:st}=de(Y),xe=[ne,Te,st].map(pt=>pt.trim());return xe.some(pt=>pt.length>0)?xe.join(":"):""},Ce=Y=>{const{firstName:ne,lastName:Te,email:st}=de(Y),xe=[ne,Te].filter(Boolean).join(" ").trim();return{name:xe.length>0?xe:void 0,email:st.length>0?st:void 0,screenShareSupported:In}},Qe=(()=>{if(s!=null&&s.speakingState){if(s.speakingState==="thinking")return"thinking";if(s.speakingState==="busy")return"searching"}})(),ot=((Ut=(Po=e.client)==null?void 0:Po.product)==null?void 0:Ut.avatar_image_url)||((Io=(Lo=e.client)==null?void 0:Lo.product)==null?void 0:Io.logo_url)||void 0,ki=((Bo=(jo=e.client)==null?void 0:jo.product)==null?void 0:Bo.greeting_video_url)||void 0,Ii=cW({sdk:e,session:s,isBlacklisted:tn}),Wr=!i&&Ii,q=!!(s??((Yl=e.client)==null?void 0:Yl.session)??null),ae=(s==null?void 0:s.clientType)==="meet"?We(s):"",he=(I=(_=e.client)==null?void 0:_.product)==null?void 0:I.assistant_subtitle,Pe=typeof he=="string"&&he.trim().length>0?he:"Onboarding Assistant",it=()=>B(Y=>Y+1),jn=async()=>{var ne,Te;if(!s)return;const Y=((Te=(ne=s.room)==null?void 0:ne.localParticipant)==null?void 0:Te.isScreenShareEnabled)??!1;try{Y?await s.setScreenShareEnabled(!1):await s.shareScreen()}catch(st){console.error("[obi-sdk] failed to toggle screen share",st)}finally{it()}},Ti=w.useRef(null),Bn=w.useRef(null),Un=w.useRef(!1),Wt=w.useRef({session:null,sessionUuid:null,started:!1}),ai=w.useRef(null),zn=w.useRef(new WeakMap),Vl=(Y,ne)=>{if(!ne)return;let Te=zn.current.get(Y);Te||(Te=new Set,zn.current.set(Y,Te)),Te.add(ne)},ks=Y=>{if(!Y||Ti.current===Y)return;Bn.current&&(Bn.current(),Bn.current=null);const ne=()=>it(),Te=ie=>{u(ie),Je(),Y!=null&&Y.sessionUuid&&j3(Y.sessionUuid,ie),p(Ne=>Ne==="pip"||Ne==="course-outline"?Ne:Ne==="course-selection"?(be.current=!0,"course-outline"):Ne)},st=ie=>{Je(),T(ie.courses),p("course-selection"),be.current=!1,u(null),Y!=null&&Y.sessionUuid&&B3(Y.sessionUuid),R(null),P(!1)},xe=(ie,Ne)=>{},Ae=ie=>{ie.isAgent},pt=ie=>{$(ie),X(Date.now())},nn=ie=>{if(!ie){$(null);return}$(ie),X(Date.now())};Y.on("stateChanged",ne),Y.on("speakingStateChanged",ne),Y.on("paused",ne),Y.on("unpaused",ne),Y.on("chatMessagesChanged",ne),Y.on("chatMessageReceived",Ae),Y.on("courseProgress",Te),Y.on("courseSelection",st),Y.on("transcript",xe),Y.on("screenCaptured",pt),Y.on("screenCaptureNotification",nn),Y.on("captions",Z),Y.on("introductionComplete",qe),Ti.current=Y,Bn.current=()=>{Y.off("stateChanged",ne),Y.off("speakingStateChanged",ne),Y.off("paused",ne),Y.off("unpaused",ne),Y.off("chatMessagesChanged",ne),Y.off("chatMessageReceived",Ae),Y.off("courseProgress",Te),Y.off("courseSelection",st),Y.off("transcript",xe),Y.off("screenCaptured",pt),Y.off("screenCaptureNotification",nn),Y.off("captions",Z),Y.off("introductionComplete",qe)}},Se=Y=>{var Te;return Y?((Te=Y.roomId)==null?void 0:Te.startsWith("obs-"))&&!c?"course-selection":"pip":"hidden"};w.useEffect(()=>{const Y=()=>{ai.current&&(ai.current(),ai.current=null)},ne=xe=>{if(xe.clientType!=="meet")return;if(Wt.current.session&&Wt.current.session===xe||!!Wt.current.sessionUuid&&!!xe.sessionUuid&&Wt.current.sessionUuid===xe.sessionUuid){if(Wt.current.started||ai.current)return}else Wt.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!1},Y();const pt=async()=>{Wt.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!0};const Ne=We(xe);Ne&&Vl(xe,Ne);try{await xe.sendHumanJoined(Ce(xe))}catch(Yt){console.error("[obi-sdk] failed to send human_joined handshake",Yt)}},nn=(Ne,Yt)=>{Ne==="connecting"||Ne==="error"||(Y(),pt())},ie=xe.state;if(ie&&ie!=="connecting"&&ie!=="error"){pt();return}xe.on("stateChanged",nn),ai.current=()=>{xe.off("stateChanged",nn)}},Te=xe=>{var Ae,pt,nn,ie;if(xe)if((Ae=e.client)!=null&&Ae.session)p(Se(((nn=e.client)==null?void 0:nn.session)??null));else{const Yt=!!e.passivePlanUuid,qn=Yt&&!!((pt=e.client)!=null&&pt.selectedPlanUuid);if(Yt&&!qn)return;p("start-session")}else(ie=e.client)!=null&&ie.session||p("hidden")},st=()=>it();if(e.on("showMenu",Te),e.on("configUpdated",st),e.client){e.client.session&&(l(e.client.session),ks(e.client.session),p(Se(e.client.session))),e.client.on("sessionStarted",Ae=>{l(Ae),ks(Ae),Un.current=!1,S(!1),y(!1),v(!1),P(!1);const pt=me.current;me.current=!1,pt?(be.current=!0,p("course-outline")):(be.current=!1,p(Se(Ae))),sa().track("session-started",{planId:Ae.planId}),ne(Ae)}),e.client.on("sessionResumed",Ae=>{l(Ae),ks(Ae),Un.current=!1,S(!1),y(!1),v(!1),P(!1),be.current=!1,p(Se(Ae)),ne(Ae)});const xe=()=>{var nn;const Ae=(nn=e.client)==null?void 0:nn.session;Ae!=null&&Ae.sessionUuid&&B3(Ae.sessionUuid);const pt=Ti.current;Bn.current&&(Bn.current(),Bn.current=null),l(null),Ti.current=null,S(!1),y(!1),v(!1),P(!1),fe(!1),me.current=!1,Je(),be.current=!1,Y(),Wt.current={session:null,sessionUuid:null,started:!1},pt&&zn.current.delete(pt),Un.current||p("hidden")};e.client.on("sessionStopped",xe),e.client.on("sessionShutdown",xe),e.client.on("stateChanged",it)}return()=>{e.off("showMenu",Te),e.off("configUpdated",st),Bn.current&&Bn.current(),Y()}},[e]),w.useEffect(()=>{const Y=s;if(!Y||Y.clientType!=="meet")return;const ne=Y.state;if(!ne||ne==="connecting"||ne==="error"||!ae)return;const Te=zn.current.get(Y);Te!=null&&Te.has(ae)||(Vl(Y,ae),Y.sendHumanJoined(Ce(Y)).catch(st=>console.error("[obi-sdk] failed to send human_joined update",st)))},[In,ae,s,s==null?void 0:s.state]),w.useLayoutEffect(()=>{var Y,ne;(ne=(Y=e.client)==null?void 0:Y.product)!=null&&ne.primary_color&&n.style.setProperty("--obi-color-primary",e.client.product.primary_color)},[(pe=(M=e.client)==null?void 0:M.product)==null?void 0:pe.primary_color,n]),w.useEffect(()=>{if(i&&!tn&&!q){if(!r){p("hidden");return}p("start-session")}},[q,i,tn,r]),w.useEffect(()=>{var nn,ie;ge(!1);const Y=(nn=e.client)==null?void 0:nn.api,ne=(ie=e.client)==null?void 0:ie.product;if(!Y||!ne)return;const Te=(ne==null?void 0:ne.uuid)??(ne==null?void 0:ne.product_uuid),st=(ne==null?void 0:ne.slug)??(ne==null?void 0:ne.product_slug),xe=(ne==null?void 0:ne.id)??(ne==null?void 0:ne.product_id),Ae={};if(Te?Ae.product_uuid=Te:st?Ae.product_slug=st:xe!=null&&(Ae.product_id=String(xe)),Object.keys(Ae).length===0)return;let pt=!1;return Y.getFeatureFlags(Ae).then(Ne=>{if(pt)return;const qn=((Ne==null?void 0:Ne.data)??[]).find(ny=>(ny==null?void 0:ny.slug)===oW);if(!qn)return;const{user_enabled:oi,product_enabled:Hn,global_enabled:Tr}=qn;let ty=!!Tr;Hn!=null&&(ty=!!Hn),oi!=null&&(ty=!!oi),ge(ty)}).catch(Ne=>{console.error("[obi-sdk] failed to load AMA feature flag",Ne)}),()=>{pt=!0}},[(Le=e.client)==null?void 0:Le.api,(ve=e.client)==null?void 0:ve.product]);const Fn=(c==null?void 0:c.stepNames.map((Y,ne)=>({id:`step-${ne+1}`,title:Y})))??[],Gl=(c==null?void 0:c.currentStep)??null,Ao=!0,Yr=(Y,ne)=>{s==null||s.say(`Can we jump to the section about ${ne.title}?`)};if(tn||i&&!r&&!q)return null;if(h==="hidden")return Wr?f.jsx(aW,{label:Pe,onClick:()=>{e.updateShowMenu(!0)}}):null;if(h==="start-session"){const Y=(zt=e.client)==null?void 0:zt.product,ne=(_t=e.client)==null?void 0:_t.selectedPlan,Te=i&&!!r,st=i&&!!r||!!((xt=e.client)!=null&&xt.selectedPlanUuid),xe=(Y==null?void 0:Y.agent_name)||"Obi",Ae=(Y==null?void 0:Y.assistant_subtitle)||"AI Assistant",pt=Te&&(ne==null?void 0:ne.description)||(Y==null?void 0:Y.assistant_description)||"";return f.jsx(iW,{open:!0,onClose:()=>{S(!1),p("hidden")},onStart:()=>{me.current=st,fe(st),S(!0),e.startSession({withMicrophone:!0})},agentName:xe,agentSubtitle:Ae,description:pt,showCloseButton:!1,startLabel:"Start Session",isStarting:m,greetingVideoSrc:ki})}if(h==="course-selection"){const Y=(Xr=s==null?void 0:s.roomId)==null?void 0:Xr.startsWith("obs-"),ne=((Ie=e.client)==null?void 0:Ie.plans)||[],Te=Y&&k.length>0,st=Te?k.slice().sort((ie,Ne)=>ie.order!==void 0&&Ne.order!==void 0?ie.order-Ne.order:ie.order!==void 0?-1:Ne.order!==void 0?1:ie.name.localeCompare(Ne.name)).map(ie=>({id:ie.uuid,title:ie.name,description:ie.description||ie.overview||"",status:ie.completed?"completed":"available",duration:typeof ie.duration=="number"?`${ie.duration} min`:ie.duration})):ne.map(ie=>{var Ne,Yt;return{id:ie.uuid,title:ie.name,description:ie.description,status:(Yt=(Ne=e.client)==null?void 0:Ne.planIsCompleted)!=null&&Yt[ne.indexOf(ie)]?"completed":"available",duration:ie.estimated_duration?`${ie.estimated_duration} min`:void 0}});Te&&j&&st.push({id:I3,title:"Ask me anything",description:"Ask questions before choosing a course.",status:"available"});const xe=(s==null?void 0:s.languageCodes)||[],Ae=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,pt={audioDevices:bn,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:Si,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:In,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),it()},onMicToggle:async()=>{s!=null&&s.isMicShared?g?(await s.unmuteMicrophone(),y(!1)):(await s.muteMicrophone(),y(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{v(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:jn,languages:xe,selectedLanguage:Ae,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...x?{screenShareButtonVariant:"compact"}:{}},nn=x?f.jsx(N3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((Uo=s==null?void 0:s.room)==null?void 0:Uo.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ne,Yt,qn,oi;if(s){const Hn=Date.now();s.appendChatMessage({timestamp:Hn,message:ie,from:{identity:((Yt=(Ne=s.room)==null?void 0:Ne.localParticipant)==null?void 0:Yt.identity)??null,name:((oi=(qn=s.room)==null?void 0:qn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>v(!1)}):void 0;return f.jsx(L3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:st,controlBarProps:pt,coursePanelProps:{selectedCourseIds:C?[C]:void 0,loadingCourseId:A,onCourseToggle:async ie=>{var Ne,Yt,qn,oi;if(!en.current)if(Te){if(ie===I3){cn(ie),R(ie);try{await((Ne=s==null?void 0:s.say)==null?void 0:Ne.call(s,"Please start an AMA session."))}catch(Tr){console.error("[obi-sdk] failed to start AMA course",Tr),Je(),R(null)}return}const Hn=k.find(Tr=>Tr.uuid===ie);if(Hn){cn(ie),R(ie);try{await((Yt=s==null?void 0:s.say)==null?void 0:Yt.call(s,`I'd like to take the ${Hn.name} course.`))}catch(Tr){console.error("[obi-sdk] failed to send course selection",Tr),Je(),R(null)}}}else{const Hn=ne.find(Tr=>Tr.uuid===ie);if(Hn){cn(ie),(qn=e.client)==null||qn.selectPlan(Hn),p("pip");try{await((oi=s==null?void 0:s.say)==null?void 0:oi.call(s,`I'd like to take the ${Hn.name} course.`))}catch(Tr){console.error("[obi-sdk] failed to send course selection",Tr),p("course-selection"),Je()}}}}},rightPanel:nn,avatarImageSrc:ot,avatarAudioPower:Mt,avatarStatus:Qe,captionsText:yn})}if(h==="course-outline"){const Y=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Te={audioDevices:bn,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:Si,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:In,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),it()},onMicToggle:async()=>{s!=null&&s.isMicShared?g?(await s.unmuteMicrophone(),y(!1)):(await s.muteMicrophone(),y(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{v(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:jn,languages:Y,selectedLanguage:ne,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...x?{screenShareButtonVariant:"compact"}:{}},st=x?f.jsx(N3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((Kl=s==null?void 0:s.room)==null?void 0:Kl.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ne,Yt,qn,oi;if(s){const Hn=Date.now();s.appendChatMessage({timestamp:Hn,message:ie,from:{identity:((Yt=(Ne=s.room)==null?void 0:Ne.localParticipant)==null?void 0:Yt.identity)??null,name:((oi=(qn=s.room)==null?void 0:qn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>v(!1)}):void 0,xe=!!c,Ae=!U,pt=async()=>{if(!(!(s!=null&&s.endCourse)||K)){P(!0);try{await s.endCourse("back_to_courses")}catch(ie){console.error("[obi-sdk] failed to end course",ie),P(!1)}}},nn=f.jsx(RV,{steps:Fn,currentStep:Gl,hideTrailingConclusionStep:Ao,onStepClick:Yr,showBackToCourses:Ae,...Ae?{onBackToCoursesConfirm:pt,backToCoursesDisabled:K}:{}});return f.jsx(L3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:Te,middlePanel:nn,rightPanel:st,isCourseOutlineOpen:xe,onReturnToPiP:xe?()=>p("pip"):void 0,avatarImageSrc:ot,avatarAudioPower:Mt,avatarStatus:Qe,captionsText:yn})}if(h==="pip"){const Y=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Te=280,st=250,xe=16,Ae={x:window.innerWidth-Te-xe,y:window.innerHeight-st-xe},pt={isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isChatOpen:x,isScreenShareActive:Si,onMicToggle:async()=>{s!=null&&s.isMicShared?g?(await s.unmuteMicrophone(),y(!1)):(await s.muteMicrophone(),y(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>v(ie=>!ie),onScreenShareToggle:jn,onLeave:()=>{s==null||s.stop()},languages:Y,selectedLanguage:ne,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0},nn=x?f.jsx($V,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((K3=s==null?void 0:s.room)==null?void 0:K3.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ne,Yt,qn,oi;if(s){const Hn=Date.now();s.appendChatMessage({timestamp:Hn,message:ie,from:{identity:((Yt=(Ne=s.room)==null?void 0:Ne.localParticipant)==null?void 0:Yt.identity)??null,name:((oi=(qn=s.room)==null?void 0:qn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(ie)}},testId:"pip-chat-panel"}):void 0;return f.jsx(sH,{initialPosition:Ae,onExit:()=>{be.current=!1,p("course-outline")},controlBarProps:pt,isCourseOutlineSelected:W&&!!c,onCourseOutlineToggle:c?()=>{L(ie=>!ie)}:void 0,isCaptionsEnabled:Q,onCaptionsToggle:()=>ce(ie=>!ie),courseOutline:c?{steps:Fn,currentStep:Gl,onStepClick:Yr,hideTrailingConclusionStep:Ao}:void 0,messagesPanel:nn,avatarFallbackProps:{audioPower:Mt,imageSrc:ot,status:Qe,captionsText:yn},screenshotUrl:te,cameraShotTrigger:V})}return null}function cW(t){var l,c;const{sdk:e,session:n,isBlacklisted:i}=t;if(i)return!1;const r=e.client;if(!r||r.state!=="ready"||(n??r.session??null))return!1;let o=e.isActive;return((l=r.product)==null?void 0:l.name)==="Canibuild"&&(o=!0),!(!o||(e.widgetDisplay??((c=r.product)==null?void 0:c.widget_display))==="invisible")}function j3(t,e){if(!t)return;const n=`obi-widget-course-progress-${t}`;if(e===null){localStorage.removeItem(n);return}try{const i={...e,timestamp:Date.now()};localStorage.setItem(n,JSON.stringify(i))}catch(i){console.error("[obi-sdk] failed to save course progress",i)}}function uW(t){if(!t)return null;const e=`obi-widget-course-progress-${t}`;try{const n=localStorage.getItem(e);if(!n)return null;const i=JSON.parse(n);if(typeof i.currentStep!="number"||typeof i.totalSteps!="number"||!Array.isArray(i.stepNames))return console.warn("[obi-sdk] invalid course progress data, clearing",i),localStorage.removeItem(e),null;const r=24*60*60*1e3;return i.timestamp&&Date.now()-i.timestamp>r?(localStorage.removeItem(e),null):{currentStep:i.currentStep,totalSteps:i.totalSteps,stepNames:i.stepNames}}catch(n){return console.error("[obi-sdk] failed to load course progress",n),localStorage.removeItem(e),null}}function B3(t){if(!t)return;const e=`obi-widget-course-progress-${t}`;try{localStorage.removeItem(e)}catch(n){console.error("[obi-sdk] failed to clear course progress",n)}}function dW(t){const[e,n]=w.useState(()=>ys(t));return w.useEffect(()=>{n(ys(t))},[t]),w.useEffect(()=>{const i=()=>{n(ys(t))};return window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[t]),e}function hW(t){const[e,n]=w.useState(0),i=w.useRef(null),r=w.useRef(0),a=w.useRef(0);return w.useEffect(()=>{if(!t){n(0),r.current=0,a.current=0;return}const o=()=>{const s=t.audioSpectrum();let l=0;if(s&&s.length>0){let b=0;for(let m=0;m<s.length;m++)b+=s[m];l=Math.min(1,Math.max(0,b/s.length))}const c=r.current,d=l>=c?.7:.15,h=c*d+l*(1-d);r.current=h;const p=h<.05?0:Math.min(1,h);Math.abs(p-a.current)>.01&&(a.current=p,n(p)),i.current=requestAnimationFrame(o)};return i.current=requestAnimationFrame(o),()=>{i.current&&cancelAnimationFrame(i.current)}},[t]),e}function fW(){const[t,e]=w.useState({audioDevices:[]});return w.useEffect(()=>{var i;if(typeof navigator>"u"||!((i=navigator.mediaDevices)!=null&&i.enumerateDevices))return;const n=()=>{navigator.mediaDevices.enumerateDevices().then(r=>{e({audioDevices:r.filter(a=>a.kind==="audioinput")})})};return n(),navigator.mediaDevices.addEventListener("devicechange",n),()=>navigator.mediaDevices.removeEventListener("devicechange",n)},[]),t}function U3(){const t=window.location.hostname;return t.endsWith(".clinic1.com")||t==="getcor.ai"||t==="getcor.io"||t==="localhost"||t==="127.0.0.1"||t==="::1"}const z3=U3();function pW(t){if(document.querySelector("#obi-host")||document.querySelector("obi-widget"))return;mW();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const n=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",n.appendChild(i);const r=new CSSStyleSheet;r.replaceSync(MB);const a=[r];if(z3){const s=new CSSStyleSheet;s.replaceSync(AB),a.push(s);const l=new CSSStyleSheet;l.replaceSync(OB),a.push(l)}else{const s=new CSSStyleSheet;s.replaceSync(NB),a.push(s)}n.adoptedStyleSheets=a;const o=RB.createRoot(i);z3?o.render(f.jsx(lW,{sdk:t,shadowHost:e})):o.render(f.jsx(LB,{sdk:t,shadowHost:e})),console.log("[obi-sdk] widget mounted")}function mW(){F3("https://fonts.cdnfonts.com/css/satoshi"),F3("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function F3(t){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}const q3="49206C6F7665204F6269_session",H3="obi-url-params",ey="obi-client-heartbeat",gW=5e3,V3=4e4,G3=15e3;function vW(){return U3()?"meet":"sdk"}class bW extends Ep{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.heartbeatInterval=null,this.dispatchCommand=(n,i)=>{var r,a,o,s,l;switch(this.commandLog.push({commandType:n,args:i}),n){case"update":this.updateConfig(i);break;case"startSession":{if(i!=null&&i.planUuid){const c=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",i);return}(o=(a=this.client)==null?void 0:a.selectPlan)==null||o.call(a,c)}this.updateActive(!0);break}case"stopSession":(l=(s=this.client)==null?void 0:s.stopSession)==null||l.call(s);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:n,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 n=null;const i=vW(),r=this.load();if(r)try{const a=this.parsePersistedSessionMetadata(r),o=a&&this.isPersistedSessionStale(a);o!=null&&o.stale&&a?(this.trackStaleSessionDiscard(a.sessionUuid,o.ageMs,o.reason),this.clearCachedClient()):(n=wh.deserialise(r,e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),n?this._resumed=!0:this.clearCachedClient())}catch(a){console.error("[obi] error loading cached client",a),this.clearCachedClient()}n||(n=new wh(e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=n,this.client.session&&this.startHeartbeat(this.client.session.sessionUuid),this.client.on("stateChanged",a=>{var o,s,l,c,u,d,h,p,b,m;a==="ready"&&this.updateConfig({isActive:((o=window==null?void 0:window.obiWidgetConfig)==null?void 0:o.isActive)??((s=this.client)==null?void 0:s.showWidget),primaryColour:((c=(l=this.client)==null?void 0:l.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((u=window==null?void 0:window.obiWidgetConfig)==null?void 0:u.widgetDisplay)||((h=(d=this.client)==null?void 0:d.product)==null?void 0:h.widget_display)||"regular",completedWidgetDisplay:((p=window==null?void 0:window.obiWidgetConfig)==null?void 0:p.completedWidgetDisplay)||((m=(b=this.client)==null?void 0:b.product)==null?void 0:m.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{var a,o;this.save(),this.startHeartbeat(((o=(a=this.client)==null?void 0:a.session)==null?void 0:o.sessionUuid)||null),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{this.clearCachedClient(),this.passivePlanUuid=null}),this.client.on("sessionShutdown",()=>{this.clearCachedClient()}),this.client.on("trackEvent",(a,o)=>{}),this.client.session&&(this.client.session.isPaused,this.client.resumeSession(a=>{a.on("stateChanged",o=>{o!=="disconnecting"&&o!=="disconnected"&&o!=="error"&&o!=="connecting"&&this.save()}),a.on("paused",()=>{this.save()}),a.on("unpaused",()=>{this.save()})}))}_maybeActOnServerEngagement(){var s;const e=this.client;if(!e||e.state!=="ready")return;const n=e.product,i=(s=e.engagement)==null?void 0:s.style;if(!i||n&&ys(n.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],a=e.planIsCompleted||[],o=r.length>0&&a.filter(Boolean).length===r.length;if(!(r.length===0||o)){if(i==="modal"){const l=a.findIndex(u=>!u),c=l>=0?r[l]:null;c&&e.selectPlan(c)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{sa().track("engagement-prompt-shown",{style:i})}catch{}}}async initialise(e={}){var n;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((n=window==null?void 0:window.obiWidgetConfig)==null?void 0:n.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){e.apiKey!==void 0&&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),e.user!==void 0&&await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var n;e===void 0||e==((n=this.client)==null?void 0:n.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 n=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:n,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(a=>{console.error("[obi] error initialising client",a),this.emit("error",a)}),e!=null&&e.email&&sa().identify((e==null?void 0:e.email)||"",n)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var n,i,r;await((r=(i=(n=this.client)==null?void 0:n.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(e){await this.client.startSession(this.client.selectedPlanUuid||null,n=>{n.on("stateChanged",i=>{i!=="disconnecting"&&i!=="disconnected"&&i!=="error"&&i!=="connecting"&&this.save()}),n.on("paused",()=>{this.save()}),n.on("unpaused",()=>{this.save()})},e)}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(n=>{try{this.dispatchCommand(n[0],n[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(H3)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((a,o)=>{e[o]=a});const n=e[q3];if(!n)return null;const i=new URL(window.location.href);i.searchParams.delete(q3),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(H3),this.passivePlanUuid=n}mountWidget(){pW(this)}showMessage(e,n){try{this.emit("showMessage",{text:e,autoCloseMs:n==null?void 0:n.autoCloseMs})}catch{}}async captureScreen(){try{await xO(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await mR(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 ZN(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var n;const e=((n=this.client)==null?void 0:n.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}parsePersistedSessionMetadata(e){const n=JSON.parse(e),i=this.parseTimestampMs(n.serialisedAt);if(!n.session)return null;let r=null;if(typeof n.session=="string")try{r=JSON.parse(n.session)}catch{return null}else typeof n.session=="object"&&(r=n.session);return r?{sessionUuid:typeof r.sessionUuid=="string"?r.sessionUuid:null,startedAtMs:this.parseTimestampMs(r.startedAt),serialisedAtMs:i}:null}isPersistedSessionStale(e){const n=Date.now(),i=this.readHeartbeat();if(i&&i.sessionUuid&&e.sessionUuid&&i.sessionUuid===e.sessionUuid){const s=Math.max(0,n-i.updatedAtMs);return{stale:s>V3,reason:s>V3?"heartbeat-stale":"heartbeat-fresh",ageMs:s}}const r=[e.serialisedAtMs,e.startedAtMs].filter(s=>typeof s=="number"&&Number.isFinite(s));if(r.length===0)return{stale:!0,reason:"fallback-missing-timestamps",ageMs:null};const a=Math.max(...r),o=Math.max(0,n-a);return{stale:o>G3,reason:o>G3?"fallback-too-old":"fallback-recent",ageMs:o}}parseTimestampMs(e){if(typeof e=="number")return e;if(typeof e=="string"){const n=Number(e);if(!Number.isNaN(n))return n;const i=Date.parse(e);return Number.isFinite(i)?i:null}return null}readHeartbeat(){const e=localStorage.getItem(ey);if(!e)return null;try{return JSON.parse(e)}catch{return null}}trackStaleSessionDiscard(e,n,i){try{sa().track("stale-session-discarded",{sessionUuid:e||void 0,ageMs:n??void 0,reason:i})}catch{}}startHeartbeat(e){if(!e){this.clearHeartbeat();return}this.stopHeartbeat(),this.writeHeartbeat(e),this.heartbeatInterval=setInterval(()=>{this.writeHeartbeat(e)},gW)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}writeHeartbeat(e){const n={sessionUuid:e,updatedAtMs:Date.now()};localStorage.setItem(ey,JSON.stringify(n))}clearHeartbeat(){this.stopHeartbeat(),localStorage.removeItem(ey)}clearCachedClient(){this.clearHeartbeat(),localStorage.removeItem("obi-client")}}async function W3(t,e){let n;try{n=window}catch{console.warn("[obi] no window object found"),n={}}return yW({appToken:t,window:n,init:e})}async function yW({appToken:t,window:e,init:n}){var a,o;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}n&&n(),t||(t=(a=e==null?void 0:e.obiWidgetConfig)==null?void 0:a.apiKey);let i;try{i=((o=e.ObiSDK)==null?void 0:o.q)||[]}catch{i=[]}const r=new bW(t);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function Y3(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{W3(void 0,Y3)}):W3(void 0,Y3)})();