obi-sdk 0.19.59 → 0.19.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -39,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 gh(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 vh(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 w8=Object.freeze({__proto__:null,removeExtmapAllowMixed:Km,shimAddIceCandidateNullOrEmpty:gh,shimConnectionState:Ym,shimMaxMessageSize:ph,shimParameterlessSetLocalDescription:vh,shimRTCIceCandidate:fh,shimRTCIceCandidateRelayProtocol:Wm,shimSendThrowTypeError:mh});function C8(){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=Mx,i=x8(t),r={browserDetails:i,commonShim:w8,extractVersion:_c,disableLog:y8,disableWarnings:_8,sdp:T8};switch(i.browser){case"chrome":if(!Gx||!Hm||!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=Gx,gh(t,i),vh(t),jx(t,i),Bx(t),Hm(t,i),Ux(t),Hx(t,i),zx(t),Fx(t),Vx(t,i),fh(t),Wm(t),Ym(t),ph(t,i),mh(t),Km(t,i);break;case"firefox":if(!nS||!Vm||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=nS,gh(t,i),vh(t),Wx(t,i),Vm(t,i),Yx(t),$x(t),Kx(t),Xx(t),Jx(t),Qx(t),Zx(t),eS(t),tS(t),fh(t),Ym(t),ph(t,i),mh(t);break;case"safari":if(!hS||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=hS,gh(t,i),vh(t),lS(t),uS(t),aS(t),iS(t),rS(t),cS(t),oS(t),dS(t),fh(t),Wm(t),ph(t,i),mh(t),Km(t,i);break;default:n("Unsupported browser!");break}return r}C8({window:typeof window>"u"?void 0:window});const E8=/version\/(\d+(\.?_?\d+)+)/i;let Xm;function di(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(Xm===void 0||e){const i=R8.find(r=>{let{test:a}=r;return a.test(n)});Xm=i==null?void 0:i.describe(n)}return Xm}const R8=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:bh(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:$m(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:bh(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:$m(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:bh(E8,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:$m(t)}}}];function bh(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 $m(t){return t.includes("mac os")?bh(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var A8="2.16.1";const N8=A8,O8=16;class Pr extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var Ct;(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"})(Ct||(Ct={}));class _e extends Pr{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Ct[n]}static notAllowed(e,n,i){return new _e(e,Ct.NotAllowed,n,i)}static timeout(e){return new _e(e,Ct.Timeout)}static leaveRequest(e,n){return new _e(e,Ct.LeaveRequest,void 0,n)}static internal(e,n){return new _e(e,Ct.InternalError,void 0,n)}static cancelled(e){return new _e(e,Ct.Cancelled)}static serverUnreachable(e,n){return new _e(e,Ct.ServerUnreachable,n)}static websocket(e,n,i){return new _e(e,Ct.WebSocket,n,i)}}class Jm extends Pr{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class ia extends Pr{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class M8 extends Pr{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class sn extends Pr{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Qm extends Pr{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class mS extends Pr{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class gS extends Pr{constructor(e,n){super(15,e),this.name="SignalRequestError",this.reason=n,this.reasonName=typeof n=="string"?n:Um[n]}}var Wn;(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"})(Wn||(Wn={}));class qi extends Pr{constructor(e,n){super(16,e),this.name="DataStreamError",this.reason=n,this.reasonName=Wn[n]}}class Fs extends Pr{constructor(e){super(18,e),this.name="SignalReconnectError"}}var yh;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(yh||(yh={})),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}(yh||(yh={}));class Rn{}Rn.setTimeout=function(){return setTimeout(...arguments)},Rn.setInterval=function(){return setInterval(...arguments)},Rn.clearTimeout=function(){return clearTimeout(...arguments)},Rn.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 ae;(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"})(ae||(ae={}));var ie;(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"})(ie||(ie={}));var te;(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"})(te||(te={}));function D8(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 ft{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 P8=["vp8","h264"],L8=["vp8","h264","vp9","av1","h265"];function I8(t){return!!P8.find(e=>e===t)}const j8=I8;var vS;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(vS||(vS={}));var Zm;(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}})(Zm||(Zm={}));const xc={h90:new ft(160,90,9e4,20),h180:new ft(320,180,16e4,20),h216:new ft(384,216,18e4,20),h360:new ft(640,360,45e4,20),h540:new ft(960,540,8e5,25),h720:new ft(1280,720,17e5,30),h1080:new ft(1920,1080,3e6,30),h1440:new ft(2560,1440,5e6,30),h2160:new ft(3840,2160,8e6,30)},eg={h120:new ft(160,120,7e4,20),h180:new ft(240,180,125e3,20),h240:new ft(320,240,14e4,20),h360:new ft(480,360,33e4,20),h480:new ft(640,480,5e5,20),h540:new ft(720,540,6e5,25),h720:new ft(960,720,13e5,30),h1080:new ft(1440,1080,23e5,30),h1440:new ft(1920,1440,38e5,30)},tg={h360fps3:new ft(640,360,2e5,3,"medium"),h360fps15:new ft(640,360,4e5,15,"medium"),h720fps5:new ft(1280,720,8e5,5,"medium"),h720fps15:new ft(1280,720,15e5,15,"medium"),h720fps30:new ft(1280,720,2e6,30,"medium"),h1080fps15:new ft(1920,1080,25e5,15,"medium"),h1080fps30:new ft(1920,1080,5e6,30,"medium"),original:new ft(0,0,7e6,30,"medium")};function bS(t,e,n){var i,r,a,o;const{optionsWithoutProcessor:s,audioProcessor:l,videoProcessor:c}=xS(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&&(ng(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&&(ng(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 ng(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function ig(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":ng(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 yS(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=_S();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 An(n),r.getByteTimeDomainData(o);const l=o.some(c=>c!==128&&c!==0);return i.close(),!l}return!1}()})}function _S(){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 B8(t){return t==="audioinput"?F.Source.Microphone:t==="videoinput"?F.Source.Camera:F.Source.Unknown}function rg(t){return t===F.Source.Microphone?"audioinput":t===F.Source.Camera?"videoinput":void 0}function U8(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,Qo()?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 Sc(t){return t.split("/")[1].toLowerCase()}function z8(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new Pm({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 F8(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function q8(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 xS(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:D8(e)}}function H8(t){switch(t){case Zt.CAMERA:return F.Source.Camera;case Zt.MICROPHONE:return F.Source.Microphone;case Zt.SCREEN_SHARE:return F.Source.ScreenShare;case Zt.SCREEN_SHARE_AUDIO:return F.Source.ScreenShareAudio;default:return F.Source.Unknown}}function SS(t,e){return t.width*t.height<e.width*e.height}function V8(t,e){var n;return(n=t.layers)===null||n===void 0?void 0:n.find(i=>i.quality===e)}const G8=5e3,kc=[];var Ti;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(Ti||(Ti={}));class F extends Dr.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=F.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(),G8):this.handleAppVisibilityChanged()},this.log=ta((r=i.loggerName)!==null&&r!==void 0?r:ur.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=F.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===F.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===F.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(kc.forEach(a=>{a.parentElement===null&&!e&&(e=a)}),e&&kc.splice(kc.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),qs(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(a=>a.kind==="audio");return e.play().then(()=>{this.emit(r?te.AudioPlaybackStarted:te.VideoPlaybackStarted)}).catch(a=>{a.name==="NotAllowedError"?this.emit(r?te.AudioPlaybackFailed:te.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(te.ElementAttached,e),e}detach(e){try{if(e){Hs(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(te.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Hs(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(te.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=ta(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),kc.forEach(i=>{i.parentElement||(n=!1)}),n&&kc.push(e)}}handleAppVisibilityChanged(){return E(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===F.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){hi()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){hi()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function qs(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)),(!Qo()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(Qo()||Jo())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Hs(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 sr.AUDIO;case e.Video:return sr.VIDEO;default:return sr.DATA}}t.kindToProto=r;function a(c){switch(c){case sr.AUDIO:return e.Audio;case sr.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=a;function o(c){switch(c){case n.Camera:return Zt.CAMERA;case n.Microphone:return Zt.MICROPHONE;case n.ScreenShare:return Zt.SCREEN_SHARE;case n.ScreenShareAudio:return Zt.SCREEN_SHARE_AUDIO;default:return Zt.UNKNOWN}}t.sourceToProto=o;function s(c){switch(c){case Zt.CAMERA:return n.Camera;case Zt.MICROPHONE:return n.Microphone;case Zt.SCREEN_SHARE:return n.ScreenShare;case Zt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=s;function l(c){switch(c){case Mm.ACTIVE:return i.Active;case Mm.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=l})(F||(F={}));const W8="|",kS="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Y8(t){const e=t.split(W8);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function An(t){return E(this,void 0,void 0,function*(){return new Promise(e=>Rn.setTimeout(e,t))})}function ag(){return"addTransceiver"in RTCPeerConnection.prototype}function og(){return"addTrack"in RTCPeerConnection.prototype}function K8(){if(!("getCapabilities"in RTCRtpSender)||Qo()||Jo())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 X8(){if(!("getCapabilities"in RTCRtpSender)||Jo())return!1;if(Qo()){const n=di();if(n!=null&&n.version&&Ir(n.version,"16")<0||(n==null?void 0:n.os)==="iOS"&&(n!=null&&n.osVersion)&&Ir(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 dr(t){return t==="av1"||t==="vp9"}function sg(t){return!document||Tc()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function $8(){return typeof RTCPeerConnection>"u"?!1:ag()||og()}function Jo(){var t;return((t=di())===null||t===void 0?void 0:t.name)==="Firefox"}function TS(){const t=di();return!!t&&t.name==="Chrome"&&t.os!=="iOS"}function Qo(){var t;return((t=di())===null||t===void 0?void 0:t.name)==="Safari"}function Tc(){const t=di();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function J8(){const t=di();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Ir(t.osVersion,"17")>=0}function Q8(t){return t||(t=di()),(t==null?void 0:t.name)==="Safari"&&Ir(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Ir(t.osVersion,"18.3")>0}function wS(){var t,e;return hi()?(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 Z8(){const t=di(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&Ir(t.osVersion,e)>=0?!0:t.name==="Safari"&&Ir(t.version,e)>=0}function hi(){return typeof document<"u"}function Lr(){return navigator.product=="ReactNative"}function Vs(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function lg(t){return Vs(t)?t.hostname.split(".")[0]:null}function CS(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ES(){if(!Lr())return;let t=CS();if(t)return t.platform}function RS(){if(hi())return window.devicePixelRatio;if(Lr()){let t=CS();if(t)return t.devicePixelRatio}return 1}function Ir(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 eD(t){for(const e of t)e.target.handleResize(e)}function tD(t){for(const e of t)e.target.handleVisibilityChanged(e)}let cg=null;const AS=()=>(cg||(cg=new ResizeObserver(eD)),cg);let ug=null;const NS=()=>(ug||(ug=new IntersectionObserver(tD,{root:null,rootMargin:"0px"})),ug);function nD(){var t;const e=new cx({sdk:ux.JS,protocol:O8,version:N8});return Lr()&&(e.os=(t=ES())!==null&&t!==void 0?t:""),e}function OS(){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 wc;function dg(){if(!wc){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(),[wc]=i.stream.getAudioTracks(),!wc)throw Error("Could not get empty media stream audio track");wc.enabled=!1}return wc.clone()}class Hi{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 iD(t){return L8.includes(t)}function Va(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 rD(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function Cc(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function aD(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 oD(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 MS(t){switch(t.reason){case Ct.LeaveRequest:return t.context;case Ct.Cancelled:return lr.CLIENT_INITIATED;case Ct.NotAllowed:return lr.USER_REJECTED;case Ct.ServerUnreachable:return lr.JOIN_FAILURE;default:return lr.UNKNOWN_REASON}}function _h(t){return t!==void 0?Number(t):void 0}function Zo(t){return t!==void 0?BigInt(t):void 0}function Gs(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function jr(t){return!!t&&t.kind==F.Kind.Audio}function Ga(t){return!!t&&t.kind==F.Kind.Video}function Wa(t){return Gs(t)&&Ga(t)}function ra(t){return Gs(t)&&jr(t)}function hg(t){return!!t&&!t.isLocal}function sD(t){return!!t&&!t.isLocal}function fg(t){return hg(t)&&Ga(t)}function lD(t){return t.isLocal}function cD(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 uD(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 dD(t,e){const n=new URL(rD(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),PS(n,"rtc")}function hD(t){const e=new URL(Cc(t));return PS(e,"validate")}function DS(t){return t.endsWith("/")?t:"".concat(t,"/")}function PS(t,e){return t.pathname="".concat(DS(t.pathname)).concat(e),t.toString()}function LS(t){if(typeof t=="string")return gx.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return gx.fromBinary(new Uint8Array(t));throw new Error("could not decode websocket message: ".concat(typeof t))}function fD(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 pD=10,Ec="lk_e2ee",mD={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:pD,keyringSize:16};var Ya;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(Ya||(Ya={}));var IS;(function(t){t.KeyRatcheted="keyRatcheted"})(IS||(IS={}));var Ka;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(Ka||(Ka={}));var jS;(function(t){t.Error="cryptorError"})(jS||(jS={}));function gD(){return vD()||pg()}function pg(){return typeof window.RTCRtpScriptTransform<"u"}function vD(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function bD(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 nx({value:t.value})}class IW extends Dr.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({},mD),e),this.on(Ya.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(Ya.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(Ya.RatchetRequest,e,n)}}var BS;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(BS||(BS={}));class yD extends Dr.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(Ka.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(Ka.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(Ka.ParticipantEncryptionStatusChanged,s.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(Ya.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(Ka.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(!gD())throw new Jm("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:p8.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(ie.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(J.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==on.NONE,r.identity)),e.on(J.ConnectionStateChanged,i=>{i===Je.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{this.setParticipantCryptorEnabled(a.trackInfo.encryption!==on.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(ae.LocalSenderCreated,(i,r)=>E(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(ae.LocalTrackPublished,i=>{if(!Ga(i.track)||!Tc())return;const r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:Sc(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r)}),n.on(Ya.SetKey,i=>this.postKey(i)).on(Ya.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 Hi;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 Hi;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"?Sc(i.mimeType):void 0)}}setupE2EESender(e,n){if(!Gs(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(pg()&&!TS()){const a={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(Ec 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:Ec in e}};this.worker.postMessage(s,[o,a])}e[Ec]=!0}})}handleSender(e,n,i){var r;if(!(Ec 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(pg()&&!TS()){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[Ec]=!0}}}const _D=500,xD=15e3;class Ws{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Ws),this._instance}addFailedConnectionAttempt(e){var n;const i=new URL(e),r=lg(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,An(Math.min(_D*Math.pow(2,a),xD)))}getBackOffPromise(e){const n=new URL(e),i=n&&lg(n);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const n=new URL(e),i=n&&lg(n);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Ws._instance=null;const mg="default";class gn{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new gn),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=gn.userMediaPromiseMap)===null||a===void 0?void 0:a.size)>0){Ee.debug("awaiting getUserMedia promise");try{n?yield gn.userMediaPromiseMap.get(n):yield Promise.all(gn.userMediaPromiseMap.values())}catch{Ee.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Qo()&&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!==mg)return n;const r=yield this.getDevices(e),a=r.find(s=>s.deviceId===mg);if(!a){Ee.warn("could not reliably determine default device");return}const o=r.find(s=>s.deviceId!==mg&&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?gn.userMediaPromiseMap.has(e):gn.userMediaPromiseMap.size>0}}gn.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],gn.userMediaPromiseMap=new Map;var Rc;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Rc||(Rc={}));class SD{constructor(){this.pendingTasks=new Map,this.taskMutex=new Vn,this.nextTaskIndex=0}run(e){return E(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Rc.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=Rc.RUNNING,yield e()}finally{n.status=Rc.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 kD{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([An(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 TD=["syncState","trickle","offer","answer","simulate","leave"];function wD(t){const e=TD.indexOf(t.case)>=0;return Ee.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var gt;(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"})(gt||(gt={}));const CD=250;class gg{get currentState(){return this.state}get isDisconnected(){return this.state===gt.DISCONNECTING||this.state===gt.DISCONNECTED}get isEstablishingConnection(){return this.state===gt.CONNECTING||this.state===gt.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=gt.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=ta((i=n.loggerName)!==null&&i!==void 0?i:ur.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new SD,this.queuedRequests=[],this.closingLock=new Vn,this.connectionLock=new Vn,this.state=gt.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=gt.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=gt.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=nD(),s=i.singlePeerConnection?RD(n,o,i):ED(n,o,i),l=dD(e,s),c=hD(l);return new Promise((u,d)=>E(this,void 0,void 0,function*(){var h,p;try{let v=!1;const m=b=>E(this,void 0,void 0,function*(){if(v)return;v=!0;const k=b instanceof Event?b.currentTarget:b,w=fD(k,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(w)).catch(C=>{this.log.error(C),this.close()}):this.close(),S(),d(_e.cancelled(w))});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=(b,k)=>{this.handleSignalConnected(b,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 kD(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===gt.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 b=yield this.ws.opened.catch(N=>E(this,void 0,void 0,function*(){if(this.state!==gt.CONNECTED){this.state=gt.DISCONNECTED,clearTimeout(g);const O=yield this.handleConnectionError(N,c);d(O);return}this.handleWSError(N),d(N)}));if(clearTimeout(g),!b)return;const k=b.readable.getReader();this.streamWriter=b.writable.getWriter();const w=yield k.read();if(k.releaseLock(),!w.value)throw _e.internal("no message received as first message");const C=LS(w.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(b,A),u(R.response)}catch(b){d(b)}finally{S()}}finally{a()}}))})}startReadingLoop(e,n){return E(this,void 0,void 0,function*(){for(n&&this.handleSignalResponse(n);;){this.signalLatency&&(yield An(this.signalLatency));const{done:i,value:r}=yield e.read();if(i)break;const a=LS(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([gt.DISCONNECTING||gt.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=gt.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,An(CD)])}}catch(a){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:a}))}finally{n&&(e.state=gt.DISCONNECTED),r()}}()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ys(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:Ys(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 oh({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new sh({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 Im({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 yx({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new Sx({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Dt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new wx({timestamp:Dt.parse(Date.now()),rtt:Dt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new Lm({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new ch({reason:lr.CLIENT_INITIATED,action:Us.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&&!wD(n)&&i.state===gt.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 An(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 UM({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=US(r.value);this.onAnswer&&this.onAnswer(o,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const o=US(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===gt.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=Rn.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&&Rn.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=Rn.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Rn.clearInterval(this.pingInterval)}handleSignalConnected(e,n,i){this.state=gt.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===gt.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 US(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 Ys(t,e){return new Ha({sdp:t.sdp,type:t.type,id:e})}function ED(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",Lr()?"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 RD(t,e,n){const i=new URLSearchParams;i.set("access_token",t);const r=new s8({clientInfo:e,connectionSettings:new Cx({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 l8({joinRequest:r.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(a.toBinary()))),i}class zS{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 AD{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 hr={},vg={},bg={exports:{}},FS;function yg(){if(FS)return bg.exports;FS=1;var t=bg.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")})}),bg.exports}var qS;function ND(){return qS||(qS=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=yg(),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 v=0;v<(r[h]||[]).length;v+=1){var m=r[h][v];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}})})}}(vg)),vg}var _g,HS;function OD(){if(HS)return _g;HS=1;var t=yg(),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 _g=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(v){u.push(i(h,p,v))})})})}),u.join(`\r
41
41
  `)+`\r
42
- `},_g}var VS;function MD(){if(VS)return hr;VS=1;var t=ND(),e=OD(),n=yg();return hr.grammar=n,hr.write=e,hr.parse=t.parse,hr.parseParams=t.parseParams,hr.parseFmtpConfig=t.parseFmtpConfig,hr.parsePayloads=t.parsePayloads,hr.parseRemoteCandidates=t.parseRemoteCandidates,hr.parseImageAttributes=t.parseImageAttributes,hr.parseSimulcastStreamList=t.parseSimulcastStreamList,hr}var Xa=MD();function xg(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),v=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(v,p);s&&s(x),u.forEach(function(b){return(0,b.resolve)(x)}),u=[]}},d()),g){var y=t.apply(v,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(v){return(0,v.reject)(p)}),u=[]},h}const DD=.7,PD=20,Ks={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class GS extends Dr.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=xg(r=>E(this,void 0,void 0,function*(){this.emit(Ks.NegotiationStarted);try{yield this.createAndSendOffer()}catch(a){if(r)r(a);else throw a}}),PD),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=ta((i=n.loggerName)!==null&&i!==void 0?i:ur.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new Vn}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}=LD(e);this.remoteStereoMids=a,this.remoteNackMids=o}else if(e.type==="answer"){const a=Xa.parse((i=e.sdp)!==null&&i!==void 0?i:"");a.media.forEach(o=>{const s=Sg(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=Xa.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(Ks.NegotiationComplete),e.sdp&&Xa.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Ks.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=Xa.parse((n=a.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(s=>{YS(s),s.type==="audio"?WS(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||(dr(l.codec)&&!Qo()&&this.ensureVideoDDExtensionForSVC(s,o),!dr(l.codec)))return!0;const u=Math.round(l.maxbr*DD);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,Xa.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=Xa.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{YS(r),r.type==="audio"&&WS(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Xa.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 sn("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 sn("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 Qm(a)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===kS))){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:kS})}}}function WS(t,e,n){const i=Sg(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 LD(t){var e;const n=[],i=[],r=Xa.parse((e=t.sdp)!==null&&e!==void 0?e:"");let a=0;return r.media.forEach(o=>{var s;const l=Sg(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 YS(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 Sg(t){return typeof t=="number"?t.toFixed(0):t}const kg="vp8",ID={audioPreset:Zm.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:tg.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:kg,backupCodec:!0,preConnectBuffer:!1},KS={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},XS={deviceId:{ideal:"default"},resolution:xc.h720.resolution},jD={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new g8,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},Tg={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ut;(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"})(Ut||(Ut={}));class BD{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Tg.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=Ut.CONNECTED:l.some(c=>c==="failed")?this.state=Ut.FAILED:l.some(c=>c==="connecting")?this.state=Ut.CONNECTING:l.every(c=>c==="closed")?this.state=Ut.CLOSED:l.some(c=>c==="closed")?this.state=Ut.CLOSING:l.every(c=>c==="new")&&(this.state=Ut.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Ut[s]," to ").concat(Ut[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=ta((r=i.loggerName)!==null&&r!==void 0?r:ur.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=n!=="subscriber-primary",this.isSubscriberConnectionRequired=n==="subscriber-primary",this.publisher=new GS(e,i),n!=="publisher-only"&&(this.subscriber=new GS(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,cr.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,cr.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=Ut.NEW,this.connectionLock=new Vn,this.remoteOfferLock=new Vn}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===cr.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(Ks.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Ks.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===cr.PUBLISHER?this.publisher.getConnectedAddress():e===cr.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),Rn.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=Rn.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(_e.internal("could not establish pc connection"))},o);for(;this.state!==Ut.CONNECTED;)if(yield An(50),r!=null&&r.signal.aborted){c(_e.cancelled("room connection has been cancelled"));return}Rn.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}const $S=5e3,UD=3e4;class $e{static fetchRegionSettings(e,n,i){return E(this,void 0,void 0,function*(){const r=yield $e.fetchLock.lock();try{const a=yield fetch("".concat(zD(e),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(a.ok){const o=uD(a.headers),s=o?o*1e3:$S;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=$e.settingsTimeouts.get(e.hostname);clearTimeout(r),$e.settingsTimeouts.set(e.hostname,setTimeout(()=>E(this,void 0,void 0,function*(){try{const a=yield $e.fetchRegionSettings(e,n);$e.updateCachedRegionSettings(e,n,a)}catch(a){if(a instanceof _e&&a.reason===Ct.NotAllowed){Ee.debug("token is not valid, cancelling auto region refresh");return}Ee.debug("auto refetching of region settings failed",{error:a}),$e.scheduleRefetch(e,n,i)}}),i))})}static updateCachedRegionSettings(e,n,i){$e.cache.set(e.hostname,i),$e.scheduleRefetch(e,n,i.maxAgeInMs)}static stopRefetch(e){const n=$e.settingsTimeouts.get(e);n&&(clearTimeout(n),$e.settingsTimeouts.delete(e))}static scheduleCleanup(e){let n=$e.connectionTrackers.get(e);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{const i=$e.connectionTrackers.get(e);i&&i.connectionCount===0&&(Ee.debug("stopping region refetch after disconnect delay",{hostname:e}),$e.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},UD))}static cancelCleanup(e){const n=$e.connectionTrackers.get(e);n!=null&&n.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let n=$e.connectionTrackers.get(e);n||(n={connectionCount:0},$e.connectionTrackers.set(e,n)),n.connectionCount++,$e.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,n=$e.connectionTrackers.get(e);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&$e.scheduleCleanup(e))}constructor(e,n){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Vs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return E(this,void 0,void 0,function*(){return $e.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=$e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(e),$e.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){$e.updateCachedRegionSettings(this.serverUrl,this.token,e)}}$e.cache=new Map,$e.settingsTimeouts=new Map,$e.connectionTrackers=new Map,$e.fetchLock=new Vn;function zD(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class zt extends Error{constructor(e,n,i){super(n),this.code=e,this.message=QS(n,zt.MAX_MESSAGE_BYTES),this.data=i?QS(i,zt.MAX_DATA_BYTES):void 0}static fromProto(e){return new zt(e.code,e.message,e.data)}toProto(){return new ax({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new zt(zt.ErrorCode[e],zt.ErrorMessage[e],n)}}zt.MAX_MESSAGE_BYTES=256,zt.MAX_DATA_BYTES=15360,zt.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},zt.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 JS=15360;function wg(t){return new TextEncoder().encode(t).length}function QS(t,e){if(wg(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 Cg=2e3;function xh(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 Eg=typeof MediaRecorder<"u";class FD{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const qD=Eg?MediaRecorder:FD;class HD extends qD{constructor(e,n){if(!Eg)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 VD(){return Eg}const GD=1e3,WD=1e4;class ZS extends F{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=xg(()=>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(te.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Vn,this.pauseUpstreamLock=new Vn,this.trackChangeLock=new Vn,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!==F.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=>{Hs(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&&(qs(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=>{qs(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]:GD;return function*(){var i;if(e.kind===F.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=di())===null||i===void 0?void 0:i.os)==="iOS"&&(yield An(10));const r=Date.now();for(;Date.now()-r<n;){const a=e.dimensions;if(a)return a;yield An(50)}throw new ia("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===Va(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Va(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===F.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),a=e.kind===F.Kind.Audio?"audioinput":"videoinput";return n?gn.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 ia("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=v8(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===F.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?Object.assign({deviceId:i},a):!0,this.attachedElements.forEach(c=>{Hs(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===F.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(te.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?te.Muted:te.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),wS()&&(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(te.UpstreamPaused,this);const i=di();if((i==null?void 0:i.name)==="Safari"&&Ir(i.version,"12.0")<0)throw new Jm("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(te.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(qs(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&&(Hs(i._mediaStreamTrack,c),qs(i.processor.processedTrack,c));yield(a=i.sender)===null||a===void 0?void 0:a.replaceTrack(i.processor.processedTrack)}i.emit(te.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(te.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!VD()){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 HD(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},WD)}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 Sh extends ZS{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,F.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=xh(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(te.AudioTrackFeatureUpdate,this,mn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(te.AudioTrackFeatureUpdate,this,mn.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===F.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!==Va(this._constraints.deviceId);return this.source===F.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=ig({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(){hi()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Cg)))}setProcessor(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Lr()&&!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(te.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 yS(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(te.AudioSilenceDetected)),e})}}function YD(t,e,n){switch(t.kind){case"audio":return new Sh(t,e,!1,void 0,n);case"video":return new kh(t,e,!1,n);default:throw new ia("unsupported track type: ".concat(t.kind))}}const KD=Object.values(xc),XD=Object.values(eg),$D=Object.values(tg),JD=[xc.h180,xc.h360],QD=[eg.h180,eg.h360],ZD=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ft(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)}),Rg=["q","h","f"];function Ag(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=tP(t,e,n,c),Ee.debug("using video encoding",o));const u=o.maxFramerate,d=new ft(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(l&&dr(c)){const v=new nk(l),m=[];if(v.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const S=di();if(Tc()||Lr()||(S==null?void 0:S.name)==="Chrome"&&Ir(S==null?void 0:S.version,"113")<0){const g=v.suffix=="h"?2:3,y=Q8(S);for(let x=0;x<v.spatial;x+=1)m.push({rid:Rg[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=tk(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:ek(t,d):h=(a=tk(i==null?void 0:i.videoSimulcastLayers))!==null&&a!==void 0?a:ek(t,d);let p;if(h.length>0){const v=h[0];h.length>1&&([,p]=h);const m=Math.max(e,n);if(m>=960&&p)return Ng(e,n,[v,p,d],u);if(m>=480)return Ng(e,n,[v,d],u)}return Ng(e,n,[d])}function eP(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===F.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Ag(t.source===F.Source.ScreenShare,l,c,n)}function tP(t,e,n,i){const r=nP(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 nP(t,e,n){if(t)return $D;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?KD:XD}function ek(t,e){if(t)return ZD(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)?JD:QD}function Ng(t,e,n,i){const r=[];if(n.forEach((a,o)=>{if(o>=Rg.length)return;const s=Math.min(t,e),c={rid:Rg[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=Jo()||o===0;a.encoding.priority&&d&&(c.priority=a.encoding.priority,c.networkPriority=a.encoding.priority),r.push(c)}),Lr()&&ES()==="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 tk(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 nk{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 iP(t){return t.source===F.Source.ScreenShare||t.constraints.height&&Va(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const rP=5e3;class kh extends ZS{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,F.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(te.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+=xh(c,h)}),this._currentBitrate=l}this.prevStats=o}),this.senderLock=new Vn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!hi())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()},Cg))}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=na(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=na(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===F.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===F.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=Ti.LOW;i<=Ti.HIGH;i+=1)n.push(new jm({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(dr(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=ig({video:e});typeof d.video!="boolean"&&(s=d.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var l=!0,c=na(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=na(r.simulcastCodecs.values()),v;v=yield p.next(),o=v.done,!o;h=!0)c=v.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)},rP))}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(dr(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(n=!0,i=na(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(dr(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 ik(d.sender,d.encodings,u.qualities,this.senderLock,dr(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 ik(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&&dr(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),wS()&&this.isInBackground&&this.source===F.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ik(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 v;let m=(v=h.rid)!==null&&v!==void 0?v:"";m===""&&(m="q");const S=rk(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),Jo()&&(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 rk(t){switch(t){case"f":return Ti.HIGH;case"h":return Ti.MEDIUM;case"q":return Ti.LOW;default:return Ti.HIGH}}function ak(t,e,n,i){if(!n)return[new qa({quality:Ti.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,a=new nk(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 qa({quality:Math.min(Ti.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=rk((o=r.rid)!==null&&o!==void 0?o:"");return new qa({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 ok="_lossy",sk="_reliable",aP=2*1e3,Og="leave-reconnect",oP=3e4,sP=8*1024,lP=256*1024;var Vi;(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"})(Vi||(Vi={}));class cP extends Dr.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Tg.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Vi.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 zS,this.reliableReceivedState=new AD(oP),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===sk)a.reliableDCSub=o;else if(o.label===ok)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=Gn.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(ie.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=nx.fromBinary(h.payload),v=new Gn({value:p.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((s=v.value)===null||s===void 0?void 0:s.case)==="user"&&lk(v,v.value.value),this.emit(ie.DataPacketReceived,v,d.value.value.encryptionType)}else((l=d.value)===null||l===void 0?void 0:l.case)==="user"&&lk(d,d.value.value),this.emit(ie.DataPacketReceived,d,on.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(ie.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){a(o);return}i===Og&&(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=Rn.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Vi.Connected&&i();const a=()=>{this.off(ie.Disconnected,o),i()},o=()=>{this.off(ie.Restarted,a),r()};this.once(ie.Restarted,a),this.once(ie.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(ie.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(Cc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===gt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===gt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Ko.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>E(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Cc(this.url),{method:"HEAD"}),An(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ta((n=e.loggerName)!==null&&n!==void 0?n:ur.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new gg(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Vn,this.dataProcessLock=new Vn,this.dcBufferStatus=new Map([[Oe.LOSSY,!0],[Oe.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(ie.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(ie.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(ie.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(ie.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(ie.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(ie.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(ie.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(ie.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(ie.SignalConnected,a),a}catch(a){if(a instanceof _e&&a.reason===Ct.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(ie.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 zS,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 ia("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!==Ut.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new BD(r,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(ie.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===Ut.CONNECTED){const u=this.pcState===Vi.New;this.pcState=Vi.Connected,u&&this.emit(ie.Connected,e)}else a===Ut.FAILED&&(this.pcState===Vi.Connected||this.pcState===Vi.Reconnecting)&&(this.pcState=Vi.Disconnected,this.handleDisconnect("peerconnection failed",s==="failed"?Ko.RR_SUBSCRIBER_FAILED:Ko.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===gt.RECONNECTING,c=[Ut.FAILED,Ut.CLOSING,Ut.CLOSED].includes(a);l&&c&&!this._isClosed&&this.emit(ie.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(ie.MediaTrackAdded,a.track,a.streams[0],a.receiver)},uP((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(ie.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ie.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(ie.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ie.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(ie.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",Ko.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:$S,regionSettings:e.regions})),e.action){case Us.DISCONNECT:this.emit(ie.Disconnected,e==null?void 0:e.reason),this.close();break;case Us.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Og);break;case Us.RESUME:this.handleDisconnect(Og)}}}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===gc.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(ok,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(sk,{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,sP),lP)}},1e3))}createSender(e,n,i){return E(this,void 0,void 0,function*(){if(ag())return yield this.createTransceiverRTCRtpSender(e,n,i);if(og())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new sn("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(ag())return this.createSimulcastTransceiverSender(e,n,i,r);if(og())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new sn("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new sn("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ga(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 sn("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 sn("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)===gc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Ut.NEW)===Ut.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 sn?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:a})),o=!1):a instanceof Fs||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Ko.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(ie.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 sn("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ie.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 Fs;a=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof _e&&o.reason===Ct.NotAllowed?new sn("could not reconnect, token might be expired"):new Fs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ie.SignalRestarted,a),yield this.waitForPCReconnected(),this.client.currentState!==gt.CONNECTED)throw new Fs("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(ie.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 sn("could not reconnect, url or token not saved");if(!this.pcManager)throw new sn("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ie.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===Ct.NotAllowed?new sn("could not reconnect, token might be expired"):r instanceof _e&&r.reason===Ct.LeaveRequest?r:new Fs(a)}if(this.emit(ie.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!==gt.CONNECTED)throw new Fs("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(ie.Resumed)})}waitForPCInitialConnection(e,n){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new sn("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return E(this,void 0,void 0,function*(){this.pcState=Vi.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield An(aP),!this.pcManager)throw new sn("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Vi.Connected}catch(e){throw this.pcState=Vi.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 Gn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcResponse",value:new Nm({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 Gn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcAck",value:new Am({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=bD(e);if(a){const o=yield this.e2eeManager.encryptData(a.toBinary());e.value={case:"encryptedPacket",value:new tx({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(ie.Closing,r);!this.dcBufferStatus.get(e);)yield An(10);this.off(ie.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 sn("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 An(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!==Ut.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 Qm("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(ie.Closing,r),this.pcManager.publisher.once(Ks.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(s=>{const l=s.codec.toLowerCase();iD(l)&&o.set(s.payload,l)}),this.emit(ie.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(a){a instanceof Qm&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ko.RR_UNKNOWN),n(a)}finally{this.off(ie.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(v=>{v.isDesired!==d&&h.push(v.trackSid),v.isEnabled||p.push(v.trackSid)}),this.client.sendSyncState(new Bm({answer:this.options.singlePeerConnection?l?Ys({sdp:l.sdp,type:l.type}):void 0:u?Ys({sdp:u.sdp,type:u.type}):void 0,offer:this.options.singlePeerConnection?s?Ys({sdp:s.sdp,type:s.type}):void 0:c?Ys({sdp:c.sdp,type:c.type}):void 0,subscription:new lh({trackSids:h,subscribe:!d,participantTracks:[]}),publishTracks:z8(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((v,m)=>new kx({publisherSid:m,lastSeq:v}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Tx({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Oe.LOSSY),cr.PUBLISHER),n(this.dataChannelForKind(Oe.RELIABLE),cr.PUBLISHER),n(this.dataChannelForKind(Oe.LOSSY,!0),cr.SUBSCRIBER),n(this.dataChannelForKind(Oe.RELIABLE,!0),cr.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Rn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){hi()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){hi()&&(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 uP(t){return t!==void 0&&t>13}function lk(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 ck{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 qi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Wn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new qi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Wn.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class dP extends ck{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 Hi,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=na(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 hP extends ck{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=_h(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 Hi,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 qi("Cannot decode datastream chunk ".concat(u.chunkIndex," as text: ").concat(h),Wn.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=na(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 fP{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 qi('A text stream handler for topic "'.concat(e,'" has already been set.'),Wn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new qi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Wn.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 qi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Wn.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 Hi;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:_h(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new qi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Wn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new dP(l,c,_h(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 Hi;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 qi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Wn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new hP(l,c,_h(e.totalLength),s),{identity:n})}})}handleStreamChunk(e,n){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Wn.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 qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Wn.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 qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Wn.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 qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Wn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class uk{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 pP extends uk{}class mP extends uk{}const dk=15e3;class gP{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 v=l.reduce((m,S)=>m+S,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,v)},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?on.GCM:on.NONE},s=new ih({streamId:a,mimeType:o.mimeType,topic:o.topic,timestamp:Zo(o.timestamp),totalLength:Zo(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new px({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"?Om.UPDATE:Om.CREATE})}}),l=e==null?void 0:e.destinationIdentities,c=new Gn({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 cD(m,dk)){const g=new rh({content:S,streamId:a,chunkIndex:Zo(u)}),y=new Gn({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 ah({streamId:a}),S=new Gn({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 v.close()});d.once(ie.Closing,p);const v=new pP(h,o,()=>this.engine.off(ie.Closing,p));return v})}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?on.GCM:on.NONE},d=new ih({totalLength:Zo((s=u.size)!==null&&s!==void 0?s:0),mimeType:u.mimeType,streamId:l,topic:u.topic,timestamp:Zo(Date.now()),attributes:u.attributes,contentHeader:{case:"byteHeader",value:new mx({name:u.name})}}),h=new Gn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(h,Oe.RELIABLE);let p=0;const v=new Vn,m=this.engine,S=this.log,g=new WritableStream({write(x){return E(this,void 0,void 0,function*(){const b=yield v.lock();let k=0;try{for(;k<x.byteLength;){const w=x.slice(k,k+dk),C=new Gn({destinationIdentities:c,value:{case:"streamChunk",value:new rh({content:w,streamId:l,chunkIndex:Zo(p)})}});yield m.sendDataPacket(C,Oe.RELIABLE),p+=1,k+=w.byteLength}}finally{b()}})},close(){return E(this,void 0,void 0,function*(){const x=new ah({streamId:l}),b=new Gn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield m.sendDataPacket(b,Oe.RELIABLE)})},abort(x){S.error("Sink error:",x)}});return new mP(g,u)})}}class hk extends F{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?te.Muted:te.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(te.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(),Cg)),F8()&&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(te.TimeSyncUpdate,{timestamp:r,rtpTimestamp:a}),this.rtpTimestamp=a)}};e()}}class vP extends hk{constructor(e,n,i,r,a,o){super(e,n,F.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=xh(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;Lr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Lr())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(sg(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&sg(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(te.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(te.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 Mg=100;class bP extends hk{constructor(e,n,i,r,a){super(e,n,F.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=xh(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=xg(()=>{this.updateDimensions()},Mg),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===F.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Hs(this._mediaStreamTrack,n):qs(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 yP(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<Mg){Rn.setTimeout(()=>{this.updateVisibility()},Mg);return}this.lastVisible=s,this.emit(te.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(te.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?RS():n||(RS()>2?2:1)}}class yP{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=Ac(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=Ac(this.element),(a=this.handleVisibilityChanged)===null||a===void 0||a.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ac(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??Dg(e),this.isPiP=hi()&&Ac(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=Dg(this.element),this.isPiP=Ac(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,NS().observe(this.element),AS().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=NS())===null||e===void 0||e.unobserve(this.element),(n=AS())===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 Ac(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Dg(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function Dg(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 aa extends Dr.EventEmitter{constructor(e,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=on.NONE,this.log=Ee,this.handleMuted=()=>{this.emit(te.Muted)},this.handleUnmuted=()=>{this.emit(te.Unmuted)},this.log=ta((a=r==null?void 0:r.loggerName)!==null&&a!==void 0?a:ur.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=F.Source.Unknown}setTrack(e){this.track&&(this.track.off(te.Muted,this.handleMuted),this.track.off(te.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(te.Muted,this.handleMuted),e.on(te.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!==on.NONE}get audioTrack(){if(jr(this.track))return this.track}get videoTrack(){if(Ga(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=F.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===F.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={}))})(aa||(aa={}));class Pg extends aa{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(te.Ended)},this.handleCpuConstrained=()=>{this.track&&Ga(this.track)&&this.emit(te.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(te.Ended,this.handleTrackEnded),this.track.off(te.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(te.Ended,this.handleTrackEnded),e.on(te.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(jr(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(mn.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(mn.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(mn.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(mn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(mn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(mn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Th(t,e){return E(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:a}=xS(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=bS(a,KS,XS),c=ig(l),u=navigator.mediaDevices.getUserMedia(c);a.audio&&(gn.userMediaPromiseMap.set("audioinput",u),u.catch(()=>gn.userMediaPromiseMap.delete("audioinput"))),a.video&&(gn.userMediaPromiseMap.set("videoinput",u),u.catch(()=>gn.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 v=p?l.audio:l.video;(typeof v=="boolean"||!v)&&(v={});let m;const S=p?c.audio:c.video;typeof S!="boolean"&&(m=S);const g=h.getSettings().deviceId;m!=null&&m.deviceId&&Va(m.deviceId)!==g?m.deviceId=g:m||(m={deviceId:g});const y=YD(h,m,e);return y.kind===F.Kind.Video?y.source=F.Source.Camera:y.kind===F.Kind.Audio&&(y.source=F.Source.Microphone),y.mediaStream=d,jr(y)&&i?yield y.setProcessor(i):Ga(y)&&r&&(yield y.setProcessor(r)),y})))}catch(d){if(!n)throw d;return Th(Object.assign(Object.assign({},t),{audio:o,video:s}),e)}})}function _P(t){return E(this,void 0,void 0,function*(){return(yield Th({audio:!1,video:t??!0}))[0]})}function xP(t){return E(this,void 0,void 0,function*(){return(yield Th({audio:t??!0,video:!1}))[0]})}var $a;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})($a||($a={}));function SP(t){switch(t){case mc.EXCELLENT:return $a.Excellent;case mc.GOOD:return $a.Good;case mc.POOR:return $a.Poor;case mc.LOST:return $a.Lost;default:return $a.Unknown}}class fk extends Dr.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===vc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===js.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]:vc.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=$a.Unknown,this.log=Ee,this.log=ta((l=o==null?void 0:o.loggerName)!==null&&l!==void 0?l:ur.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 Hi,this.once(ae.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(F.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(F.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(F.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===js.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==js.ACTIVE&&this.emit(ae.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(ae.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(ae.ParticipantNameChanged,e)}_setAttributes(e){const n=q8(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(ae.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(ae.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ae.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=SP(e),n!==this._connectionQuality&&this.emit(ae.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=>jr(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(te.Muted,()=>{this.emit(ae.TrackMuted,e)}),e.on(te.Unmuted,()=>{this.emit(ae.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case F.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case F.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function kP(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 xx({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 TP extends fk{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=on.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Hi)},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 Hi),(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!==Um.OK&&d.reject(new gS(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=zt.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=>kP(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(ae.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 v=yield p.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var m=!0,S=na(v),g;g=yield S.next(),l=g.done,!l;m=!0){d=g.value,m=!1;const y=d;j8(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===F.Source.ScreenShare||s.source===F.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(ra(s)||Wa(s))try{if(hi())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:s.source===F.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))),ra(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!==on.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(ie.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(ie.Connected,this.handleReconnected).on(ie.SignalConnected,this.handleSignalConnected).on(ie.SignalRestarted,this.handleReconnected).on(ie.SignalResumed,this.handleReconnected).on(ie.Restarting,this.handleReconnecting).on(ie.Resuming,this.handleReconnecting).on(ie.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ie.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ie.Closing,this.handleClosing).on(ie.SignalRequestResponse,this.handleSignalRequestResponse).on(ie.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:v=>{l(v),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(v=>{let[m,S]=v;return this.attributes[m]===S||S===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),s();return}yield An(50)}l(new gS("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(F.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(F.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(F.Source.ScreenShare,e,n,i)}setE2EEEnabled(e){return E(this,void 0,void 0,function*(){this.encryptionType=e?on.GCM:on.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 F.Source.Camera:l=yield this.createTracks({video:(a=i)!==null&&a!==void 0?a:!0});break;case F.Source.Microphone:l=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case F.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new ia(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(ae.MediaDevicesError,c,rg(e)),this.pendingPublishing.delete(e),c}for(const c of l){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===F.Source.Microphone&&jr(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===F.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const l=this.getTrackPublication(F.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(F.Source.Camera)||this.pendingPublishing.has(F.Source.Microphone))){this.pendingPublishing.add(F.Source.Camera),this.pendingPublishing.add(F.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(F.Source.Camera),this.pendingPublishing.delete(F.Source.Microphone)}}})}createTracks(e){return E(this,void 0,void 0,function*(){var n,i;e??(e={});const r=bS(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 Th(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(jr(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=F.Source.Microphone,this.emit(ae.AudioStreamAcquired)),Ga(s)&&(this.cameraError=void 0,s.source=F.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 Jm("getDisplayMedia not supported");e.resolution===void 0&&!J8()&&(e.resolution=tg.h1080fps30.resolution);const n=U8(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new ia("no video track found");const a=new kh(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=F.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);const o=[a];if(i.getAudioTracks().length>0){this.emit(ae.AudioStreamAcquired);const s=new Sh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=F.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;ra(i)&&i.setAudioContext(a.audioContext),yield(s=a.reconnectFuture)===null||s===void 0?void 0:s.promise,a.republishPromise&&!o&&(yield a.republishPromise),Gs(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 F.Source.Microphone:g="audioinput";break;case F.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 Sh(i,d,!0,a.audioContext,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;case"video":i=new kh(i,d,!0,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;default:throw new ia("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),v="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(l=p.forceStereo)!==null&&l!==void 0?l:v;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)),!Z8()&&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!==gt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:je(i)}));let x=!1;const b=setTimeout(()=>{x=!0,i.stop(),y(new mS("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),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 Hi),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=>H8(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 mS("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Gs(e)&&A.source===e.source)&&e.source!==F.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&&jr(e)&&(e.stopOnMute=!0),e.source===F.Source.ScreenShare&&Jo()&&(n.simulcast=!1),n.videoCodec==="av1"&&!K8()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!X8()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=kg),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>n.videoCodec===Sc(A.mime))||(n.videoCodec=Sc(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;e.on(te.Muted,this.onTrackMuted),e.on(te.Unmuted,this.onTrackUnmuted),e.on(te.Ended,this.handleTrackEnded),e.on(te.UpstreamPaused,this.onTrackUpstreamPaused),e.on(te.UpstreamResumed,this.onTrackUpstreamResumed),e.on(te.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],g=!(!((r=n.dtx)!==null&&r!==void 0)||r),y=e.getSourceTrackSettings();y.autoGainControl&&S.push(mn.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&S.push(mn.TF_ECHO_CANCELLATION),y.noiseSuppression&&S.push(mn.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&S.push(mn.TF_STEREO),g&&S.push(mn.TF_NO_DTX),ra(e)&&e.hasPreConnectBuffer&&S.push(mn.TF_PRECONNECT_BUFFER);const x=new bc({cid:e.mediaStreamTrack.id,name:n.name,type:F.kindToProto(e.kind),muted:e.isMuted,source:F.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 b;if(e.kind===F.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:xc.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,Wa(e)&&(dr(m)&&(e.source===F.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 Dm({codec:m,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:kg}),n.backupCodec&&m!==n.backupCodec.codec&&x.encryption===on.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Dm({codec:n.backupCodec.codec,cid:""})))),b=Ag(e.source===F.Source.ScreenShare,x.width,x.height,n),x.layers=ak(x.width,x.height,b,dr(n.videoCodec))}else e.kind===F.Kind.Audio&&(b=[{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 sn("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 sn("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,b),this.emit(ae.LocalSenderCreated,e.sender,e),Wa(e)&&((A=n.degradationPreference)!==null&&A!==void 0||(n.degradationPreference=iP(e)),e.setDegradationPreference(n.degradationPreference)),b)if(Jo()&&e.kind===F.Kind.Audio){let B;for(const X of this.engine.pcManager.publisher.getTransceivers())if(X.sender===e.sender){B=X;break}B&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:B,codec:"opus",maxbr:!((N=b[0])===null||N===void 0)&&N.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&dr(e.codec)&&(!((O=b[0])===null||O===void 0)&&O.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let w;const C=new Promise((A,N)=>E(this,void 0,void 0,function*(){var O;try{w=yield this.engine.addTrack(x),A(w)}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(X=>{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:X}))})),N(B)}}));if(this.enabledPublishVideoCodecs.length>0)w=(yield Promise.all([C,k()]))[0];else{w=yield C;let A;if(w.codecs.forEach(N=>{A===void 0&&(A=N.mimeType)}),A&&e.kind===F.Kind.Video){const N=Sc(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,b=Ag(e.source===F.Source.ScreenShare,x.width,x.height,n))}yield k()}const R=new Pg(e.kind,w,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(R.on(te.CpuConstrained,A=>this.onTrackCpuConstrained(A,R)),R.options=n,e.sid=w.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:w})),Wa(e)?e.startMonitor(this.engine.client):ra(e)&&e.startMonitor(),this.addTrackPublication(R),this.emit(ae.LocalTrackPublished,R),ra(e)&&w.audioFeatures.includes(mn.TF_PRECONNECT_BUFFER)){const A=e.getPreConnectBuffer(),N=e.getPreConnectBufferMimeType();this.on(ae.LocalTrackSubscribed,O=>{if(O.trackSid===w.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,X)=>E(this,void 0,void 0,function*(){var L,Y,P,V,K,ee;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),je(e)));const Q=setTimeout(()=>{X(new Error("agent not active within 10 seconds"))},1e4),le=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:[le.identity],attributes:{trackId:R.trackSid,sampleRate:String((K=y.sampleRate)!==null&&K!==void 0?K:"48000"),channels:String((ee=y.channelCount)!==null&&ee!==void 0?ee:"1")}});try{for(var $=!0,U=na(A),Z;Z=yield U.next(),L=Z.done,!L;$=!0){V=Z.value,$=!1;const ge=V;yield j.write(ge)}}catch(ge){Y={error:ge}}finally{try{!$&&!L&&(P=U.return)&&(yield P.call(U))}finally{if(Y)throw Y.error}}yield j.close(),B()}catch(Q){X(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!==on.NONE)return;let a;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(a=p)}),!a)throw new ia("track is not published");if(!Wa(e))throw new ia("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=eP(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 bc({cid:l.mediaStreamTrack.id,type:F.kindToProto(e.kind),muted:e.isMuted,source:F.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=ak(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new sn("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(Gs(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(te.Muted,this.onTrackMuted),e.off(te.Unmuted,this.onTrackUnmuted),e.off(te.Ended,this.handleTrackEnded),e.off(te.UpstreamPaused,this.onTrackUpstreamPaused),e.off(te.UpstreamResumed,this.onTrackUpstreamResumed),e.off(te.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<Ut.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),Wa(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 F.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case F.Kind.Video:this.videoTrackPublications.delete(a.trackSid);break}return this.emit(ae.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!==F.Source.ScreenShare&&c.source!==F.Source.ScreenShareAudio&&(ra(c)||Wa(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 Em({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:s});const c=new Gn({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 Gn({kind:Oe.RELIABLE,value:{case:"sipDtmf",value:new rx({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 Gn({value:{case:"chatMessage",value:new nh(Object.assign(Object.assign({},i),{timestamp:Dt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(ae.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 Gn({value:{case:"chatMessage",value:new nh(Object.assign(Object.assign({},i),{timestamp:Dt.parse(i.timestamp),editTimestamp:Dt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(ae.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,v,m;if(wg(o)>JS){d(zt.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&&Ir((m=(v=this.engine.latestJoinResponse)===null||v===void 0?void 0:v.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){d(zt.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(zt.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(zt.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(g,{resolve:(b,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(b??"")},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 Gn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcRequest",value:new Rm({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,zt.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 Hi),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(ra(r)||Wa(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 An(20)}})}}class wP extends aa{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(te.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 lh({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ox({participantSid:"",trackSids:[this.trackSid]})]});this.emit(te.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?aa.SubscriptionStatus.Unsubscribed:super.isSubscribed?aa.SubscriptionStatus.Subscribed:aa.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?aa.PermissionStatus.Allowed:aa.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||(fg(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&fg(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ti.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(te.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(te.VisibilityChanged,this.handleVisibilityChange),r.off(te.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(te.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(te.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(te.VisibilityChanged,this.handleVisibilityChange),e.on(te.Ended,this.handleEnded),this.emit(te.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(te.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?te.Muted:te.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(te.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(te.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 fg(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new vx({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===F.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)SS(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=V8(this.trackInfo,this.requestedMaxQuality);i&&SS(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:Ti.HIGH})),e.quality=Ti.HIGH)}this.emit(te.UpdateSettings,e)}}class wh extends fk{static fromParticipantInfo(e,n,i){return new wh(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]:vc.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(te.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(te.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(te.SubscriptionPermissionChanged,n=>{this.emit(ae.TrackSubscriptionPermissionChanged,e,n)}),e.on(te.SubscriptionStatusChanged,n=>{this.emit(ae.TrackSubscriptionStatusChanged,e,n)}),e.on(te.Subscribed,n=>{this.emit(ae.TrackSubscribed,n,e)}),e.on(te.Unsubscribed,n=>{this.emit(ae.TrackUnsubscribed,n,e)}),e.on(te.SubscriptionFailed,n=>{this.emit(ae.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]:F.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]:F.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(ae.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(ae.TrackSubscriptionFailed,n);return}const l=e.kind==="video";let c;return l?c=new bP(e,n,r,a):c=new vP(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)&&hg(c)&&jr(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=F.kindFromProto(r.type);if(!l)return;s=new wP(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!==F.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(ae.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 F.Kind.Audio:this.audioTrackPublications.delete(e);break;case F.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(ae.TrackUnpublished,i)}setAudioOutput(e){return E(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;jr(i.track)&&hg(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 Je;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(Je||(Je={}));const CP=4*1e3;class Xs extends Dr.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var n,i,r,a;if(super(),n=this,this.state=Je.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(!$8())throw Lr()?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===Je.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(Je.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==DS(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Vs(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new $e(o,s):this.regionUrlProvider.updateToken(s),this.regionUrlProvider.fetchRegionSettings().then(p=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const d=(p,v,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 Ws.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!==Ct.Cancelled&&x.reason!==Ct.NotAllowed){let b=null;try{this.log.debug("Fetching next region"),b=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===Ct.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(k);return}}[Ct.InternalError,Ct.ServerUnreachable,Ct.Timeout].includes(x.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Ws.getInstance().addFailedConnectionAttempt(o)),b&&!(!((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(b),this.logContext),this.recreateEngine(),yield d(p,v,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,MS(x)),v(x))}else{let b=lr.UNKNOWN_REASON;x instanceof _e&&(b=MS(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),v(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Hi((p,v)=>{d(p,v,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,s,l,c,u,d)=>E(this,void 0,void 0,function*(){var h,p,v;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:(v=m.participant)===null||v===void 0?void 0:v.identity}),!S.version)throw new M8("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===Je.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({},Tg),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}hi()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),hi()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Je.Connected),this.emit(J.Connected),Ws.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 v=yield c.disconnectLock.lock();try{if(c.state===Je.Disconnected){c.log.debug("already disconnected",c.logContext);return}if(c.log.info("disconnect from room",Object.assign({},c.logContext)),c.state===Je.Connecting||c.state===Je.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,lr.CLIENT_INITIATED),c.engine=void 0}finally{v()}}()})},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=di();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=dg();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(Je.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(Je.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===js.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=F.streamStateFromProto(s.state);c.track.setStreamState(u),u!==c.track.streamState&&(l.emit(ae.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(ae.DataReceived,s.payload,l,c)},this.handleSipDtmf=(o,s)=>{this.emit(J.SipDTMFReceived,s,o),o==null||o.emit(ae.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=aD(s,this.transcriptionReceivedTimes);c==null||c.emit(te.TranscriptionReceived,u),l==null||l.emit(ae.TranscriptionReceived,u,c),this.emit(J.TranscriptionReceived,u,l,c)},this.handleChatMessage=(o,s)=>{const l=oD(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=di())===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(te.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.on(te.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),ra(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),v=rg(o.source);v&&p&&p!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,p),this.emit(J.ActiveDeviceChanged,v,p))}),this.onLocalTrackUnpublished=o=>{var s,l;(s=o.track)===null||s===void 0||s.off(te.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.off(te.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=rg(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({},jD),e),this.log=ta((i=this.options.loggerName)!==null&&i!==void 0?i:ur.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},KS),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},XS),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},ID),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new fP,this.outgoingDataStreamManager=new gP(this.engine,this.log),this.disconnectLock=new Vn,this.localParticipant=new TP("","",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",Va(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Va(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Va(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),hi()){const o=new AbortController;(a=navigator.mediaDevices)===null||a===void 0||a.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),Xs.cleanupRegistry&&Xs.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 yD(i,n),this.e2eeManager.on(Ka.ParticipantEncryptionStatusChanged,(r,a)=>{lD(a)&&(this.isE2EEEnabled=r),this.emit(J.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(Ka.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===Je.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(ie.RoomUpdate,i),e(r.sid))};this.engine.on(ie.RoomUpdate,i),this.once(J.Disconnected,()=>{this.engine.off(ie.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 cP(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ie.ParticipantUpdate,this.handleParticipantUpdates).on(ie.RoomUpdate,this.handleRoomUpdate).on(ie.SpeakersChanged,this.handleSpeakersChanged).on(ie.StreamStateChanged,this.handleStreamStateUpdate).on(ie.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ie.SubscriptionError,this.handleSubscriptionError).on(ie.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ie.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(ie.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ie.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ie.DataPacketReceived,this.handleDataPacket).on(ie.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Je.SignalReconnecting)&&this.emit(J.SignalReconnecting)}).on(ie.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Je.Connected)&&this.emit(J.Reconnected)}).on(ie.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Je.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ie.Restarting,this.handleRestarting).on(ie.SignalRestarted,this.handleSignalRestarted).on(ie.Offline,()=>{this.setAndEmitConnectionState(Je.Reconnecting)&&this.emit(J.Reconnecting)}).on(ie.DCBufferStatusChanged,(e,n)=>{this.emit(J.DCBufferStatusChanged,e,n)}).on(ie.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(ae.LocalTrackSubscribed,n),this.emitWhenConnected(J.LocalTrackSubscribed,n,this.localParticipant)}).on(ie.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 gn.getInstance().getDevices(e,n)}prepareConnection(e,n){return E(this,void 0,void 0,function*(){if(this.state===Je.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Vs(new URL(e))&&n){this.regionUrlProvider=new $e(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Je.Disconnected&&(this.regionUrl=i,yield fetch(Cc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Cc(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 Mr({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Mr({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Mr({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Mr({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 Mr({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 Mr({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 Mr({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 ch({reason:lr.CLIENT_INITIATED,action:Us.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Mr({scenario:{case:"subscriberBandwidth",value:Zo(n)}});break;case"leave-full-reconnect":r=new Mr({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 v=!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(b=>b.source===F.Source.Microphone);try{v=(yield Promise.all(y.map(b=>{var k;return(k=b.audioTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(b=>b===!0)}catch(b){throw a.options.audioCaptureDefaults.deviceId=g,b}const x=y.some(b=>{var k,w;return(w=(k=b.track)===null||k===void 0?void 0:k.isMuted)!==null&&w!==void 0?w:!1});v&&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(b=>b.source===F.Source.Camera);try{v=(yield Promise.all(y.map(b=>{var k;return(k=b.videoTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(b=>b===!0)}catch(b){throw a.options.videoCaptureDefaults.deviceId=g,b}const x=y.some(b=>{var k,w;return(w=(k=b.track)===null||k===void 0?void 0:k.isMuted)!==null&&w!==void 0?w:!1});v&&x&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!sg()&&!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 gn.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)),v}()})}setupLocalParticipantEvents(){this.localParticipant.on(ae.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ae.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ae.AttributesChanged,this.onLocalAttributesChanged).on(ae.TrackMuted,this.onLocalTrackMuted).on(ae.TrackUnmuted,this.onLocalTrackUnmuted).on(ae.LocalTrackPublished,this.onLocalTrackPublished).on(ae.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ae.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ae.MediaDevicesError,this.onMediaDevicesError).on(ae.AudioStreamAcquired,this.startAudio).on(ae.ChatMessage,this.onLocalChatMessageSent).on(ae.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===Je.Connecting||this.state===Je.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===Je.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=Y8(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!==Je.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(ae.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ae.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ae.AttributesChanged,this.onLocalAttributesChanged).off(ae.TrackMuted,this.onLocalTrackMuted).off(ae.TrackUnmuted,this.onLocalTrackUnmuted).off(ae.LocalTrackPublished,this.onLocalTrackPublished).off(ae.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ae.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ae.MediaDevicesError,this.onMediaDevicesError).off(ae.AudioStreamAcquired,this.startAudio).off(ae.ChatMessage,this.onLocalChatMessageSent).off(ae.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),hi()&&(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(Je.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,zt.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(e,n,null,zt.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield s({requestId:n,callerIdentity:e,payload:r,responseTimeout:a});wg(u)>JS?(l=zt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof zt?l=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=zt.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=gn.getInstance().previousDevices,a=yield gn.getInstance().getDevices(void 0,!1),o=di();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=B8(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"&&!Tc()||l==="videoinput"||d.length>0&&!d.find(p=>p.deviceId===this.getActiveDevice(l))&&(l!=="audiooutput"||!Tc())&&(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=_S())!==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(),An(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=wh.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new wh(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(ae.TrackPublished,r=>{this.emitWhenConnected(J.TrackPublished,r,i)}).on(ae.TrackSubscribed,(r,a)=>{r.kind===F.Kind.Audio?(r.on(te.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(te.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===F.Kind.Video&&(r.on(te.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(te.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(J.TrackSubscribed,r,a,i)}).on(ae.TrackUnpublished,r=>{this.emit(J.TrackUnpublished,r,i)}).on(ae.TrackUnsubscribed,(r,a)=>{this.emit(J.TrackUnsubscribed,r,a,i)}).on(ae.TrackMuted,r=>{this.emitWhenConnected(J.TrackMuted,r,i)}).on(ae.TrackUnmuted,r=>{this.emitWhenConnected(J.TrackUnmuted,r,i)}).on(ae.ParticipantMetadataChanged,r=>{this.emitWhenConnected(J.ParticipantMetadataChanged,r,i)}).on(ae.ParticipantNameChanged,r=>{this.emitWhenConnected(J.ParticipantNameChanged,r,i)}).on(ae.AttributesChanged,r=>{this.emitWhenConnected(J.ParticipantAttributesChanged,r,i)}).on(ae.ConnectionQualityChanged,r=>{this.emitWhenConnected(J.ConnectionQualityChanged,r,i)}).on(ae.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(J.ParticipantPermissionsChanged,r,i)}).on(ae.TrackSubscriptionStatusChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionStatusChanged,r,a,i)}).on(ae.TrackSubscriptionFailed,(r,a)=>{this.emit(J.TrackSubscriptionFailed,r,i,a)}).on(ae.TrackSubscriptionPermissionChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionPermissionChanged,r,a,i)}).on(ae.Active,()=>{this.emitWhenConnected(J.ParticipantActive,i),i.kind===vc.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&&sD(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=Rn.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,lr.STATE_MISMATCH))):e=0},CP)}clearConnectionReconcile(){this.connectionReconcileInterval&&Rn.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===Je.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Je.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 eh({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Dt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Xo({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(J.SignalConnected),this.emit(J.Connected),this.setAndEmitConnectionState(Je.Connected),r.video){const o=new Pg(F.Kind.Video,new Bs({source:Zt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sr.AUDIO,name:"video-dummy"}),new kh(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:OS(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(ae.LocalTrackPublished,o)}if(r.audio){const o=new Pg(F.Kind.Audio,new Bs({source:Zt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sr.AUDIO}),new Sh(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:dg(),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(ae.LocalTrackPublished,o)}for(let o=0;o<a.count-1;o+=1){let s=new Xo({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:js.ACTIVE,tracks:[],joinedAt:Dt.parse(Date.now())});const l=this.getOrCreateParticipant(s.identity,s);if(a.video){const c=OS(160*((i=a.aspectRatios[o%a.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Bs({source:Zt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sr.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}if(a.audio){const c=dg(),u=new Bs({source:Zt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sr.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=pk(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)}}Xs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function pk(t){return t.map(e=>{if(e)return Array.isArray(e)?pk(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var fr;(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"})(fr||(fr={}));class Ja extends Dr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=fr.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new Xs(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return E(this,void 0,void 0,function*(){if(this.status!==fr.IDLE)throw Error("check is running already");this.setStatus(fr.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!==fr.SKIPPED&&this.setStatus(this.isSuccess()?fr.SUCCESS:fr.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===Je.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!==Je.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(fr.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 An(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 EP extends Ja{get description(){return"Cloud regions"}perform(){return E(this,void 0,void 0,function*(){const e=new $e(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 v=0;v<l;v++)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(v=>{v.type==="candidate-pair"&&v.nominated&&(p.rtt=v.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Lg=1e4;class RP extends Ja{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/(Lg/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Lg/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,Lg)),clearInterval(d),s.stop(),n.remove(),yield this.disconnect(),u})}}class AP extends Ja{get description(){return"Can publish audio"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield xP();if(yield yS(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 NP extends Ja{get description(){return"Can publish video"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield _P();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 OP extends Ja{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!==Je.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 MP extends Ja{get description(){return"Can connect via TURN"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;Vs(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new $e(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new gg,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 DP extends Ja{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&&(PP(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 PP(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 LP extends Ja{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 gg,a;try{a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1})}catch(o){if(Vs(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const l=yield new $e(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)===lx.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 jW extends Dr.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:fr.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!==fr.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(LP)})}checkWebRTC(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(DP)})}checkTURN(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(MP)})}checkReconnect(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(OP)})}checkPublishAudio(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(AP)})}checkPublishVideo(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(NP)})}checkConnectionProtocol(){return E(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(RP);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(EP)})}}function Be(t,e,n){return(e=jP(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function IP(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 jP(t){var e=IP(t,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class Yn 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(Yn,"code","ERR_JOSE_GENERIC");class BP extends Yn{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(BP,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class UP extends Yn{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(UP,"code","ERR_JWT_EXPIRED");class zP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Be(zP,"code","ERR_JOSE_ALG_NOT_ALLOWED");class FP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Be(FP,"code","ERR_JOSE_NOT_SUPPORTED");class qP extends Yn{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(qP,"code","ERR_JWE_DECRYPTION_FAILED");class HP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWE_INVALID")}}Be(HP,"code","ERR_JWE_INVALID");class VP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWS_INVALID")}}Be(VP,"code","ERR_JWS_INVALID");class GP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWT_INVALID")}}Be(GP,"code","ERR_JWT_INVALID");class WP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWK_INVALID")}}Be(WP,"code","ERR_JWK_INVALID");class YP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWKS_INVALID")}}Be(YP,"code","ERR_JWKS_INVALID");class KP extends Yn{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(KP,"code","ERR_JWKS_NO_MATCHING_KEY");class XP extends Yn{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(XP,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class $P extends Yn{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($P,"code","ERR_JWKS_TIMEOUT");class JP extends Yn{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(JP,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const QP=/\{[^{}]+\}/g;function ZP(){return Math.random().toString(36).slice(2,11)}function eL(t){let{baseUrl:e="",Request:n=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:a,headers:o,...s}={...t};e=bk(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:p=i,Request:v=n,headers:m,params:S={},parseAs:g="json",querySerializer:y,bodySerializer:x=a??nL,body:b,...k}=d||{};h&&(e=bk(h));let w=typeof r=="function"?r:vk(r);y&&(w=typeof y=="function"?y:vk({...typeof r=="object"?r:{},...y}));const C=b===void 0?void 0:x(b),R=C===void 0||C instanceof FormData?{}:{"Content-Type":"application/json"},A={redirect:"follow",...s,...k,body:C,headers:rL(R,o,m,S.header)};let N,O,B=new n(iL(u,{baseUrl:e,params:S,querySerializer:w}),A);for(const Y in k)Y in B||(B[Y]=k[Y]);if(l.length){N=ZP(),O=Object.freeze({baseUrl:e,fetch:p,parseAs:g,querySerializer:w,bodySerializer:x});for(const Y of l)if(Y&&typeof Y=="object"&&typeof Y.onRequest=="function"){const P=await Y.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 X=await p(B);if(l.length)for(let Y=l.length-1;Y>=0;Y--){const P=l[Y];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const V=await P.onResponse({request:B,response:X,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");X=V}}}if(X.status===204||X.headers.get("Content-Length")==="0")return X.ok?{data:{},response:X}:{error:{},response:X};if(X.ok)return g==="stream"?{data:X.body,response:X}:{data:await X[g](),response:X};let L=await X.text();try{L=JSON.parse(L)}catch{}return{error:L,response:X}}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 Ch(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 mk(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(Ch(s,e[o],n))}const a=i.join(r);return n.style==="label"||n.style==="matrix"?`${r}${a}`:a}function gk(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(Ch(t,a,n));return n.style==="label"||n.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function vk(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(gk(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(mk(r,a,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}i.push(Ch(r,a,t))}}return i.join("&")}}function tL(t,e){let n=t;for(const i of t.match(QP)??[]){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,gk(r,s,{style:o,explode:a}));continue}if(typeof s=="object"){n=n.replace(i,mk(r,s,{style:o,explode:a}));continue}if(o==="matrix"){n=n.replace(i,`;${Ch(r,s)}`);continue}n=n.replace(i,o==="label"?`.${encodeURIComponent(s)}`:encodeURIComponent(s))}return n}function nL(t){return t instanceof FormData?t:JSON.stringify(t)}function iL(t,e){var r;let n=`${e.baseUrl}${t}`;(r=e.params)!=null&&r.path&&(n=tL(n,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(n+=`?${i}`),n}function rL(...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 bk(t){return t.endsWith("/")?t.substring(0,t.length-1):t}const yk="Onboardee-Session-Token",_k="OnboardeeSessionToken";class xk{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=eL({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(_k);i&&n.headers.set(yk,i)}return n},onResponse:({response:n})=>{if(this.trackOnboardeeToken){const i=n.headers.get(yk);i&&window.localStorage&&window.localStorage.setItem(_k,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 getProductDeploymentScript(e){return await this.client.GET("/api/products/{id}/deployment-script",{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,n){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e},...n!=null&&n.environment?{query:{environment:n.environment}}:{}}})}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,v,m,S,g,y;switch((p=n.onEvent)==null||p.call(n,h),h.type){case"started":(v=n.onStarted)==null||v.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(oa(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(oa(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 Sk(s);console.error("[TranscriptChat] HTTP error:",{status:s.status,payload:h}),a(oa(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 Sk(s);console.error("[TranscriptChat] Invalid content type:",l),a(oa(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(oa(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 v=d.split(`
42
+ `},_g}var VS;function MD(){if(VS)return hr;VS=1;var t=ND(),e=OD(),n=yg();return hr.grammar=n,hr.write=e,hr.parse=t.parse,hr.parseParams=t.parseParams,hr.parseFmtpConfig=t.parseFmtpConfig,hr.parsePayloads=t.parsePayloads,hr.parseRemoteCandidates=t.parseRemoteCandidates,hr.parseImageAttributes=t.parseImageAttributes,hr.parseSimulcastStreamList=t.parseSimulcastStreamList,hr}var Xa=MD();function xg(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),v=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(v,p);s&&s(x),u.forEach(function(b){return(0,b.resolve)(x)}),u=[]}},d()),g){var y=t.apply(v,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(v){return(0,v.reject)(p)}),u=[]},h}const DD=.7,PD=20,Ks={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class GS extends Dr.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=xg(r=>E(this,void 0,void 0,function*(){this.emit(Ks.NegotiationStarted);try{yield this.createAndSendOffer()}catch(a){if(r)r(a);else throw a}}),PD),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=ta((i=n.loggerName)!==null&&i!==void 0?i:ur.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new Vn}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}=LD(e);this.remoteStereoMids=a,this.remoteNackMids=o}else if(e.type==="answer"){const a=Xa.parse((i=e.sdp)!==null&&i!==void 0?i:"");a.media.forEach(o=>{const s=Sg(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=Xa.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(Ks.NegotiationComplete),e.sdp&&Xa.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Ks.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=Xa.parse((n=a.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(s=>{YS(s),s.type==="audio"?WS(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||(dr(l.codec)&&!Qo()&&this.ensureVideoDDExtensionForSVC(s,o),!dr(l.codec)))return!0;const u=Math.round(l.maxbr*DD);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,Xa.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=Xa.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{YS(r),r.type==="audio"&&WS(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Xa.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 sn("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 sn("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 Qm(a)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===kS))){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:kS})}}}function WS(t,e,n){const i=Sg(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 LD(t){var e;const n=[],i=[],r=Xa.parse((e=t.sdp)!==null&&e!==void 0?e:"");let a=0;return r.media.forEach(o=>{var s;const l=Sg(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 YS(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 Sg(t){return typeof t=="number"?t.toFixed(0):t}const kg="vp8",ID={audioPreset:Zm.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:tg.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:kg,backupCodec:!0,preConnectBuffer:!1},KS={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},XS={deviceId:{ideal:"default"},resolution:xc.h720.resolution},jD={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new g8,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},Tg={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ut;(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"})(Ut||(Ut={}));class BD{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Tg.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=Ut.CONNECTED:l.some(c=>c==="failed")?this.state=Ut.FAILED:l.some(c=>c==="connecting")?this.state=Ut.CONNECTING:l.every(c=>c==="closed")?this.state=Ut.CLOSED:l.some(c=>c==="closed")?this.state=Ut.CLOSING:l.every(c=>c==="new")&&(this.state=Ut.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Ut[s]," to ").concat(Ut[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=ta((r=i.loggerName)!==null&&r!==void 0?r:ur.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=n!=="subscriber-primary",this.isSubscriberConnectionRequired=n==="subscriber-primary",this.publisher=new GS(e,i),n!=="publisher-only"&&(this.subscriber=new GS(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,cr.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,cr.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=Ut.NEW,this.connectionLock=new Vn,this.remoteOfferLock=new Vn}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===cr.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(Ks.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Ks.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===cr.PUBLISHER?this.publisher.getConnectedAddress():e===cr.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),Rn.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=Rn.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(_e.internal("could not establish pc connection"))},o);for(;this.state!==Ut.CONNECTED;)if(yield An(50),r!=null&&r.signal.aborted){c(_e.cancelled("room connection has been cancelled"));return}Rn.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}const $S=5e3,UD=3e4;class $e{static fetchRegionSettings(e,n,i){return E(this,void 0,void 0,function*(){const r=yield $e.fetchLock.lock();try{const a=yield fetch("".concat(zD(e),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(a.ok){const o=uD(a.headers),s=o?o*1e3:$S;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=$e.settingsTimeouts.get(e.hostname);clearTimeout(r),$e.settingsTimeouts.set(e.hostname,setTimeout(()=>E(this,void 0,void 0,function*(){try{const a=yield $e.fetchRegionSettings(e,n);$e.updateCachedRegionSettings(e,n,a)}catch(a){if(a instanceof _e&&a.reason===Ct.NotAllowed){Ee.debug("token is not valid, cancelling auto region refresh");return}Ee.debug("auto refetching of region settings failed",{error:a}),$e.scheduleRefetch(e,n,i)}}),i))})}static updateCachedRegionSettings(e,n,i){$e.cache.set(e.hostname,i),$e.scheduleRefetch(e,n,i.maxAgeInMs)}static stopRefetch(e){const n=$e.settingsTimeouts.get(e);n&&(clearTimeout(n),$e.settingsTimeouts.delete(e))}static scheduleCleanup(e){let n=$e.connectionTrackers.get(e);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{const i=$e.connectionTrackers.get(e);i&&i.connectionCount===0&&(Ee.debug("stopping region refetch after disconnect delay",{hostname:e}),$e.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},UD))}static cancelCleanup(e){const n=$e.connectionTrackers.get(e);n!=null&&n.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let n=$e.connectionTrackers.get(e);n||(n={connectionCount:0},$e.connectionTrackers.set(e,n)),n.connectionCount++,$e.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,n=$e.connectionTrackers.get(e);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&$e.scheduleCleanup(e))}constructor(e,n){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Vs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return E(this,void 0,void 0,function*(){return $e.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=$e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(e),$e.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){$e.updateCachedRegionSettings(this.serverUrl,this.token,e)}}$e.cache=new Map,$e.settingsTimeouts=new Map,$e.connectionTrackers=new Map,$e.fetchLock=new Vn;function zD(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class zt extends Error{constructor(e,n,i){super(n),this.code=e,this.message=QS(n,zt.MAX_MESSAGE_BYTES),this.data=i?QS(i,zt.MAX_DATA_BYTES):void 0}static fromProto(e){return new zt(e.code,e.message,e.data)}toProto(){return new ax({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new zt(zt.ErrorCode[e],zt.ErrorMessage[e],n)}}zt.MAX_MESSAGE_BYTES=256,zt.MAX_DATA_BYTES=15360,zt.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},zt.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 JS=15360;function wg(t){return new TextEncoder().encode(t).length}function QS(t,e){if(wg(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 Cg=2e3;function xh(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 Eg=typeof MediaRecorder<"u";class FD{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const qD=Eg?MediaRecorder:FD;class HD extends qD{constructor(e,n){if(!Eg)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 VD(){return Eg}const GD=1e3,WD=1e4;class ZS extends F{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=xg(()=>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(te.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Vn,this.pauseUpstreamLock=new Vn,this.trackChangeLock=new Vn,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!==F.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=>{Hs(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&&(qs(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=>{qs(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]:GD;return function*(){var i;if(e.kind===F.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=di())===null||i===void 0?void 0:i.os)==="iOS"&&(yield An(10));const r=Date.now();for(;Date.now()-r<n;){const a=e.dimensions;if(a)return a;yield An(50)}throw new ia("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===Va(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Va(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===F.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),a=e.kind===F.Kind.Audio?"audioinput":"videoinput";return n?gn.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 ia("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=v8(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===F.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?Object.assign({deviceId:i},a):!0,this.attachedElements.forEach(c=>{Hs(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===F.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(te.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?te.Muted:te.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),wS()&&(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(te.UpstreamPaused,this);const i=di();if((i==null?void 0:i.name)==="Safari"&&Ir(i.version,"12.0")<0)throw new Jm("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(te.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(qs(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&&(Hs(i._mediaStreamTrack,c),qs(i.processor.processedTrack,c));yield(a=i.sender)===null||a===void 0?void 0:a.replaceTrack(i.processor.processedTrack)}i.emit(te.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(te.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!VD()){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 HD(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},WD)}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 Sh extends ZS{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,F.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=xh(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(te.AudioTrackFeatureUpdate,this,mn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(te.AudioTrackFeatureUpdate,this,mn.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===F.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!==Va(this._constraints.deviceId);return this.source===F.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=ig({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(){hi()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Cg)))}setProcessor(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Lr()&&!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(te.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 yS(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(te.AudioSilenceDetected)),e})}}function YD(t,e,n){switch(t.kind){case"audio":return new Sh(t,e,!1,void 0,n);case"video":return new kh(t,e,!1,n);default:throw new ia("unsupported track type: ".concat(t.kind))}}const KD=Object.values(xc),XD=Object.values(eg),$D=Object.values(tg),JD=[xc.h180,xc.h360],QD=[eg.h180,eg.h360],ZD=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ft(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)}),Rg=["q","h","f"];function Ag(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=tP(t,e,n,c),Ee.debug("using video encoding",o));const u=o.maxFramerate,d=new ft(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(l&&dr(c)){const v=new nk(l),m=[];if(v.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const S=di();if(Tc()||Lr()||(S==null?void 0:S.name)==="Chrome"&&Ir(S==null?void 0:S.version,"113")<0){const g=v.suffix=="h"?2:3,y=Q8(S);for(let x=0;x<v.spatial;x+=1)m.push({rid:Rg[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=tk(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:ek(t,d):h=(a=tk(i==null?void 0:i.videoSimulcastLayers))!==null&&a!==void 0?a:ek(t,d);let p;if(h.length>0){const v=h[0];h.length>1&&([,p]=h);const m=Math.max(e,n);if(m>=960&&p)return Ng(e,n,[v,p,d],u);if(m>=480)return Ng(e,n,[v,d],u)}return Ng(e,n,[d])}function eP(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===F.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Ag(t.source===F.Source.ScreenShare,l,c,n)}function tP(t,e,n,i){const r=nP(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 nP(t,e,n){if(t)return $D;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?KD:XD}function ek(t,e){if(t)return ZD(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)?JD:QD}function Ng(t,e,n,i){const r=[];if(n.forEach((a,o)=>{if(o>=Rg.length)return;const s=Math.min(t,e),c={rid:Rg[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=Jo()||o===0;a.encoding.priority&&d&&(c.priority=a.encoding.priority,c.networkPriority=a.encoding.priority),r.push(c)}),Lr()&&ES()==="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 tk(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 nk{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 iP(t){return t.source===F.Source.ScreenShare||t.constraints.height&&Va(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const rP=5e3;class kh extends ZS{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,F.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(te.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+=xh(c,h)}),this._currentBitrate=l}this.prevStats=o}),this.senderLock=new Vn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!hi())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()},Cg))}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=na(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=na(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===F.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===F.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=Ti.LOW;i<=Ti.HIGH;i+=1)n.push(new jm({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(dr(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=ig({video:e});typeof d.video!="boolean"&&(s=d.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var l=!0,c=na(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=na(r.simulcastCodecs.values()),v;v=yield p.next(),o=v.done,!o;h=!0)c=v.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)},rP))}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(dr(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(n=!0,i=na(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(dr(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 ik(d.sender,d.encodings,u.qualities,this.senderLock,dr(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 ik(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&&dr(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),wS()&&this.isInBackground&&this.source===F.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ik(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 v;let m=(v=h.rid)!==null&&v!==void 0?v:"";m===""&&(m="q");const S=rk(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),Jo()&&(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 rk(t){switch(t){case"f":return Ti.HIGH;case"h":return Ti.MEDIUM;case"q":return Ti.LOW;default:return Ti.HIGH}}function ak(t,e,n,i){if(!n)return[new qa({quality:Ti.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,a=new nk(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 qa({quality:Math.min(Ti.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=rk((o=r.rid)!==null&&o!==void 0?o:"");return new qa({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 ok="_lossy",sk="_reliable",aP=2*1e3,Og="leave-reconnect",oP=3e4,sP=8*1024,lP=256*1024;var Vi;(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"})(Vi||(Vi={}));class cP extends Dr.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Tg.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Vi.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 zS,this.reliableReceivedState=new AD(oP),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===sk)a.reliableDCSub=o;else if(o.label===ok)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=Gn.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(ie.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=nx.fromBinary(h.payload),v=new Gn({value:p.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((s=v.value)===null||s===void 0?void 0:s.case)==="user"&&lk(v,v.value.value),this.emit(ie.DataPacketReceived,v,d.value.value.encryptionType)}else((l=d.value)===null||l===void 0?void 0:l.case)==="user"&&lk(d,d.value.value),this.emit(ie.DataPacketReceived,d,on.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(ie.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){a(o);return}i===Og&&(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=Rn.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Vi.Connected&&i();const a=()=>{this.off(ie.Disconnected,o),i()},o=()=>{this.off(ie.Restarted,a),r()};this.once(ie.Restarted,a),this.once(ie.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(ie.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(Cc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===gt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===gt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Ko.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>E(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Cc(this.url),{method:"HEAD"}),An(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ta((n=e.loggerName)!==null&&n!==void 0?n:ur.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new gg(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Vn,this.dataProcessLock=new Vn,this.dcBufferStatus=new Map([[Oe.LOSSY,!0],[Oe.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(ie.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(ie.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(ie.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(ie.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(ie.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(ie.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(ie.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(ie.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(ie.SignalConnected,a),a}catch(a){if(a instanceof _e&&a.reason===Ct.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(ie.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 zS,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 ia("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!==Ut.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new BD(r,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(ie.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===Ut.CONNECTED){const u=this.pcState===Vi.New;this.pcState=Vi.Connected,u&&this.emit(ie.Connected,e)}else a===Ut.FAILED&&(this.pcState===Vi.Connected||this.pcState===Vi.Reconnecting)&&(this.pcState=Vi.Disconnected,this.handleDisconnect("peerconnection failed",s==="failed"?Ko.RR_SUBSCRIBER_FAILED:Ko.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===gt.RECONNECTING,c=[Ut.FAILED,Ut.CLOSING,Ut.CLOSED].includes(a);l&&c&&!this._isClosed&&this.emit(ie.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(ie.MediaTrackAdded,a.track,a.streams[0],a.receiver)},uP((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(ie.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ie.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(ie.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ie.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(ie.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",Ko.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:$S,regionSettings:e.regions})),e.action){case Us.DISCONNECT:this.emit(ie.Disconnected,e==null?void 0:e.reason),this.close();break;case Us.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Og);break;case Us.RESUME:this.handleDisconnect(Og)}}}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===gc.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(ok,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(sk,{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,sP),lP)}},1e3))}createSender(e,n,i){return E(this,void 0,void 0,function*(){if(ag())return yield this.createTransceiverRTCRtpSender(e,n,i);if(og())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new sn("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(ag())return this.createSimulcastTransceiverSender(e,n,i,r);if(og())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new sn("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new sn("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ga(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 sn("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 sn("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)===gc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Ut.NEW)===Ut.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 sn?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:a})),o=!1):a instanceof Fs||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Ko.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(ie.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 sn("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ie.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 Fs;a=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof _e&&o.reason===Ct.NotAllowed?new sn("could not reconnect, token might be expired"):new Fs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ie.SignalRestarted,a),yield this.waitForPCReconnected(),this.client.currentState!==gt.CONNECTED)throw new Fs("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(ie.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 sn("could not reconnect, url or token not saved");if(!this.pcManager)throw new sn("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ie.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===Ct.NotAllowed?new sn("could not reconnect, token might be expired"):r instanceof _e&&r.reason===Ct.LeaveRequest?r:new Fs(a)}if(this.emit(ie.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!==gt.CONNECTED)throw new Fs("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(ie.Resumed)})}waitForPCInitialConnection(e,n){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new sn("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return E(this,void 0,void 0,function*(){this.pcState=Vi.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield An(aP),!this.pcManager)throw new sn("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Vi.Connected}catch(e){throw this.pcState=Vi.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 Gn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcResponse",value:new Nm({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 Gn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcAck",value:new Am({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=bD(e);if(a){const o=yield this.e2eeManager.encryptData(a.toBinary());e.value={case:"encryptedPacket",value:new tx({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(ie.Closing,r);!this.dcBufferStatus.get(e);)yield An(10);this.off(ie.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 sn("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 An(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!==Ut.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 Qm("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(ie.Closing,r),this.pcManager.publisher.once(Ks.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(s=>{const l=s.codec.toLowerCase();iD(l)&&o.set(s.payload,l)}),this.emit(ie.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(a){a instanceof Qm&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ko.RR_UNKNOWN),n(a)}finally{this.off(ie.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(v=>{v.isDesired!==d&&h.push(v.trackSid),v.isEnabled||p.push(v.trackSid)}),this.client.sendSyncState(new Bm({answer:this.options.singlePeerConnection?l?Ys({sdp:l.sdp,type:l.type}):void 0:u?Ys({sdp:u.sdp,type:u.type}):void 0,offer:this.options.singlePeerConnection?s?Ys({sdp:s.sdp,type:s.type}):void 0:c?Ys({sdp:c.sdp,type:c.type}):void 0,subscription:new lh({trackSids:h,subscribe:!d,participantTracks:[]}),publishTracks:z8(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((v,m)=>new kx({publisherSid:m,lastSeq:v}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Tx({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Oe.LOSSY),cr.PUBLISHER),n(this.dataChannelForKind(Oe.RELIABLE),cr.PUBLISHER),n(this.dataChannelForKind(Oe.LOSSY,!0),cr.SUBSCRIBER),n(this.dataChannelForKind(Oe.RELIABLE,!0),cr.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Rn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){hi()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){hi()&&(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 uP(t){return t!==void 0&&t>13}function lk(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 ck{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 qi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Wn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new qi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Wn.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class dP extends ck{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 Hi,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=na(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 hP extends ck{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=_h(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 Hi,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 qi("Cannot decode datastream chunk ".concat(u.chunkIndex," as text: ").concat(h),Wn.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=na(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 fP{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 qi('A text stream handler for topic "'.concat(e,'" has already been set.'),Wn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new qi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Wn.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 qi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Wn.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 Hi;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:_h(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new qi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Wn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new dP(l,c,_h(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 Hi;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 qi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Wn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new hP(l,c,_h(e.totalLength),s),{identity:n})}})}handleStreamChunk(e,n){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Wn.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 qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Wn.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 qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Wn.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 qi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Wn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class uk{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 pP extends uk{}class mP extends uk{}const dk=15e3;class gP{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 v=l.reduce((m,S)=>m+S,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,v)},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?on.GCM:on.NONE},s=new ih({streamId:a,mimeType:o.mimeType,topic:o.topic,timestamp:Zo(o.timestamp),totalLength:Zo(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new px({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"?Om.UPDATE:Om.CREATE})}}),l=e==null?void 0:e.destinationIdentities,c=new Gn({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 cD(m,dk)){const g=new rh({content:S,streamId:a,chunkIndex:Zo(u)}),y=new Gn({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 ah({streamId:a}),S=new Gn({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 v.close()});d.once(ie.Closing,p);const v=new pP(h,o,()=>this.engine.off(ie.Closing,p));return v})}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?on.GCM:on.NONE},d=new ih({totalLength:Zo((s=u.size)!==null&&s!==void 0?s:0),mimeType:u.mimeType,streamId:l,topic:u.topic,timestamp:Zo(Date.now()),attributes:u.attributes,contentHeader:{case:"byteHeader",value:new mx({name:u.name})}}),h=new Gn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(h,Oe.RELIABLE);let p=0;const v=new Vn,m=this.engine,S=this.log,g=new WritableStream({write(x){return E(this,void 0,void 0,function*(){const b=yield v.lock();let k=0;try{for(;k<x.byteLength;){const w=x.slice(k,k+dk),C=new Gn({destinationIdentities:c,value:{case:"streamChunk",value:new rh({content:w,streamId:l,chunkIndex:Zo(p)})}});yield m.sendDataPacket(C,Oe.RELIABLE),p+=1,k+=w.byteLength}}finally{b()}})},close(){return E(this,void 0,void 0,function*(){const x=new ah({streamId:l}),b=new Gn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield m.sendDataPacket(b,Oe.RELIABLE)})},abort(x){S.error("Sink error:",x)}});return new mP(g,u)})}}class hk extends F{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?te.Muted:te.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(te.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(),Cg)),F8()&&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(te.TimeSyncUpdate,{timestamp:r,rtpTimestamp:a}),this.rtpTimestamp=a)}};e()}}class vP extends hk{constructor(e,n,i,r,a,o){super(e,n,F.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=xh(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;Lr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Lr())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(sg(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&sg(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(te.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(te.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 Mg=100;class bP extends hk{constructor(e,n,i,r,a){super(e,n,F.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=xh(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=xg(()=>{this.updateDimensions()},Mg),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===F.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Hs(this._mediaStreamTrack,n):qs(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 yP(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<Mg){Rn.setTimeout(()=>{this.updateVisibility()},Mg);return}this.lastVisible=s,this.emit(te.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(te.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?RS():n||(RS()>2?2:1)}}class yP{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=Ac(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=Ac(this.element),(a=this.handleVisibilityChanged)===null||a===void 0||a.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ac(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??Dg(e),this.isPiP=hi()&&Ac(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=Dg(this.element),this.isPiP=Ac(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,NS().observe(this.element),AS().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=NS())===null||e===void 0||e.unobserve(this.element),(n=AS())===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 Ac(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Dg(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function Dg(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 aa extends Dr.EventEmitter{constructor(e,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=on.NONE,this.log=Ee,this.handleMuted=()=>{this.emit(te.Muted)},this.handleUnmuted=()=>{this.emit(te.Unmuted)},this.log=ta((a=r==null?void 0:r.loggerName)!==null&&a!==void 0?a:ur.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=F.Source.Unknown}setTrack(e){this.track&&(this.track.off(te.Muted,this.handleMuted),this.track.off(te.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(te.Muted,this.handleMuted),e.on(te.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!==on.NONE}get audioTrack(){if(jr(this.track))return this.track}get videoTrack(){if(Ga(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=F.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===F.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={}))})(aa||(aa={}));class Pg extends aa{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(te.Ended)},this.handleCpuConstrained=()=>{this.track&&Ga(this.track)&&this.emit(te.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(te.Ended,this.handleTrackEnded),this.track.off(te.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(te.Ended,this.handleTrackEnded),e.on(te.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(jr(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(mn.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(mn.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(mn.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(mn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(mn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(mn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Th(t,e){return E(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:a}=xS(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=bS(a,KS,XS),c=ig(l),u=navigator.mediaDevices.getUserMedia(c);a.audio&&(gn.userMediaPromiseMap.set("audioinput",u),u.catch(()=>gn.userMediaPromiseMap.delete("audioinput"))),a.video&&(gn.userMediaPromiseMap.set("videoinput",u),u.catch(()=>gn.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 v=p?l.audio:l.video;(typeof v=="boolean"||!v)&&(v={});let m;const S=p?c.audio:c.video;typeof S!="boolean"&&(m=S);const g=h.getSettings().deviceId;m!=null&&m.deviceId&&Va(m.deviceId)!==g?m.deviceId=g:m||(m={deviceId:g});const y=YD(h,m,e);return y.kind===F.Kind.Video?y.source=F.Source.Camera:y.kind===F.Kind.Audio&&(y.source=F.Source.Microphone),y.mediaStream=d,jr(y)&&i?yield y.setProcessor(i):Ga(y)&&r&&(yield y.setProcessor(r)),y})))}catch(d){if(!n)throw d;return Th(Object.assign(Object.assign({},t),{audio:o,video:s}),e)}})}function _P(t){return E(this,void 0,void 0,function*(){return(yield Th({audio:!1,video:t??!0}))[0]})}function xP(t){return E(this,void 0,void 0,function*(){return(yield Th({audio:t??!0,video:!1}))[0]})}var $a;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})($a||($a={}));function SP(t){switch(t){case mc.EXCELLENT:return $a.Excellent;case mc.GOOD:return $a.Good;case mc.POOR:return $a.Poor;case mc.LOST:return $a.Lost;default:return $a.Unknown}}class fk extends Dr.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===vc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===js.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]:vc.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=$a.Unknown,this.log=Ee,this.log=ta((l=o==null?void 0:o.loggerName)!==null&&l!==void 0?l:ur.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 Hi,this.once(ae.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(F.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(F.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(F.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===js.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==js.ACTIVE&&this.emit(ae.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(ae.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(ae.ParticipantNameChanged,e)}_setAttributes(e){const n=q8(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(ae.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(ae.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ae.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=SP(e),n!==this._connectionQuality&&this.emit(ae.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=>jr(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(te.Muted,()=>{this.emit(ae.TrackMuted,e)}),e.on(te.Unmuted,()=>{this.emit(ae.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case F.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case F.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function kP(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 xx({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 TP extends fk{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=on.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Hi)},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 Hi),(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!==Um.OK&&d.reject(new gS(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=zt.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=>kP(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(ae.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 v=yield p.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var m=!0,S=na(v),g;g=yield S.next(),l=g.done,!l;m=!0){d=g.value,m=!1;const y=d;j8(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===F.Source.ScreenShare||s.source===F.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(ra(s)||Wa(s))try{if(hi())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:s.source===F.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))),ra(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!==on.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(ie.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(ie.Connected,this.handleReconnected).on(ie.SignalConnected,this.handleSignalConnected).on(ie.SignalRestarted,this.handleReconnected).on(ie.SignalResumed,this.handleReconnected).on(ie.Restarting,this.handleReconnecting).on(ie.Resuming,this.handleReconnecting).on(ie.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ie.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ie.Closing,this.handleClosing).on(ie.SignalRequestResponse,this.handleSignalRequestResponse).on(ie.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:v=>{l(v),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(v=>{let[m,S]=v;return this.attributes[m]===S||S===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),s();return}yield An(50)}l(new gS("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(F.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(F.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(F.Source.ScreenShare,e,n,i)}setE2EEEnabled(e){return E(this,void 0,void 0,function*(){this.encryptionType=e?on.GCM:on.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 F.Source.Camera:l=yield this.createTracks({video:(a=i)!==null&&a!==void 0?a:!0});break;case F.Source.Microphone:l=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case F.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new ia(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(ae.MediaDevicesError,c,rg(e)),this.pendingPublishing.delete(e),c}for(const c of l){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===F.Source.Microphone&&jr(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===F.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const l=this.getTrackPublication(F.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(F.Source.Camera)||this.pendingPublishing.has(F.Source.Microphone))){this.pendingPublishing.add(F.Source.Camera),this.pendingPublishing.add(F.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(F.Source.Camera),this.pendingPublishing.delete(F.Source.Microphone)}}})}createTracks(e){return E(this,void 0,void 0,function*(){var n,i;e??(e={});const r=bS(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 Th(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(jr(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=F.Source.Microphone,this.emit(ae.AudioStreamAcquired)),Ga(s)&&(this.cameraError=void 0,s.source=F.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 Jm("getDisplayMedia not supported");e.resolution===void 0&&!J8()&&(e.resolution=tg.h1080fps30.resolution);const n=U8(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new ia("no video track found");const a=new kh(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=F.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);const o=[a];if(i.getAudioTracks().length>0){this.emit(ae.AudioStreamAcquired);const s=new Sh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=F.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;ra(i)&&i.setAudioContext(a.audioContext),yield(s=a.reconnectFuture)===null||s===void 0?void 0:s.promise,a.republishPromise&&!o&&(yield a.republishPromise),Gs(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 F.Source.Microphone:g="audioinput";break;case F.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 Sh(i,d,!0,a.audioContext,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;case"video":i=new kh(i,d,!0,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;default:throw new ia("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),v="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(l=p.forceStereo)!==null&&l!==void 0?l:v;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)),!Z8()&&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!==gt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:je(i)}));let x=!1;const b=setTimeout(()=>{x=!0,i.stop(),y(new mS("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),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 Hi),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=>H8(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 mS("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Gs(e)&&A.source===e.source)&&e.source!==F.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&&jr(e)&&(e.stopOnMute=!0),e.source===F.Source.ScreenShare&&Jo()&&(n.simulcast=!1),n.videoCodec==="av1"&&!K8()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!X8()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=kg),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>n.videoCodec===Sc(A.mime))||(n.videoCodec=Sc(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;e.on(te.Muted,this.onTrackMuted),e.on(te.Unmuted,this.onTrackUnmuted),e.on(te.Ended,this.handleTrackEnded),e.on(te.UpstreamPaused,this.onTrackUpstreamPaused),e.on(te.UpstreamResumed,this.onTrackUpstreamResumed),e.on(te.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],g=!(!((r=n.dtx)!==null&&r!==void 0)||r),y=e.getSourceTrackSettings();y.autoGainControl&&S.push(mn.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&S.push(mn.TF_ECHO_CANCELLATION),y.noiseSuppression&&S.push(mn.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&S.push(mn.TF_STEREO),g&&S.push(mn.TF_NO_DTX),ra(e)&&e.hasPreConnectBuffer&&S.push(mn.TF_PRECONNECT_BUFFER);const x=new bc({cid:e.mediaStreamTrack.id,name:n.name,type:F.kindToProto(e.kind),muted:e.isMuted,source:F.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 b;if(e.kind===F.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:xc.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,Wa(e)&&(dr(m)&&(e.source===F.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 Dm({codec:m,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:kg}),n.backupCodec&&m!==n.backupCodec.codec&&x.encryption===on.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Dm({codec:n.backupCodec.codec,cid:""})))),b=Ag(e.source===F.Source.ScreenShare,x.width,x.height,n),x.layers=ak(x.width,x.height,b,dr(n.videoCodec))}else e.kind===F.Kind.Audio&&(b=[{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 sn("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 sn("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,b),this.emit(ae.LocalSenderCreated,e.sender,e),Wa(e)&&((A=n.degradationPreference)!==null&&A!==void 0||(n.degradationPreference=iP(e)),e.setDegradationPreference(n.degradationPreference)),b)if(Jo()&&e.kind===F.Kind.Audio){let B;for(const X of this.engine.pcManager.publisher.getTransceivers())if(X.sender===e.sender){B=X;break}B&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:B,codec:"opus",maxbr:!((N=b[0])===null||N===void 0)&&N.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&dr(e.codec)&&(!((O=b[0])===null||O===void 0)&&O.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let w;const C=new Promise((A,N)=>E(this,void 0,void 0,function*(){var O;try{w=yield this.engine.addTrack(x),A(w)}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(X=>{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:X}))})),N(B)}}));if(this.enabledPublishVideoCodecs.length>0)w=(yield Promise.all([C,k()]))[0];else{w=yield C;let A;if(w.codecs.forEach(N=>{A===void 0&&(A=N.mimeType)}),A&&e.kind===F.Kind.Video){const N=Sc(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,b=Ag(e.source===F.Source.ScreenShare,x.width,x.height,n))}yield k()}const R=new Pg(e.kind,w,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(R.on(te.CpuConstrained,A=>this.onTrackCpuConstrained(A,R)),R.options=n,e.sid=w.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:w})),Wa(e)?e.startMonitor(this.engine.client):ra(e)&&e.startMonitor(),this.addTrackPublication(R),this.emit(ae.LocalTrackPublished,R),ra(e)&&w.audioFeatures.includes(mn.TF_PRECONNECT_BUFFER)){const A=e.getPreConnectBuffer(),N=e.getPreConnectBufferMimeType();this.on(ae.LocalTrackSubscribed,O=>{if(O.trackSid===w.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,X)=>E(this,void 0,void 0,function*(){var L,Y,P,V,K,ee;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),je(e)));const Q=setTimeout(()=>{X(new Error("agent not active within 10 seconds"))},1e4),le=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:[le.identity],attributes:{trackId:R.trackSid,sampleRate:String((K=y.sampleRate)!==null&&K!==void 0?K:"48000"),channels:String((ee=y.channelCount)!==null&&ee!==void 0?ee:"1")}});try{for(var $=!0,U=na(A),Z;Z=yield U.next(),L=Z.done,!L;$=!0){V=Z.value,$=!1;const ge=V;yield j.write(ge)}}catch(ge){Y={error:ge}}finally{try{!$&&!L&&(P=U.return)&&(yield P.call(U))}finally{if(Y)throw Y.error}}yield j.close(),B()}catch(Q){X(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!==on.NONE)return;let a;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(a=p)}),!a)throw new ia("track is not published");if(!Wa(e))throw new ia("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=eP(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 bc({cid:l.mediaStreamTrack.id,type:F.kindToProto(e.kind),muted:e.isMuted,source:F.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=ak(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new sn("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(Gs(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(te.Muted,this.onTrackMuted),e.off(te.Unmuted,this.onTrackUnmuted),e.off(te.Ended,this.handleTrackEnded),e.off(te.UpstreamPaused,this.onTrackUpstreamPaused),e.off(te.UpstreamResumed,this.onTrackUpstreamResumed),e.off(te.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<Ut.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),Wa(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 F.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case F.Kind.Video:this.videoTrackPublications.delete(a.trackSid);break}return this.emit(ae.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!==F.Source.ScreenShare&&c.source!==F.Source.ScreenShareAudio&&(ra(c)||Wa(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 Em({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:s});const c=new Gn({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 Gn({kind:Oe.RELIABLE,value:{case:"sipDtmf",value:new rx({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 Gn({value:{case:"chatMessage",value:new nh(Object.assign(Object.assign({},i),{timestamp:Dt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(ae.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 Gn({value:{case:"chatMessage",value:new nh(Object.assign(Object.assign({},i),{timestamp:Dt.parse(i.timestamp),editTimestamp:Dt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Oe.RELIABLE),this.emit(ae.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,v,m;if(wg(o)>JS){d(zt.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&&Ir((m=(v=this.engine.latestJoinResponse)===null||v===void 0?void 0:v.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){d(zt.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(zt.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(zt.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(g,{resolve:(b,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(b??"")},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 Gn({destinationIdentities:[e],kind:Oe.RELIABLE,value:{case:"rpcRequest",value:new Rm({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,zt.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 Hi),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(ra(r)||Wa(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 An(20)}})}}class wP extends aa{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(te.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 lh({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ox({participantSid:"",trackSids:[this.trackSid]})]});this.emit(te.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?aa.SubscriptionStatus.Unsubscribed:super.isSubscribed?aa.SubscriptionStatus.Subscribed:aa.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?aa.PermissionStatus.Allowed:aa.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||(fg(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&fg(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ti.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(te.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(te.VisibilityChanged,this.handleVisibilityChange),r.off(te.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(te.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(te.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(te.VisibilityChanged,this.handleVisibilityChange),e.on(te.Ended,this.handleEnded),this.emit(te.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(te.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?te.Muted:te.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(te.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(te.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 fg(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new vx({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===F.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)SS(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=V8(this.trackInfo,this.requestedMaxQuality);i&&SS(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:Ti.HIGH})),e.quality=Ti.HIGH)}this.emit(te.UpdateSettings,e)}}class wh extends fk{static fromParticipantInfo(e,n,i){return new wh(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]:vc.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(te.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(te.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(te.SubscriptionPermissionChanged,n=>{this.emit(ae.TrackSubscriptionPermissionChanged,e,n)}),e.on(te.SubscriptionStatusChanged,n=>{this.emit(ae.TrackSubscriptionStatusChanged,e,n)}),e.on(te.Subscribed,n=>{this.emit(ae.TrackSubscribed,n,e)}),e.on(te.Unsubscribed,n=>{this.emit(ae.TrackUnsubscribed,n,e)}),e.on(te.SubscriptionFailed,n=>{this.emit(ae.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]:F.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]:F.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(ae.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(ae.TrackSubscriptionFailed,n);return}const l=e.kind==="video";let c;return l?c=new bP(e,n,r,a):c=new vP(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)&&hg(c)&&jr(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=F.kindFromProto(r.type);if(!l)return;s=new wP(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!==F.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(ae.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 F.Kind.Audio:this.audioTrackPublications.delete(e);break;case F.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(ae.TrackUnpublished,i)}setAudioOutput(e){return E(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;jr(i.track)&&hg(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 Je;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(Je||(Je={}));const CP=4*1e3;class Xs extends Dr.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var n,i,r,a;if(super(),n=this,this.state=Je.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(!$8())throw Lr()?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===Je.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(Je.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==DS(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Vs(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new $e(o,s):this.regionUrlProvider.updateToken(s),this.regionUrlProvider.fetchRegionSettings().then(p=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const d=(p,v,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 Ws.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!==Ct.Cancelled&&x.reason!==Ct.NotAllowed){let b=null;try{this.log.debug("Fetching next region"),b=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===Ct.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(k);return}}[Ct.InternalError,Ct.ServerUnreachable,Ct.Timeout].includes(x.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Ws.getInstance().addFailedConnectionAttempt(o)),b&&!(!((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(b),this.logContext),this.recreateEngine(),yield d(p,v,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,MS(x)),v(x))}else{let b=lr.UNKNOWN_REASON;x instanceof _e&&(b=MS(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),v(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Hi((p,v)=>{d(p,v,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,s,l,c,u,d)=>E(this,void 0,void 0,function*(){var h,p,v;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:(v=m.participant)===null||v===void 0?void 0:v.identity}),!S.version)throw new M8("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===Je.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({},Tg),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}hi()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),hi()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Je.Connected),this.emit(J.Connected),Ws.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 v=yield c.disconnectLock.lock();try{if(c.state===Je.Disconnected){c.log.debug("already disconnected",c.logContext);return}if(c.log.info("disconnect from room",Object.assign({},c.logContext)),c.state===Je.Connecting||c.state===Je.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,lr.CLIENT_INITIATED),c.engine=void 0}finally{v()}}()})},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=di();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=dg();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(Je.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(Je.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===js.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=F.streamStateFromProto(s.state);c.track.setStreamState(u),u!==c.track.streamState&&(l.emit(ae.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(ae.DataReceived,s.payload,l,c)},this.handleSipDtmf=(o,s)=>{this.emit(J.SipDTMFReceived,s,o),o==null||o.emit(ae.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=aD(s,this.transcriptionReceivedTimes);c==null||c.emit(te.TranscriptionReceived,u),l==null||l.emit(ae.TranscriptionReceived,u,c),this.emit(J.TranscriptionReceived,u,l,c)},this.handleChatMessage=(o,s)=>{const l=oD(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=di())===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(te.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.on(te.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),ra(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),v=rg(o.source);v&&p&&p!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,p),this.emit(J.ActiveDeviceChanged,v,p))}),this.onLocalTrackUnpublished=o=>{var s,l;(s=o.track)===null||s===void 0||s.off(te.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.off(te.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=rg(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({},jD),e),this.log=ta((i=this.options.loggerName)!==null&&i!==void 0?i:ur.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},KS),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},XS),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},ID),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new fP,this.outgoingDataStreamManager=new gP(this.engine,this.log),this.disconnectLock=new Vn,this.localParticipant=new TP("","",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",Va(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Va(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Va(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),hi()){const o=new AbortController;(a=navigator.mediaDevices)===null||a===void 0||a.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),Xs.cleanupRegistry&&Xs.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 yD(i,n),this.e2eeManager.on(Ka.ParticipantEncryptionStatusChanged,(r,a)=>{lD(a)&&(this.isE2EEEnabled=r),this.emit(J.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(Ka.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===Je.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(ie.RoomUpdate,i),e(r.sid))};this.engine.on(ie.RoomUpdate,i),this.once(J.Disconnected,()=>{this.engine.off(ie.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 cP(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ie.ParticipantUpdate,this.handleParticipantUpdates).on(ie.RoomUpdate,this.handleRoomUpdate).on(ie.SpeakersChanged,this.handleSpeakersChanged).on(ie.StreamStateChanged,this.handleStreamStateUpdate).on(ie.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ie.SubscriptionError,this.handleSubscriptionError).on(ie.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ie.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(ie.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ie.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ie.DataPacketReceived,this.handleDataPacket).on(ie.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Je.SignalReconnecting)&&this.emit(J.SignalReconnecting)}).on(ie.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Je.Connected)&&this.emit(J.Reconnected)}).on(ie.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Je.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ie.Restarting,this.handleRestarting).on(ie.SignalRestarted,this.handleSignalRestarted).on(ie.Offline,()=>{this.setAndEmitConnectionState(Je.Reconnecting)&&this.emit(J.Reconnecting)}).on(ie.DCBufferStatusChanged,(e,n)=>{this.emit(J.DCBufferStatusChanged,e,n)}).on(ie.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(ae.LocalTrackSubscribed,n),this.emitWhenConnected(J.LocalTrackSubscribed,n,this.localParticipant)}).on(ie.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 gn.getInstance().getDevices(e,n)}prepareConnection(e,n){return E(this,void 0,void 0,function*(){if(this.state===Je.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Vs(new URL(e))&&n){this.regionUrlProvider=new $e(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Je.Disconnected&&(this.regionUrl=i,yield fetch(Cc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Cc(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 Mr({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Mr({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Mr({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Mr({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 Mr({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 Mr({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 Mr({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 ch({reason:lr.CLIENT_INITIATED,action:Us.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Mr({scenario:{case:"subscriberBandwidth",value:Zo(n)}});break;case"leave-full-reconnect":r=new Mr({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 v=!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(b=>b.source===F.Source.Microphone);try{v=(yield Promise.all(y.map(b=>{var k;return(k=b.audioTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(b=>b===!0)}catch(b){throw a.options.audioCaptureDefaults.deviceId=g,b}const x=y.some(b=>{var k,w;return(w=(k=b.track)===null||k===void 0?void 0:k.isMuted)!==null&&w!==void 0?w:!1});v&&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(b=>b.source===F.Source.Camera);try{v=(yield Promise.all(y.map(b=>{var k;return(k=b.videoTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(b=>b===!0)}catch(b){throw a.options.videoCaptureDefaults.deviceId=g,b}const x=y.some(b=>{var k,w;return(w=(k=b.track)===null||k===void 0?void 0:k.isMuted)!==null&&w!==void 0?w:!1});v&&x&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!sg()&&!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 gn.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)),v}()})}setupLocalParticipantEvents(){this.localParticipant.on(ae.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ae.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ae.AttributesChanged,this.onLocalAttributesChanged).on(ae.TrackMuted,this.onLocalTrackMuted).on(ae.TrackUnmuted,this.onLocalTrackUnmuted).on(ae.LocalTrackPublished,this.onLocalTrackPublished).on(ae.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ae.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ae.MediaDevicesError,this.onMediaDevicesError).on(ae.AudioStreamAcquired,this.startAudio).on(ae.ChatMessage,this.onLocalChatMessageSent).on(ae.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===Je.Connecting||this.state===Je.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===Je.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=Y8(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!==Je.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(ae.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ae.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ae.AttributesChanged,this.onLocalAttributesChanged).off(ae.TrackMuted,this.onLocalTrackMuted).off(ae.TrackUnmuted,this.onLocalTrackUnmuted).off(ae.LocalTrackPublished,this.onLocalTrackPublished).off(ae.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ae.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ae.MediaDevicesError,this.onMediaDevicesError).off(ae.AudioStreamAcquired,this.startAudio).off(ae.ChatMessage,this.onLocalChatMessageSent).off(ae.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),hi()&&(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(Je.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,zt.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(e,n,null,zt.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield s({requestId:n,callerIdentity:e,payload:r,responseTimeout:a});wg(u)>JS?(l=zt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof zt?l=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=zt.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=gn.getInstance().previousDevices,a=yield gn.getInstance().getDevices(void 0,!1),o=di();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=B8(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"&&!Tc()||l==="videoinput"||d.length>0&&!d.find(p=>p.deviceId===this.getActiveDevice(l))&&(l!=="audiooutput"||!Tc())&&(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=_S())!==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(),An(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=wh.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new wh(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(ae.TrackPublished,r=>{this.emitWhenConnected(J.TrackPublished,r,i)}).on(ae.TrackSubscribed,(r,a)=>{r.kind===F.Kind.Audio?(r.on(te.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(te.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===F.Kind.Video&&(r.on(te.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(te.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(J.TrackSubscribed,r,a,i)}).on(ae.TrackUnpublished,r=>{this.emit(J.TrackUnpublished,r,i)}).on(ae.TrackUnsubscribed,(r,a)=>{this.emit(J.TrackUnsubscribed,r,a,i)}).on(ae.TrackMuted,r=>{this.emitWhenConnected(J.TrackMuted,r,i)}).on(ae.TrackUnmuted,r=>{this.emitWhenConnected(J.TrackUnmuted,r,i)}).on(ae.ParticipantMetadataChanged,r=>{this.emitWhenConnected(J.ParticipantMetadataChanged,r,i)}).on(ae.ParticipantNameChanged,r=>{this.emitWhenConnected(J.ParticipantNameChanged,r,i)}).on(ae.AttributesChanged,r=>{this.emitWhenConnected(J.ParticipantAttributesChanged,r,i)}).on(ae.ConnectionQualityChanged,r=>{this.emitWhenConnected(J.ConnectionQualityChanged,r,i)}).on(ae.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(J.ParticipantPermissionsChanged,r,i)}).on(ae.TrackSubscriptionStatusChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionStatusChanged,r,a,i)}).on(ae.TrackSubscriptionFailed,(r,a)=>{this.emit(J.TrackSubscriptionFailed,r,i,a)}).on(ae.TrackSubscriptionPermissionChanged,(r,a)=>{this.emitWhenConnected(J.TrackSubscriptionPermissionChanged,r,a,i)}).on(ae.Active,()=>{this.emitWhenConnected(J.ParticipantActive,i),i.kind===vc.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&&sD(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=Rn.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,lr.STATE_MISMATCH))):e=0},CP)}clearConnectionReconcile(){this.connectionReconcileInterval&&Rn.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===Je.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Je.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 eh({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Dt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Xo({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(J.SignalConnected),this.emit(J.Connected),this.setAndEmitConnectionState(Je.Connected),r.video){const o=new Pg(F.Kind.Video,new Bs({source:Zt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sr.AUDIO,name:"video-dummy"}),new kh(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:OS(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(ae.LocalTrackPublished,o)}if(r.audio){const o=new Pg(F.Kind.Audio,new Bs({source:Zt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sr.AUDIO}),new Sh(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:dg(),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(ae.LocalTrackPublished,o)}for(let o=0;o<a.count-1;o+=1){let s=new Xo({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:js.ACTIVE,tracks:[],joinedAt:Dt.parse(Date.now())});const l=this.getOrCreateParticipant(s.identity,s);if(a.video){const c=OS(160*((i=a.aspectRatios[o%a.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Bs({source:Zt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:sr.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}if(a.audio){const c=dg(),u=new Bs({source:Zt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:sr.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=pk(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)}}Xs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function pk(t){return t.map(e=>{if(e)return Array.isArray(e)?pk(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var fr;(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"})(fr||(fr={}));class Ja extends Dr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=fr.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new Xs(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return E(this,void 0,void 0,function*(){if(this.status!==fr.IDLE)throw Error("check is running already");this.setStatus(fr.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!==fr.SKIPPED&&this.setStatus(this.isSuccess()?fr.SUCCESS:fr.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===Je.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!==Je.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(fr.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 An(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 EP extends Ja{get description(){return"Cloud regions"}perform(){return E(this,void 0,void 0,function*(){const e=new $e(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 v=0;v<l;v++)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(v=>{v.type==="candidate-pair"&&v.nominated&&(p.rtt=v.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Lg=1e4;class RP extends Ja{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/(Lg/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Lg/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,Lg)),clearInterval(d),s.stop(),n.remove(),yield this.disconnect(),u})}}class AP extends Ja{get description(){return"Can publish audio"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield xP();if(yield yS(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 NP extends Ja{get description(){return"Can publish video"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield _P();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 OP extends Ja{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!==Je.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 MP extends Ja{get description(){return"Can connect via TURN"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;Vs(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new $e(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new gg,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 DP extends Ja{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&&(PP(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 PP(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 LP extends Ja{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 gg,a;try{a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1})}catch(o){if(Vs(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const l=yield new $e(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)===lx.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 jW extends Dr.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:fr.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!==fr.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(LP)})}checkWebRTC(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(DP)})}checkTURN(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(MP)})}checkReconnect(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(OP)})}checkPublishAudio(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(AP)})}checkPublishVideo(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(NP)})}checkConnectionProtocol(){return E(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(RP);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(EP)})}}function Be(t,e,n){return(e=jP(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function IP(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 jP(t){var e=IP(t,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class Yn 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(Yn,"code","ERR_JOSE_GENERIC");class BP extends Yn{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(BP,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class UP extends Yn{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(UP,"code","ERR_JWT_EXPIRED");class zP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Be(zP,"code","ERR_JOSE_ALG_NOT_ALLOWED");class FP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Be(FP,"code","ERR_JOSE_NOT_SUPPORTED");class qP extends Yn{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(qP,"code","ERR_JWE_DECRYPTION_FAILED");class HP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWE_INVALID")}}Be(HP,"code","ERR_JWE_INVALID");class VP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWS_INVALID")}}Be(VP,"code","ERR_JWS_INVALID");class GP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWT_INVALID")}}Be(GP,"code","ERR_JWT_INVALID");class WP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWK_INVALID")}}Be(WP,"code","ERR_JWK_INVALID");class YP extends Yn{constructor(){super(...arguments),Be(this,"code","ERR_JWKS_INVALID")}}Be(YP,"code","ERR_JWKS_INVALID");class KP extends Yn{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(KP,"code","ERR_JWKS_NO_MATCHING_KEY");class XP extends Yn{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(XP,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class $P extends Yn{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($P,"code","ERR_JWKS_TIMEOUT");class JP extends Yn{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(JP,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const QP=/\{[^{}]+\}/g;function ZP(){return Math.random().toString(36).slice(2,11)}function eL(t){let{baseUrl:e="",Request:n=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:a,headers:o,...s}={...t};e=bk(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:p=i,Request:v=n,headers:m,params:S={},parseAs:g="json",querySerializer:y,bodySerializer:x=a??nL,body:b,...k}=d||{};h&&(e=bk(h));let w=typeof r=="function"?r:vk(r);y&&(w=typeof y=="function"?y:vk({...typeof r=="object"?r:{},...y}));const C=b===void 0?void 0:x(b),R=C===void 0||C instanceof FormData?{}:{"Content-Type":"application/json"},A={redirect:"follow",...s,...k,body:C,headers:rL(R,o,m,S.header)};let N,O,B=new n(iL(u,{baseUrl:e,params:S,querySerializer:w}),A);for(const Y in k)Y in B||(B[Y]=k[Y]);if(l.length){N=ZP(),O=Object.freeze({baseUrl:e,fetch:p,parseAs:g,querySerializer:w,bodySerializer:x});for(const Y of l)if(Y&&typeof Y=="object"&&typeof Y.onRequest=="function"){const P=await Y.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 X=await p(B);if(l.length)for(let Y=l.length-1;Y>=0;Y--){const P=l[Y];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const V=await P.onResponse({request:B,response:X,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");X=V}}}if(X.status===204||X.headers.get("Content-Length")==="0")return X.ok?{data:{},response:X}:{error:{},response:X};if(X.ok)return g==="stream"?{data:X.body,response:X}:{data:await X[g](),response:X};let L=await X.text();try{L=JSON.parse(L)}catch{}return{error:L,response:X}}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 Ch(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 mk(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(Ch(s,e[o],n))}const a=i.join(r);return n.style==="label"||n.style==="matrix"?`${r}${a}`:a}function gk(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(Ch(t,a,n));return n.style==="label"||n.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function vk(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(gk(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(mk(r,a,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}i.push(Ch(r,a,t))}}return i.join("&")}}function tL(t,e){let n=t;for(const i of t.match(QP)??[]){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,gk(r,s,{style:o,explode:a}));continue}if(typeof s=="object"){n=n.replace(i,mk(r,s,{style:o,explode:a}));continue}if(o==="matrix"){n=n.replace(i,`;${Ch(r,s)}`);continue}n=n.replace(i,o==="label"?`.${encodeURIComponent(s)}`:encodeURIComponent(s))}return n}function nL(t){return t instanceof FormData?t:JSON.stringify(t)}function iL(t,e){var r;let n=`${e.baseUrl}${t}`;(r=e.params)!=null&&r.path&&(n=tL(n,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(n+=`?${i}`),n}function rL(...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 bk(t){return t.endsWith("/")?t.substring(0,t.length-1):t}const yk="Onboardee-Session-Token",_k="OnboardeeSessionToken";class xk{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=eL({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(_k);i&&n.headers.set(yk,i)}return n},onResponse:({response:n})=>{if(this.trackOnboardeeToken){const i=n.headers.get(yk);i&&window.localStorage&&window.localStorage.setItem(_k,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 listProductUsers(e){return await this.client.GET("/api/products/{id}/users",{params:{path:{id:String(e)}}})}async getProductUser(e,n){return await this.client.GET("/api/products/{id}/users/{userId}",{params:{path:{id:String(e),userId:n}}})}async removeProductUser(e,n){return await this.client.DELETE("/api/products/{id}/users/{userId}",{params:{path:{id:String(e),userId:n}}})}async listProductInvitations(e,n){const i={};return n!=null&&n.status&&(i.status=n.status),(n==null?void 0:n.limit)!==void 0&&(i.limit=String(n.limit)),(n==null?void 0:n.offset)!==void 0&&(i.offset=String(n.offset)),await this.client.GET("/api/products/{id}/invitations",{params:{path:{id:String(e)},query:i}})}async createProductInvitationsBulk(e,n){return await this.client.POST("/api/products/{id}/invitations/bulk",{params:{path:{id:String(e)}},body:n})}async cancelProductInvitation(e,n){return await this.client.DELETE("/api/products/{id}/invitations",{params:{path:{id:String(e)},query:{email:n}}})}async listAccountUsers(e){return this.listProductUsers(e)}async getAccountUser(e,n){return this.getProductUser(e,n)}async removeAccountUser(e,n){return this.removeProductUser(e,n)}async listAccountInvitations(e,n){return this.listProductInvitations(e,n)}async createAccountInvitationsBulk(e,n){return this.createProductInvitationsBulk(e,n)}async cancelAccountInvitation(e,n){return this.cancelProductInvitation(e,n)}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 getProductDeploymentScript(e){return await this.client.GET("/api/products/{id}/deployment-script",{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,n){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e},...n!=null&&n.environment?{query:{environment:n.environment}}:{}}})}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 deleteSession(e){return await this.client.DELETE("/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,v,m,S,g,y;switch((p=n.onEvent)==null||p.call(n,h),h.type){case"started":(v=n.onStarted)==null||v.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(oa(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(oa(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 Sk(s);console.error("[TranscriptChat] HTTP error:",{status:s.status,payload:h}),a(oa(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 Sk(s);console.error("[TranscriptChat] Invalid content type:",l),a(oa(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(oa(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 v=d.split(`
43
43
 
44
44
  `);d=v.pop()??"";for(const m of v){const S=kk(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(oa(x,s.status,"stream_parse_error",`Failed to parse transcript chat stream event: ${S.event}`)),x}const y=Tk(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=kk(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(oa(y,s.status,"stream_parse_error",`Failed to parse final transcript chat stream event: ${m.event}`)),y}const g=Tk(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(oa(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 Sk(t){try{return await t.clone().json()}catch{return null}}function oa(t,e,n,i){const r=typeof t=="object"&&t!==null?t:{},a=Qa(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 kk(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 Tk(t,e){switch(t){case"started":return{type:"started",data:aL(e)};case"batch_complete":return{type:"batch_complete",data:oL(e)};case"answer_chunk":return{type:"answer_chunk",data:sL(e)};case"completed":return{type:"completed",data:lL(e)};case"error":return{type:"error",data:oa(e,0,"stream_error","Transcript chat stream error")};default:return null}}function aL(t){return{sessionCount:Qa((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,batchCount:Qa((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 oL(t){return{batchNumber:Qa((t==null?void 0:t.batchNumber)??(t==null?void 0:t.BatchNumber))??0,totalBatches:Qa((t==null?void 0:t.totalBatches)??(t==null?void 0:t.TotalBatches))??0,sessionsInBatch:Qa((t==null?void 0:t.sessionsInBatch)??(t==null?void 0:t.SessionsInBatch))??0}}function sL(t){return{content:typeof(t==null?void 0:t.content)=="string"?t.content:typeof(t==null?void 0:t.Content)=="string"?t.Content:""}}function lL(t){const e=wk((t==null?void 0:t.sessionUuids)??(t==null?void 0:t.SessionUUIDs)),n=wk((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:Qa((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,sessionUuids:e,batchCount:Qa((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 Qa(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 wk(t){if(Array.isArray(t))return t.map(e=>String(e))}const Ck="https://app.coragents.ai";class Eh extends Dp{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 xk({baseUrl:Ck}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(a=>new Xs(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},...(e==null?void 0:e.environment)&&{environment:e.environment}})).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===F.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":if(typeof a.current_step=="number"&&typeof a.total_steps=="number"&&Array.isArray(a.step_names)){const s=Math.max(0,a.total_steps),l=s>0?Math.min(Math.max(1,a.current_step),s):Math.max(1,a.current_step);this.emit("courseProgress",{currentStep:l,totalSteps:s,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:F.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===F.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===F.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===F.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),v=Math.min(p,this.frequencyDataBuffer.length),m=Math.min(h,v);if(m<v){let S=0;for(let y=m;y<v;y++)S+=this.frequencyDataBuffer[y];const g=S/(v-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 Eh(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!==Je.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!==Je.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 Rh extends Dp{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 xk({baseUrl:i.apiBaseUrl||Ck}),this.sessionFactory=i.sessionFactory||((r,a,o,s)=>new Eh(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 v=await this.api.getSessionPlan(e.planUuid);if(v.error)throw new Error(`Session plan not found: ${v.error}`);v.data&&(d=v.data,h=!0)}catch(v){console.error("[obi] error getting plan via both endpoints",{planErr:p,sessionErr:v})}}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 Rh(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=Eh.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 Ek={exports:{}},Ah={};var cL=Symbol.for("react.transitional.element"),uL=Symbol.for("react.fragment");function Rk(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:cL,type:t,key:i,ref:e!==void 0?e:null,props:n}}Ah.Fragment=uL,Ah.jsx=Rk,Ah.jsxs=Rk,Ek.exports=Ah;var f=Ek.exports,Ak={exports:{}},ke={};var Ig=Symbol.for("react.transitional.element"),dL=Symbol.for("react.portal"),hL=Symbol.for("react.fragment"),fL=Symbol.for("react.strict_mode"),pL=Symbol.for("react.profiler"),mL=Symbol.for("react.consumer"),gL=Symbol.for("react.context"),vL=Symbol.for("react.forward_ref"),bL=Symbol.for("react.suspense"),yL=Symbol.for("react.memo"),Nk=Symbol.for("react.lazy"),_L=Symbol.for("react.activity"),Ok=Symbol.iterator;function xL(t){return t===null||typeof t!="object"?null:(t=Ok&&t[Ok]||t["@@iterator"],typeof t=="function"?t:null)}var Mk={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Dk=Object.assign,Pk={};function $s(t,e,n){this.props=t,this.context=e,this.refs=Pk,this.updater=n||Mk}$s.prototype.isReactComponent={},$s.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")},$s.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Lk(){}Lk.prototype=$s.prototype;function jg(t,e,n){this.props=t,this.context=e,this.refs=Pk,this.updater=n||Mk}var Bg=jg.prototype=new Lk;Bg.constructor=jg,Dk(Bg,$s.prototype),Bg.isPureReactComponent=!0;var Ik=Array.isArray;function Ug(){}var Et={H:null,A:null,T:null,S:null},jk=Object.prototype.hasOwnProperty;function zg(t,e,n){var i=n.ref;return{$$typeof:Ig,type:t,key:e,ref:i!==void 0?i:null,props:n}}function SL(t,e){return zg(t.type,e,t.props)}function Fg(t){return typeof t=="object"&&t!==null&&t.$$typeof===Ig}function kL(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Bk=/\/+/g;function qg(t,e){return typeof t=="object"&&t!==null&&t.key!=null?kL(""+t.key):e.toString(36)}function TL(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Ug,Ug):(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 Js(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 Ig:case dL:o=!0;break;case Nk:return o=t._init,Js(o(t._payload),e,n,i,r)}}if(o)return r=r(t),o=i===""?"."+qg(t,0):i,Ik(r)?(n="",o!=null&&(n=o.replace(Bk,"$&/")+"/"),Js(r,e,n,"",function(c){return c})):r!=null&&(Fg(r)&&(r=SL(r,n+(r.key==null||t&&t.key===r.key?"":(""+r.key).replace(Bk,"$&/")+"/")+o)),e.push(r)),1;o=0;var s=i===""?".":i+":";if(Ik(t))for(var l=0;l<t.length;l++)i=t[l],a=s+qg(i,l),o+=Js(i,e,n,a,r);else if(l=xL(t),typeof l=="function")for(t=l.call(t),l=0;!(i=t.next()).done;)i=i.value,a=s+qg(i,l++),o+=Js(i,e,n,a,r);else if(a==="object"){if(typeof t.then=="function")return Js(TL(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 Nh(t,e,n){if(t==null)return t;var i=[],r=0;return Js(t,i,"","",function(a){return e.call(n,a,r++)}),i}function wL(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 Uk=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)},CL={map:Nh,forEach:function(t,e,n){Nh(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Nh(t,function(){e++}),e},toArray:function(t){return Nh(t,function(e){return e})||[]},only:function(t){if(!Fg(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};ke.Activity=_L,ke.Children=CL,ke.Component=$s,ke.Fragment=hL,ke.Profiler=pL,ke.PureComponent=jg,ke.StrictMode=fL,ke.Suspense=bL,ke.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Et,ke.__COMPILER_RUNTIME={__proto__:null,c:function(t){return Et.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=Dk({},t.props),r=t.key;if(e!=null)for(a in e.key!==void 0&&(r=""+e.key),e)!jk.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 zg(t.type,r,i)},ke.createContext=function(t){return t={$$typeof:gL,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:mL,_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)jk.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 zg(t,a,r)},ke.createRef=function(){return{current:null}},ke.forwardRef=function(t){return{$$typeof:vL,render:t}},ke.isValidElement=Fg,ke.lazy=function(t){return{$$typeof:Nk,_payload:{_status:-1,_result:t},_init:wL}},ke.memo=function(t,e){return{$$typeof:yL,type:t,compare:e===void 0?null:e}},ke.startTransition=function(t){var e=Et.T,n={};Et.T=n;try{var i=t(),r=Et.S;r!==null&&r(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(Ug,Uk)}catch(a){Uk(a)}finally{e!==null&&n.types!==null&&(e.types=n.types),Et.T=e}},ke.unstable_useCacheRefresh=function(){return Et.H.useCacheRefresh()},ke.use=function(t){return Et.H.use(t)},ke.useActionState=function(t,e,n){return Et.H.useActionState(t,e,n)},ke.useCallback=function(t,e){return Et.H.useCallback(t,e)},ke.useContext=function(t){return Et.H.useContext(t)},ke.useDebugValue=function(){},ke.useDeferredValue=function(t,e){return Et.H.useDeferredValue(t,e)},ke.useEffect=function(t,e){return Et.H.useEffect(t,e)},ke.useEffectEvent=function(t){return Et.H.useEffectEvent(t)},ke.useId=function(){return Et.H.useId()},ke.useImperativeHandle=function(t,e,n){return Et.H.useImperativeHandle(t,e,n)},ke.useInsertionEffect=function(t,e){return Et.H.useInsertionEffect(t,e)},ke.useLayoutEffect=function(t,e){return Et.H.useLayoutEffect(t,e)},ke.useMemo=function(t,e){return Et.H.useMemo(t,e)},ke.useOptimistic=function(t,e){return Et.H.useOptimistic(t,e)},ke.useReducer=function(t,e,n){return Et.H.useReducer(t,e,n)},ke.useRef=function(t){return Et.H.useRef(t)},ke.useState=function(t){return Et.H.useState(t)},ke.useSyncExternalStore=function(t,e,n){return Et.H.useSyncExternalStore(t,e,n)},ke.useTransition=function(){return Et.H.useTransition()},ke.version="19.2.3",Ak.exports=ke;var T=Ak.exports;const fi=gy(T);function EL(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var zk={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})()})(zk);var RL=zk.exports;const Oh=EL(RL),AL="_box_1r6by_1",NL={box:AL},Fk={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 pr(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in Fk)return Fk[t];if(typeof t=="string"&&t.trim().length>0)return t}}const qk={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},Hk={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 OL(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in qk)return qk[t];if(typeof t=="string"&&t.trim().length>0)return t}}function ML(t){if(t!==void 0){if(t in Hk)return Hk[t];if(typeof t=="string"&&t.trim().length>0)return t}}function DL(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:v,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:b,marginRight:k,radius:w,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:B,radiusBottomLeft:X,radiusBottomRight:L,background:Y,gap:P,style:V,...K}=t,ee=n??"div",$={...V},U=$,Z={},Q=(H,he)=>{if(he===void 0)return;const ve=pr(he);ve&&($[H]=ve)},le=(H,he)=>{if(he===void 0)return;const ve=pr(he);ve&&($[H]=ve)},j=(H,he)=>{if(he===void 0)return;const ve=OL(he);ve&&($[H]=ve)};if(r!==void 0){const H=pr(r);H&&(U["--box-padding"]=H)}if(a!==void 0){const H=pr(a);H&&($.paddingLeft=H,$.paddingRight=H)}if(o!==void 0){const H=pr(o);H&&($.paddingTop=H,$.paddingBottom=H)}Q("paddingTop",s),Q("paddingBottom",l),Q("paddingLeft",c),Q("paddingRight",u);const ge=[["sm",d],["md",h],["lg",p],["xl",v]];for(const[H,he]of ge){if(he===void 0)continue;const ve=pr(he);ve&&(U[`--box-padding-${H}`]=ve,Z[`data-padding-${H}`]="")}if(m!==void 0){const H=pr(m);H&&($.margin=H)}if(S!==void 0){const H=pr(S);H&&($.marginLeft=H,$.marginRight=H)}if(g!==void 0){const H=pr(g);H&&($.marginTop=H,$.marginBottom=H)}if(le("marginTop",y),le("marginBottom",x),le("marginLeft",b),le("marginRight",k),P!==void 0){const H=pr(P);H&&($.gap=H)}if(j("borderRadius",w),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",X),j("borderBottomRightRadius",L),Y!==void 0){const H=ML(Y);H&&($.background=H)}return f.jsx(ee,{ref:e,className:Oh(NL.box,i),style:$,...Z,...K})}const PL=fi.forwardRef(DL);PL.displayName="Box";const LL="_inline_1gpyx_1",IL="_vertical_1gpyx_6",jL="_divider_1gpyx_10",BL="_dividerVertical_1gpyx_16",UL="_customDivider_1gpyx_21",Nc={inline:LL,vertical:IL,divider:jL,dividerVertical:BL,customDivider:UL};function zL(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",v={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=pr(r);y&&(v.gap=y)}const m=fi.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:Oh(Nc.divider,i==="vertical"&&Nc.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:Nc.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const b=S(x);b&&g.push(b)}g.push(y)}),f.jsx(p,{ref:e,className:Oh(Nc.inline,i==="vertical"&&Nc.vertical,c),style:v,...h,children:g})}const FL=fi.forwardRef(zL);FL.displayName="Inline",T.createContext("vertical");function qL({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 Vk({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(qL,{})})}function Gk({open:t=!1,children:e,onClose:n,size:i="medium",preventOutsideClick:r=!1}){const a=T.useRef(null),o=T.useRef(null);T.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 T.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(Vk,{onClose:c}),f.jsx("div",{className:"modal-content",children:t?typeof e=="function"?e():e:null})]})}const Wk=8,Mh=8,HL=100,VL=.7,Qs=3;function Yk({getBands:t,color:e="white"}){const n=T.useRef(null);return T.useEffect(()=>{if(!t)return;let i=0,r;const a=o=>{try{if(o-i>=HL){const s=t();if(n.current){const l=n.current.querySelectorAll(".bar"),c=s&&s.length>0?s.slice(0,Mh).map(u=>{const d=Math.abs(u);return Math.min(d/VL*Wk,Wk)||Qs}):Array(Mh).fill(Qs);for(;c.length<Mh;)c.push(Qs);c.forEach((u,d)=>{if(u<Qs&&(u=Qs),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:Mh},(i,r)=>f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar",style:{height:`${Qs}px`,backgroundColor:e,display:"block"}})},r))})}function Dh({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 GL({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 WL({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 YL(t){const{spectrum:e}=t;return f.jsx(Dh,{isActive:!0,children:f.jsx(Yk,{getBands:e})})}function Hg(t){const{children:e,className:n="",...i}=t;return f.jsx("div",{className:`${n} obi-panel`,...i,children:e})}function Kk({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 KL(t){const{currentStep:e,totalSteps:n,stepNames:i,className:r,onStepClick:a}=t,[o,s]=T.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}`,v=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 ${v}`,"aria-label":p})},h)})}),f.jsx("div",{className:"obi-course-progress-description",children:u})]})}function XL({onContinue:t,onWrapUp:e}){return f.jsx(Hg,{className:"obi-exit-survey",children:f.jsx(JL,{onContinue:t,onWrapUp:()=>{e()}})})}function $L({onOtherSelect:t,onReasonSelect:e,onClose:n}){const[i,r]=T.useState("reason"),a=o=>{o==="other"?(t(),r("other-reason")):e(o)};return f.jsx(Hg,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?f.jsx(QL,{onReasonSelect:a}):f.jsx(ZL,{onReasonSelect:a,onClose:n})})}function JL({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 QL({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 ZL({onReasonSelect:t,onClose:e}){const[n,i]=T.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(Vk,{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 eI=8;function Xk({color:t="white"}){return f.jsx("div",{className:"obi-loading-dots",children:Array.from({length:eI},(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 sa({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 tI(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]=T.useState(n||i||""),[v,m]=T.useState((n||i||"").length>24),S=T.useRef(null);T.useLayoutEffect(()=>{v&&(s==null||s(!0))},[]);const g=n!==void 0?n:h,y=k=>{const w=k.currentTarget.value;n===void 0&&p(w),r==null||r(w)},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),b()),(g||"").length>=24&&!v&&(m(!0),s==null||s(!0))};T.useEffect(()=>{S.current&&S.current.focus()},[S.current]);const b=()=>{!g.trim()||l||c||(a==null||a(g.trim()),n===void 0&&p(""))};return f.jsxs("div",{className:`obi-message-input ${v?"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:[v&&f.jsx("div",{children:d}),f.jsx("button",{className:"obi-button send",onClick:b,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 Vg=T.createContext(null);function nI({children:t}){const e=T.useContext(Vg);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=T.useRef(null),d=$k(o,a),[h,p]=T.useState(!1);T.useEffect(()=>{n!==void 0&&n!==h&&(n?m():S()),p(n)},[n]),T.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);function v(){u.current&&(clearTimeout(u.current),u.current=null)}function m(){v(),c>0?u.current=setTimeout(()=>{l==null||l(!0),r(!0),u.current=null},c):(l==null||l(!0),r(!0))}function S(){v(),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 iI({children:t}){const e=T.useContext(Vg);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=$k(o,r);return T.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 pi({trigger:t="click",open:e,onChange:n,children:i,delayMs:r=0,offset:a=0,className:o=""}){const[s,l]=T.useState(!1),[c,u]=T.useState(!1),d=T.useRef(null),h=T.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(Vg.Provider,{value:p,children:f.jsx("div",{className:`obi-popout ${o}`,children:i})})}pi.Target=nI,pi.Content=iI;function $k(t,e){const n=T.useRef(null),i=T.useRef(null),r=T.useRef(!0),a=T.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 T.useEffect(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),a}function es({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:rI(t)})}function rI(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 mr({className:t,onClick:e,type:n,disabled:i,title:r}){const a={cancel:f.jsx(es,{type:"close",size:16}),pause:f.jsx(es,{type:"pause",size:16}),play:f.jsx(es,{type:"play",size:16}),message:f.jsx(es,{type:"message",size:16}),minimize:f.jsx(es,{type:"minimize",size:16}),voice:f.jsx(es,{type:"voice",size:16}),open:f.jsx(es,{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(pi,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[f.jsx(pi.Target,{children:s}),f.jsx(pi.Content,{children:f.jsx("div",{className:"obi-round-button-title",children:r})})]}):s}function aI(t){const{disabled:e,inPlan:n,isPaused:i}=t,[r,a]=T.useState(null),[o,s]=T.useState(t.isActive??t.defaultIsActive??!1),[l,c]=T.useState(!1),[u,d]=T.useState(t.cancelling??!1),[h,p]=T.useState(t.messaging??!1),[v,m]=T.useState(!1),[S,g]=T.useState(h),[y,x]=T.useState(!1);function b(){s(!0),c(!1),x(!0)}function k(){}function w(){r&&(clearTimeout(r),a(null))}function C(){a(setTimeout(()=>{s(t.defaultIsActive??!1),x(!1)},400))}function R(me){var Ne;m(!1),(Ne=t.onMessage)==null||Ne.call(t,me)}function A(){var me;p(!1),m(!1),s(!1),c(!0),(me=t.onMinimize)==null||me.call(t)}function N(){var me;p(!1),d(!0),m(!1),(me=t.onCancelClick)==null||me.call(t)}function O(){var me;n||((me=t.onOpen)==null||me.call(t))}function B(me){var Ne,_t,dt,Ht,un,Ot;switch(me){case"need-help":(Ne=t.onMessage)==null||Ne.call(t,"I'm struggling, can you look at my screen and help me out."),(_t=t.onOneClickAction)==null||_t.call(t,"need-help");break;case"continue":(dt=t.onMessage)==null||dt.call(t,"Okay, let's continue."),(Ht=t.onOneClickAction)==null||Ht.call(t,"continue");break;case"say-again":(un=t.onMessage)==null||un.call(t,"Please say that again."),(Ot=t.onOneClickAction)==null||Ot.call(t,"say-again");break}}function X(me){var Ne,_t;t.messaging===void 0?((Ne=t.onMessagingChange)==null||Ne.call(t,me),p(me)):((_t=t.onMessagingChange)==null||_t.call(t,!t.messaging),p(!t.messaging)),me||m(!1)}const L=t.isActive??((o||n)&&!l&&!e),Y=L&&n,P=L&&n&&!v,V=t.speakingStatus==="user-speaking",K=t.speakingStatus==="thinking",ee=t.speakingStatus==="busy",$=L&&!n&&!u&&y,U=L&&n&&i&&!V&&!u,Z=L&&n&&!U&&!V&&h!==S&&!u,Q=L&&n&&i&&V&&!u,le=L&&n&&!i&&V&&!u,j=L&&n&&!i&&ee&&!u,ge=t.messaging!==void 0?t.messaging:h,H=ge&&V,he=$||U||Q||le||Z||u,ve=400,Ye=!!t.courseProgress&&!l,Lt=$?5:10;return T.useLayoutEffect(()=>{g(h)},[V]),!n&&!u?f.jsx(oI,{...t}):!n&&u?f.jsx(sI,{onOtherSelect:()=>{var me;(me=t.onCancelReasonOther)==null||me.call(t)},onCancelReason:me=>{var Ne;s(t.defaultIsActive??!1),d(!1),(Ne=t.onCancelReason)==null||Ne.call(t,me)},onClose:()=>{s(t.defaultIsActive??!1),d(!1)}}):f.jsxs(Hg,{className:`obi-widget-panel ${Y?"expanded":""} ${v?"maximized":""} ${ge?"messaging":""} ${ee?"tool-usage":""}`,children:[f.jsxs("div",{className:`obi-widget ${L?"active":""} ${n?"in-plan":""}`,onMouseEnter:w,onMouseLeave:C,children:[P&&f.jsx(mr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),P&&!i&&f.jsx(mr,{type:"pause",onClick:t.onPause,title:"Pause session"}),P&&i&&f.jsx(mr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsxs(pi,{className:"obi-widget-popout",open:he,trigger:null,delayMs:ve,offset:Lt,children:[f.jsxs(pi.Target,{children:[H&&f.jsx(tI,{value:t.message,onCancel:()=>X(!1),onSend:R,onExpand:m,onChange:t.onMessageChange,children:f.jsxs("div",{className:"obi-widget-buttons",children:[f.jsx(mr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),!i&&f.jsx(mr,{type:"pause",onClick:t.onPause,title:"Pause session"}),i&&f.jsx(mr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsx(mr,{type:ge?"voice":"message",onClick:()=>X(!ge),title:ge?"Voice input":"Text input"}),f.jsx(mr,{type:"minimize",onClick:A,title:"Minimize widget"})]})}),!H&&f.jsxs(Dh,{className:L&&!n?"button":"",isActive:L,speakingStatus:t.speakingStatus,onClick:O,onMouseEnter:b,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&&!K&&!j&&f.jsx(Yk,{getBands:t.spectrum}),L&&K&&!j&&f.jsx(Xk,{})]})]}),f.jsx(pi.Content,{children:f.jsxs("div",{onMouseLeave:C,children:[$&&f.jsx(sa,{onClick:O,children:"Click to see all"}),U&&f.jsx(sa,{children:"Session will pause shortly"}),Z&&f.jsxs(sa,{children:["Switched to ",ge?"chat":"voice"]}),Q&&f.jsx(sa,{children:"Paused"}),le&&f.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[f.jsx(sa,{onClick:()=>B("need-help"),children:"Need help"}),f.jsx(sa,{onClick:()=>B("continue"),children:"Continue"}),f.jsx(sa,{onClick:()=>B("say-again"),children:"Say again"})]}),u&&f.jsx(XL,{onContinue:()=>{var me;(me=t.onCancelAbort)==null||me.call(t),d(!1),t.messaging!==void 0&&p(t.messaging)},onWrapUp:()=>{var me;(me=t.onCancel)==null||me.call(t)}})]})})]}),P&&f.jsx(mr,{type:ge?"voice":"message",onClick:()=>X(!ge),title:ge?"Voice input":"Text input"}),P&&f.jsx(mr,{type:"minimize",onClick:A,title:"Minimize widget"})]}),Ye&&t.courseProgress&&f.jsx("div",{className:`obi-widget-course-progress ${ge?"expanded":""}`,children:f.jsx(KL,{currentStep:t.courseProgress.currentStep,totalSteps:t.courseProgress.totalSteps,stepNames:t.courseProgress.stepNames,onStepClick:(me,Ne)=>{var dt;const _t=`Can we please jump to the steps related to: ${Ne}`;(dt=t.onMessage)==null||dt.call(t,_t)}})})]})}function oI(t){const{disabled:e,completedTutorials:n,totalTutorials:i,agentName:r}=t,[a,o]=T.useState(null),[s,l]=T.useState(t.isActive??t.defaultIsActive??!1),[c,u]=T.useState(!1),[d,h]=T.useState(t.hovered??!1),[p,v]=T.useState(null),[m,S]=T.useState(null);function g(){m&&(clearTimeout(m),S(null)),p&&v(null)}function y(){var X;l(!0),u(!1),h(!0),(X=t.onHover)==null||X.call(t,!0)}function x(){}function b(){a&&(clearTimeout(a),o(null))}function k(){s&&o(setTimeout(()=>{var X;l(t.defaultIsActive??!1),h(!1),(X=t.onHover)==null||X.call(t,!1)},400))}function w(){g(),l(!1),u(!0)}function C(){var X;g(),(X=t.onOpen)==null||X.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`),T.useLayoutEffect(()=>{if(t.toastMessage&&t.toastMessage.text){m&&clearTimeout(m);const X=t.toastMessage.autoCloseMs??3e3;v({text:t.toastMessage.text,autoCloseMs:X});const L=setTimeout(()=>{v(null)},X);S(L)}else t.toastMessage===null&&(m&&clearTimeout(m),v(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:b,onMouseLeave:k,onClickCapture:g,children:[f.jsx("div",{className:O,style:{width:"30px",height:"30px"}}),f.jsxs(pi,{className:"obi-widget-popout",open:N,trigger:null,delayMs:400,offset:5,children:[f.jsx(pi.Target,{children:f.jsx(WL,{className:A?"button":"",active:A,onClick:C,onMouseEnter:y,onMouseLeave:x,children:f.jsxs("span",{className:"text",children:[f.jsx(Kk,{size:16}),B]})})}),f.jsxs(pi.Content,{children:[!!p&&f.jsx(sa,{onClick:()=>{g(),C()},children:p.text}),!p&&f.jsx("div",{onMouseLeave:k,children:f.jsx(sa,{className:"message",onClick:C,children:"Click to see all"})})]})]}),f.jsx(mr,{className:O,type:"minimize",onClick:w,title:"Minimize widget"})]})})}function sI(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(pi,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[f.jsx(pi.Target,{children:f.jsx(GL,{active:!1})}),f.jsx(pi.Content,{children:f.jsx($L,{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 lI({open:t=!1,children:e,onClose:n,preventOutsideClick:i=!1}){return f.jsx(Gk,{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 cI({logoUrl:t="",appName:e="App"}){const[n,i]=T.useState(!1),[r,a]=T.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 Zs({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,v]=T.useState(a),[m,S]=T.useState(!1),[g,y]=T.useState(r);T.useEffect(()=>{m||(r==="listening"&&g!=="listening"&&p&&v(!1),r!=="listening"&&!p&&v(!0)),y(r)},[r,p]),T.useEffect(()=>{v(a)},[a]);const x=()=>{p||(v(!0),S(!0),h==null||h())},b=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${n} is speaking`;default:return i}},k=s?"a":"button",w=s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return f.jsx("div",{className:Oh("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,...w,children:f.jsx("span",{className:"button-text",children:b()})})}),o&&f.jsx("div",{className:"tour-footer",children:o})]})})}function uI({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(Zs,{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(cI,{logoUrl:t.appLogoUrl,appName:t.appName}),onAction:n})}const{entries:Jk,setPrototypeOf:Qk,isFrozen:dI,getPrototypeOf:hI,getOwnPropertyDescriptor:fI}=Object;let{freeze:Kn,seal:Gi,create:Gg}=Object,{apply:Wg,construct:Yg}=typeof Reflect<"u"&&Reflect;Kn||(Kn=function(t){return t}),Gi||(Gi=function(t){return t}),Wg||(Wg=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)}),Yg||(Yg=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 Ph=$n(Array.prototype.forEach),pI=$n(Array.prototype.lastIndexOf),Zk=$n(Array.prototype.pop),Oc=$n(Array.prototype.push),mI=$n(Array.prototype.splice),Lh=$n(String.prototype.toLowerCase),Kg=$n(String.prototype.toString),Xg=$n(String.prototype.match),Mc=$n(String.prototype.replace),gI=$n(String.prototype.indexOf),vI=$n(String.prototype.trim),gr=$n(Object.prototype.hasOwnProperty),Xn=$n(RegExp.prototype.test),Dc=bI(TypeError);function $n(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 Wg(t,e,i)}}function bI(t){return function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return Yg(t,n)}}function Me(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Lh;Qk&&Qk(t,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const a=n(r);a!==r&&(dI(e)||(e[i]=a),r=a)}t[r]=!0}return t}function yI(t){for(let e=0;e<t.length;e++)gr(t,e)||(t[e]=null);return t}function Br(t){const e=Gg(null);for(const[n,i]of Jk(t))gr(t,n)&&(Array.isArray(i)?e[n]=yI(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=Br(i):e[n]=i);return e}function Pc(t,e){for(;t!==null;){const i=fI(t,e);if(i){if(i.get)return $n(i.get);if(typeof i.value=="function")return $n(i.value)}t=hI(t)}function n(){return null}return n}const eT=Kn(["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"]),$g=Kn(["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"]),Jg=Kn(["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"]),_I=Kn(["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"]),Qg=Kn(["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"]),xI=Kn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),tT=Kn(["#text"]),nT=Kn(["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"]),Zg=Kn(["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"]),iT=Kn(["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"]),Ih=Kn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),SI=Gi(/\{\{[\w\W]*|[\w\W]*\}\}/gm),kI=Gi(/<%[\w\W]*|[\w\W]*%>/gm),TI=Gi(/\$\{[\w\W]*/gm),wI=Gi(/^data-[\-\w.\u00B7-\uFFFF]+$/),CI=Gi(/^aria-[\-\w]+$/),rT=Gi(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),EI=Gi(/^(?:\w+script|data):/i),RI=Gi(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),aT=Gi(/^html$/i),AI=Gi(/^[a-z][.\w]*(-[.\w]+)+$/i);var oT=Object.freeze({__proto__:null,ARIA_ATTR:CI,ATTR_WHITESPACE:RI,CUSTOM_ELEMENT:AI,DATA_ATTR:wI,DOCTYPE_NAME:aT,ERB_EXPR:kI,IS_ALLOWED_URI:rT,IS_SCRIPT_OR_DATA:EI,MUSTACHE_EXPR:SI,TMPLIT_EXPR:TI});const Lc={element:1,text:3,progressingInstruction:7,comment:8,document:9},NI=function(){return typeof window>"u"?null:window},OI=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}},sT=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function lT(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:NI();const e=_=>lT(_);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==Lc.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,v=l.prototype,m=Pc(v,"cloneNode"),S=Pc(v,"remove"),g=Pc(v,"nextSibling"),y=Pc(v,"childNodes"),x=Pc(v,"parentNode");if(typeof o=="function"){const _=n.createElement("template");_.content&&_.content.ownerDocument&&(n=_.content.ownerDocument)}let b,k="";const{implementation:w,createNodeIterator:C,createDocumentFragment:R,getElementsByTagName:A}=n,{importNode:N}=i;let O=sT();e.isSupported=typeof Jk=="function"&&typeof x=="function"&&w&&w.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:B,ERB_EXPR:X,TMPLIT_EXPR:L,DATA_ATTR:Y,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:V,ATTR_WHITESPACE:K,CUSTOM_ELEMENT:ee}=oT;let{IS_ALLOWED_URI:$}=oT,U=null;const Z=Me({},[...eT,...$g,...Jg,...Qg,...tT]);let Q=null;const le=Me({},[...nT,...Zg,...iT,...Ih]);let j=Object.seal(Gg(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,H=null;const he=Object.seal(Gg(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ve=!0,Ye=!0,Lt=!1,me=!0,Ne=!1,_t=!0,dt=!1,Ht=!1,un=!1,Ot=!1,dn=!1,In=!1,ri=!0,ai=!1;const ue="user-content-";let Ke=!0,Ce=!1,tt={},st=null;const Fn=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 Li=null;const Yr=Me({},["audio","video","img","source","image","track"]);let q=null;const re=Me({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),de="http://www.w3.org/1998/Math/MathML",qe="http://www.w3.org/2000/svg",He="http://www.w3.org/1999/xhtml";let St=He,hn=!1,Ii=null;const wr=Me({},[de,qe,He],Kg);let Vt=Me({},["mi","mo","mn","ms","mtext"]),qn=Me({},["annotation-xml"]);const xn=Me({},["title","style","font","a","script"]);let jn=null;const Oo=["application/xhtml+xml","text/html"],Wl="text/html";let Te=null,Sn=null;const Yl=n.createElement("form"),Kl=function(_){return _ instanceof RegExp||_ instanceof Function},Kr=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Sn&&Sn===_)){if((!_||typeof _!="object")&&(_={}),_=Br(_),jn=Oo.indexOf(_.PARSER_MEDIA_TYPE)===-1?Wl:_.PARSER_MEDIA_TYPE,Te=jn==="application/xhtml+xml"?Kg:Lh,U=gr(_,"ALLOWED_TAGS")?Me({},_.ALLOWED_TAGS,Te):Z,Q=gr(_,"ALLOWED_ATTR")?Me({},_.ALLOWED_ATTR,Te):le,Ii=gr(_,"ALLOWED_NAMESPACES")?Me({},_.ALLOWED_NAMESPACES,Kg):wr,q=gr(_,"ADD_URI_SAFE_ATTR")?Me(Br(re),_.ADD_URI_SAFE_ATTR,Te):re,Li=gr(_,"ADD_DATA_URI_TAGS")?Me(Br(Yr),_.ADD_DATA_URI_TAGS,Te):Yr,st=gr(_,"FORBID_CONTENTS")?Me({},_.FORBID_CONTENTS,Te):Fn,ge=gr(_,"FORBID_TAGS")?Me({},_.FORBID_TAGS,Te):Br({}),H=gr(_,"FORBID_ATTR")?Me({},_.FORBID_ATTR,Te):Br({}),tt=gr(_,"USE_PROFILES")?_.USE_PROFILES:!1,ve=_.ALLOW_ARIA_ATTR!==!1,Ye=_.ALLOW_DATA_ATTR!==!1,Lt=_.ALLOW_UNKNOWN_PROTOCOLS||!1,me=_.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ne=_.SAFE_FOR_TEMPLATES||!1,_t=_.SAFE_FOR_XML!==!1,dt=_.WHOLE_DOCUMENT||!1,Ot=_.RETURN_DOM||!1,dn=_.RETURN_DOM_FRAGMENT||!1,In=_.RETURN_TRUSTED_TYPE||!1,un=_.FORCE_BODY||!1,ri=_.SANITIZE_DOM!==!1,ai=_.SANITIZE_NAMED_PROPS||!1,Ke=_.KEEP_CONTENT!==!1,Ce=_.IN_PLACE||!1,$=_.ALLOWED_URI_REGEXP||rT,St=_.NAMESPACE||He,Vt=_.MATHML_TEXT_INTEGRATION_POINTS||Vt,qn=_.HTML_INTEGRATION_POINTS||qn,j=_.CUSTOM_ELEMENT_HANDLING||{},_.CUSTOM_ELEMENT_HANDLING&&Kl(_.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=_.CUSTOM_ELEMENT_HANDLING.tagNameCheck),_.CUSTOM_ELEMENT_HANDLING&&Kl(_.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),Ne&&(Ye=!1),dn&&(Ot=!0),tt&&(U=Me({},tT),Q=[],tt.html===!0&&(Me(U,eT),Me(Q,nT)),tt.svg===!0&&(Me(U,$g),Me(Q,Zg),Me(Q,Ih)),tt.svgFilters===!0&&(Me(U,Jg),Me(Q,Zg),Me(Q,Ih)),tt.mathMl===!0&&(Me(U,Qg),Me(Q,iT),Me(Q,Ih))),_.ADD_TAGS&&(typeof _.ADD_TAGS=="function"?he.tagCheck=_.ADD_TAGS:(U===Z&&(U=Br(U)),Me(U,_.ADD_TAGS,Te))),_.ADD_ATTR&&(typeof _.ADD_ATTR=="function"?he.attributeCheck=_.ADD_ATTR:(Q===le&&(Q=Br(Q)),Me(Q,_.ADD_ATTR,Te))),_.ADD_URI_SAFE_ATTR&&Me(q,_.ADD_URI_SAFE_ATTR,Te),_.FORBID_CONTENTS&&(st===Fn&&(st=Br(st)),Me(st,_.FORBID_CONTENTS,Te)),_.ADD_FORBID_CONTENTS&&(st===Fn&&(st=Br(st)),Me(st,_.ADD_FORBID_CONTENTS,Te)),Ke&&(U["#text"]=!0),dt&&Me(U,["html","head","body"]),U.table&&(Me(U,["tbody"]),delete ge.tbody),_.TRUSTED_TYPES_POLICY){if(typeof _.TRUSTED_TYPES_POLICY.createHTML!="function")throw Dc('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof _.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Dc('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=_.TRUSTED_TYPES_POLICY,k=b.createHTML("")}else b===void 0&&(b=OI(p,r)),b!==null&&typeof k=="string"&&(k=b.createHTML(""));Kn&&Kn(_),Sn=_}},Mo=Me({},[...$g,...Jg,..._I]),Do=Me({},[...Qg,...xI]),Xl=function(_){let I=x(_);(!I||!I.tagName)&&(I={namespaceURI:St,tagName:"template"});const M=Lh(_.tagName),pe=Lh(I.tagName);return Ii[_.namespaceURI]?_.namespaceURI===qe?I.namespaceURI===He?M==="svg":I.namespaceURI===de?M==="svg"&&(pe==="annotation-xml"||Vt[pe]):!!Mo[M]:_.namespaceURI===de?I.namespaceURI===He?M==="math":I.namespaceURI===qe?M==="math"&&qn[pe]:!!Do[M]:_.namespaceURI===He?I.namespaceURI===qe&&!qn[pe]||I.namespaceURI===de&&!Vt[pe]?!1:!Do[M]&&(xn[M]||!Mo[M]):!!(jn==="application/xhtml+xml"&&Ii[_.namespaceURI]):!1},kn=function(_){Oc(e.removed,{element:_});try{x(_).removeChild(_)}catch{S(_)}},Tn=function(_,I){try{Oc(e.removed,{attribute:I.getAttributeNode(_),from:I})}catch{Oc(e.removed,{attribute:null,from:I})}if(I.removeAttribute(_),_==="is")if(Ot||dn)try{kn(I)}catch{}else try{I.setAttribute(_,"")}catch{}},Po=function(_){let I=null,M=null;if(un)_="<remove></remove>"+_;else{const be=Xg(_,/^[\r\n\t ]+/);M=be&&be[0]}jn==="application/xhtml+xml"&&St===He&&(_='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+_+"</body></html>");const pe=b?b.createHTML(_):_;if(St===He)try{I=new h().parseFromString(pe,jn)}catch{}if(!I||!I.documentElement){I=w.createDocument(St,"template",null);try{I.documentElement.innerHTML=hn?k:pe}catch{}}const Pe=I.body||I.documentElement;return _&&M&&Pe.insertBefore(n.createTextNode(M),Pe.childNodes[0]||null),St===He?A.call(I,dt?"html":"body")[0]:dt?I.documentElement:Pe},Lo=function(_){return C.call(_.ownerDocument||_,_,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Xr=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")},Io=function(_){return typeof s=="function"&&_ instanceof s};function Gt(_,I,M){Ph(_,pe=>{pe.call(e,I,M,Sn)})}const jo=function(_){let I=null;if(Gt(O.beforeSanitizeElements,_,null),Xr(_))return kn(_),!0;const M=Te(_.nodeName);if(Gt(O.uponSanitizeElement,_,{tagName:M,allowedTags:U}),_t&&_.hasChildNodes()&&!Io(_.firstElementChild)&&Xn(/<[/\w!]/g,_.innerHTML)&&Xn(/<[/\w!]/g,_.textContent)||_.nodeType===Lc.progressingInstruction||_t&&_.nodeType===Lc.comment&&Xn(/<[/\w]/g,_.data))return kn(_),!0;if(!(he.tagCheck instanceof Function&&he.tagCheck(M))&&(!U[M]||ge[M])){if(!ge[M]&&Uo(M)&&(j.tagNameCheck instanceof RegExp&&Xn(j.tagNameCheck,M)||j.tagNameCheck instanceof Function&&j.tagNameCheck(M)))return!1;if(Ke&&!st[M]){const pe=x(_)||_.parentNode,Pe=y(_)||_.childNodes;if(Pe&&pe){const be=Pe.length;for(let Wt=be-1;Wt>=0;--Wt){const kt=m(Pe[Wt],!0);kt.__removalCount=(_.__removalCount||0)+1,pe.insertBefore(kt,g(_))}}}return kn(_),!0}return _ instanceof l&&!Xl(_)||(M==="noscript"||M==="noembed"||M==="noframes")&&Xn(/<\/no(script|embed|frames)/i,_.innerHTML)?(kn(_),!0):(Ne&&_.nodeType===Lc.text&&(I=_.textContent,Ph([B,X,L],pe=>{I=Mc(I,pe," ")}),_.textContent!==I&&(Oc(e.removed,{element:_.cloneNode()}),_.textContent=I)),Gt(O.afterSanitizeElements,_,null),!1)},Bo=function(_,I,M){if(ri&&(I==="id"||I==="name")&&(M in n||M in Yl))return!1;if(!(Ye&&!H[I]&&Xn(Y,I))&&!(ve&&Xn(P,I))&&!(he.attributeCheck instanceof Function&&he.attributeCheck(I,_))){if(!Q[I]||H[I]){if(!(Uo(_)&&(j.tagNameCheck instanceof RegExp&&Xn(j.tagNameCheck,_)||j.tagNameCheck instanceof Function&&j.tagNameCheck(_))&&(j.attributeNameCheck instanceof RegExp&&Xn(j.attributeNameCheck,I)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(I,_))||I==="is"&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&Xn(j.tagNameCheck,M)||j.tagNameCheck instanceof Function&&j.tagNameCheck(M))))return!1}else if(!q[I]&&!Xn($,Mc(M,K,""))&&!((I==="src"||I==="xlink:href"||I==="href")&&_!=="script"&&gI(M,"data:")===0&&Li[_])&&!(Lt&&!Xn(V,Mc(M,K,"")))&&M)return!1}return!0},Uo=function(_){return _!=="annotation-xml"&&Xg(_,ee)},zo=function(_){Gt(O.beforeSanitizeAttributes,_,null);const{attributes:I}=_;if(!I||Xr(_))return;const M={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Q,forceKeepAttr:void 0};let pe=I.length;for(;pe--;){const Pe=I[pe],{name:be,namespaceURI:Wt,value:kt}=Pe,Tt=Te(be),$r=kt;let Le=be==="value"?$r:vI($r);if(M.attrName=Tt,M.attrValue=Le,M.keepAttr=!0,M.forceKeepAttr=void 0,Gt(O.uponSanitizeAttribute,_,M),Le=M.attrValue,ai&&(Tt==="id"||Tt==="name")&&(Tn(be,_),Le=ue+Le),_t&&Xn(/((--!?|])>)|<\/(style|title|textarea)/i,Le)){Tn(be,_);continue}if(Tt==="attributename"&&Xg(Le,"href")){Tn(be,_);continue}if(M.forceKeepAttr)continue;if(!M.keepAttr){Tn(be,_);continue}if(!me&&Xn(/\/>/i,Le)){Tn(be,_);continue}Ne&&Ph([B,X,L],Jl=>{Le=Mc(Le,Jl," ")});const Fo=Te(_.nodeName);if(!Bo(Fo,Tt,Le)){Tn(be,_);continue}if(b&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Wt)switch(p.getAttributeType(Fo,Tt)){case"TrustedHTML":{Le=b.createHTML(Le);break}case"TrustedScriptURL":{Le=b.createScriptURL(Le);break}}if(Le!==$r)try{Wt?_.setAttributeNS(Wt,be,Le):_.setAttribute(be,Le),Xr(_)?kn(_):Zk(e.removed)}catch{Tn(be,_)}}Gt(O.afterSanitizeAttributes,_,null)},$l=function _(I){let M=null;const pe=Lo(I);for(Gt(O.beforeSanitizeShadowDOM,I,null);M=pe.nextNode();)Gt(O.uponSanitizeShadowNode,M,null),jo(M),zo(M),M.content instanceof a&&_(M.content);Gt(O.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(_){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,pe=null,Pe=null,be=null;if(hn=!_,hn&&(_="<!-->"),typeof _!="string"&&!Io(_))if(typeof _.toString=="function"){if(_=_.toString(),typeof _!="string")throw Dc("dirty is not a string, aborting")}else throw Dc("toString is not a function");if(!e.isSupported)return _;if(Ht||Kr(I),e.removed=[],typeof _=="string"&&(Ce=!1),Ce){if(_.nodeName){const Tt=Te(_.nodeName);if(!U[Tt]||ge[Tt])throw Dc("root node is forbidden and cannot be sanitized in-place")}}else if(_ instanceof s)M=Po("<!---->"),pe=M.ownerDocument.importNode(_,!0),pe.nodeType===Lc.element&&pe.nodeName==="BODY"||pe.nodeName==="HTML"?M=pe:M.appendChild(pe);else{if(!Ot&&!Ne&&!dt&&_.indexOf("<")===-1)return b&&In?b.createHTML(_):_;if(M=Po(_),!M)return Ot?null:In?k:""}M&&un&&kn(M.firstChild);const Wt=Lo(Ce?_:M);for(;Pe=Wt.nextNode();)jo(Pe),zo(Pe),Pe.content instanceof a&&$l(Pe.content);if(Ce)return _;if(Ot){if(dn)for(be=R.call(M.ownerDocument);M.firstChild;)be.appendChild(M.firstChild);else be=M;return(Q.shadowroot||Q.shadowrootmode)&&(be=N.call(i,be,!0)),be}let kt=dt?M.outerHTML:M.innerHTML;return dt&&U["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&Xn(aT,M.ownerDocument.doctype.name)&&(kt="<!DOCTYPE "+M.ownerDocument.doctype.name+`>
@@ -131,4 +131,4 @@ ${t}</tr>
131
131
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
132
132
  `}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>${Ra(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=_3(t);if(r===null)return i;t=r;let a='<a href="'+t+'"';return e&&(a+=' title="'+Ra(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=_3(t);if(r===null)return Ra(n);t=r;let a=`<img src="${t}" alt="${n}"`;return e&&(a+=` title="${Ra(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Ra(t.text)}},Zb=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}},Sr=class cy{constructor(e){bt(this,"options"),bt(this,"renderer"),bt(this,"textRenderer"),this.options=e||Ss,this.options.renderer=this.options.renderer||new Sp,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Zb}static parse(e,n){return new cy(n).parse(e)}static parseInline(e,n){return new cy(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}},kp,Hu=(kp=class{constructor(t){bt(this,"options"),bt(this,"block"),this.options=t||Ss}preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?xr.lex:xr.lexInline}provideParser(){return this.block?Sr.parse:Sr.parseInline}},bt(kp,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),bt(kp,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),kp),oF=class{constructor(...t){bt(this,"defaults",Vb()),bt(this,"options",this.setOptions),bt(this,"parse",this.parseMarkdown(!0)),bt(this,"parseInline",this.parseMarkdown(!1)),bt(this,"Parser",Sr),bt(this,"Renderer",Sp),bt(this,"TextRenderer",Zb),bt(this,"Lexer",xr),bt(this,"Tokenizer",xp),bt(this,"Hooks",Hu),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 Sp(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 xp(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 Hu;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];Hu.passThroughHooks.has(a)?r[o]=c=>{if(this.defaults.async&&Hu.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 xr.lex(t,e??this.defaults)}parser(t,e){return Sr.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?xr.lex:xr.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?Sr.parse:Sr.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?xr.lex:xr.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?Sr.parse:Sr.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+=`
133
133
  Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+Ra(n.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(n);throw n}}},ks=new oF;function ot(t,e){return ks.parse(t,e)}ot.options=ot.setOptions=function(t){return ks.setOptions(t),ot.defaults=ks.defaults,o3(ot.defaults),ot},ot.getDefaults=Vb,ot.defaults=Ss,ot.use=function(...t){return ks.use(...t),ot.defaults=ks.defaults,o3(ot.defaults),ot},ot.walkTokens=function(t,e){return ks.walkTokens(t,e)},ot.parseInline=ks.parseInline,ot.Parser=Sr,ot.parser=Sr.parse,ot.Renderer=Sp,ot.TextRenderer=Zb,ot.Lexer=xr,ot.lexer=xr.lex,ot.Tokenizer=xp,ot.Hooks=Hu,ot.parse=ot,ot.options,ot.setOptions,ot.use,ot.walkTokens,ot.parseInline,Sr.parse,xr.lex;const sF="_base_1ne03_1",lF={base:sF},cF=["p","br","strong","em","u","a","ul","ol","li","h1","h2","h3","h4","h5","h6","code","pre","blockquote","hr"],uF=["href","title","target","rel"];ot.setOptions({breaks:!0,gfm:!0});function dF(t){const{content:e,className:n,...i}=t,r=T.useMemo(()=>{if(!e)return"";const a=ot.parse(e,{async:!1});return kz.sanitize(a,{ALLOWED_TAGS:[...cF],ALLOWED_ATTR:[...uF],ALLOW_DATA_ATTR:!1})},[e]);return r?f.jsx("div",{className:oe(lF.base,n),dangerouslySetInnerHTML:{__html:r},...i}):null}const hF="_controlBar_7jslb_1",fF="_popoverAnchor_7jslb_11",pF="_controlBarSlot_7jslb_15",mF="_confirmationPopover_7jslb_21",gF="_confirmationPopoverAlignRight_7jslb_36",vF="_confirmationPopoverAlignCenter_7jslb_39",bF="_confirmationMessage_7jslb_59",yF="_confirmationActions_7jslb_66",_F="_confirmationButton_7jslb_71",xF="_confirmationButtonCancel_7jslb_89",SF="_confirmationButtonNeutral_7jslb_97",kF="_confirmationButtonDanger_7jslb_105",TF="_controlButton_7jslb_114",wF="_controlButtonIconOnly_7jslb_136",CF="_controlButtonDisabled_7jslb_141",EF="_controlButtonDanger_7jslb_168",RF="_controlButtonContent_7jslb_184",AF="_controlButtonIcon_7jslb_136",NF="_controlButtonLabel_7jslb_200",OF="_controlButtonChevron_7jslb_207",MF="_controlButtonNotificationDot_7jslb_216",DF="_deviceSplitButton_7jslb_228",PF="_deviceSplitButtonEnabled_7jslb_232",LF="_dualButtonContent_7jslb_313",IF="_dualButtonIcon_7jslb_323",jF="_dualButtonLabel_7jslb_332",BF="_screenShareButton_7jslb_346",UF="_screenShareButtonCompact_7jslb_357",Fe={controlBar:hF,popoverAnchor:fF,controlBarSlot:pF,confirmationPopover:mF,confirmationPopoverAlignRight:gF,confirmationPopoverAlignCenter:vF,confirmationMessage:bF,confirmationActions:yF,confirmationButton:_F,confirmationButtonCancel:xF,confirmationButtonNeutral:SF,confirmationButtonDanger:kF,controlButton:TF,controlButtonIconOnly:wF,controlButtonDisabled:CF,controlButtonDanger:EF,controlButtonContent:RF,controlButtonIcon:AF,controlButtonLabel:NF,controlButtonChevron:OF,controlButtonNotificationDot:MF,deviceSplitButton:DF,deviceSplitButtonEnabled:PF,dualButtonContent:LF,dualButtonIcon:IF,dualButtonLabel:jF,screenShareButton:BF,screenShareButtonCompact:UF},zF="_inline_1gpyx_1",FF="_vertical_1gpyx_6",qF="_divider_1gpyx_10",HF="_dividerVertical_1gpyx_16",VF="_customDivider_1gpyx_21",Vu={inline:zF,vertical:FF,divider:qF,dividerVertical:HF,customDivider:VF},k3={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 kr(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 GF(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",v={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=kr(r);y&&(v.gap=y)}const m=fi.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:oe(Vu.divider,i==="vertical"&&Vu.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:Vu.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const b=S(x);b&&g.push(b)}g.push(y)}),f.jsx(p,{ref:e,className:oe(Vu.inline,i==="vertical"&&Vu.vertical,c),style:v,...h,children:g})}const Tp=fi.forwardRef(GF);Tp.displayName="Inline";function WF(){const[t,e]=T.useState(()=>typeof window>"u"?!1:window.innerWidth<768);return T.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 wp(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=oe(Fe.controlButton,a&&Fe.controlButtonDisabled,l&&Fe.controlButtonIconOnly,r==="danger"&&Fe.controlButtonDanger,o),v=Number.parseInt(Nb[s],10),m=r==="danger"?"outline":"primary",S=r==="danger"?"danger":"default",g=f.jsxs(f.Fragment,{children:[f.jsxs("span",{className:Fe.controlButtonContent,children:[e?f.jsx("span",{className:Fe.controlButtonIcon,children:fi.isValidElement(e)&&e.props.size===void 0?fi.cloneElement(e,{size:v}):e}):null,l?null:f.jsx("span",{className:Fe.controlButtonLabel,children:n}),l||!i?null:f.jsx("span",{className:Fe.controlButtonChevron,"aria-hidden":"true",children:f.jsx(Ob,{size:16})})]}),c?f.jsx("span",{className:Fe.controlButtonNotificationDot,"aria-hidden":"true"}):null]});return typeof u=="boolean"?f.jsx(hp,{...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(Ro,{...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 YF(t){const{audioDevices:e,currentMicrophoneId:n,isMicrophoneEnabled:i,isScreenShareActive:r,widgetState:a,canPublishData:o,browserSupportsScreenSharing:s,screenShareButtonVariant:l="default",microphoneButtonVariant:c="split",onMicDeviceSelect:u,onMicToggle:d,onChatToggle:h,onLeave:p,onScreenShareToggle:v,showChatNotification:m=!1,isLanguageSelectorEnabled:S=!0,languages:g=[],selectedLanguage:y=null,defaultLanguageCode:x=null,isMultilingual:b=!1,onLanguageChange:k,isChatOpen:w=a==="chat",leadingControl:C,trailingControl:R}=t,A=g.length,N=!S||A===0,O=WF(),B=O?"xs":"sm",X=O,[L,Y]=T.useState(!1),[P,V]=T.useState(!1),K=T.useRef(null),ee=T.useRef(null);T.useEffect(()=>{const Ye=me=>{const Ne=me.composedPath();L&&K.current&&!Ne.includes(K.current)&&Y(!1),P&&ee.current&&!Ne.includes(ee.current)&&V(!1)},Lt=me=>{me.key==="Escape"&&(L&&Y(!1),P&&V(!1))};if(L||P)return document.addEventListener("mousedown",Ye),document.addEventListener("keydown",Lt),()=>{document.removeEventListener("mousedown",Ye),document.removeEventListener("keydown",Lt)}},[L,P]),T.useEffect(()=>{r||Y(!1)},[r]);const $=T.useMemo(()=>e.map(Ye=>({label:Ye.label||`Microphone ${Ye.deviceId.slice(0,8)}`,value:Ye.deviceId})),[e]),U=T.useMemo(()=>n?$.find(Ye=>Ye.value===n)??null:null,[n,$]),Z=T.useCallback(Ye=>{Ye.value,u(Ye.value)},[u]),Q={microphone:!0,screenShare:s,chat:o},le=T.useCallback(()=>{if(r){Y(!0);return}v()},[r,v]),j=T.useCallback(()=>{Y(!1),v()},[v]),ge=T.useCallback(()=>{Y(!1)},[]),H=T.useCallback(()=>{V(!0)},[]),he=T.useCallback(()=>{V(!1),p()},[p]),ve=T.useCallback(()=>{V(!1)},[]);return f.jsx("div",{className:Fe.controlBar,"data-testid":"control-bar","data-controls":JSON.stringify(Q),"data-language-option-count":A>0?String(A):void 0,"data-default-language-code":x??void 0,children:f.jsxs(Tp,{gap:B,align:"center",justify:"center",wrap:X,children:[C?f.jsx("div",{className:Fe.controlBarSlot,children:C}):null,c==="simple"?f.jsx(wp,{icon:i?f.jsx(up,{}):f.jsx(dp,{}),label:"Microphone",onClick:d,isOn:i,"aria-label":i?"Mute microphone":"Unmute microphone"}):f.jsx(MU,{onClick:d,buttonAriaLabel:i?"Mute microphone":"Unmute microphone",options:$,value:U,onChange:Z,variant:"primary",menuPlacement:"top",menuDisabled:$.length===0,menuAriaLabel:"Select microphone device",listboxAriaLabel:"Microphone devices",ariaPressed:i,className:oe(Fe.deviceSplitButton,i&&Fe.deviceSplitButtonEnabled),children:f.jsxs("span",{className:Fe.dualButtonContent,children:[f.jsx("span",{className:Fe.dualButtonIcon,children:i?f.jsx(up,{}):f.jsx(dp,{})}),f.jsx("span",{className:Fe.dualButtonLabel,children:"Microphone"})]})}),o?f.jsx(wp,{icon:f.jsx(OE,{}),label:"Chat",onClick:h,isOn:w,"aria-label":"Toggle chat",showNotificationDot:m}):null,s?f.jsxs("div",{ref:K,className:Fe.popoverAnchor,children:[f.jsx(wp,{icon:f.jsx(LE,{}),label:r?"Share screen off":"Share screen",className:l==="compact"?Fe.screenShareButtonCompact:Fe.screenShareButton,iconOnly:l==="compact",onClick:le,isOn:r,"aria-label":r?"Stop screen sharing":"Start screen sharing"}),L?f.jsxs("div",{className:oe(Fe.confirmationPopover,Fe.confirmationPopoverAlignCenter),role:"dialog","aria-label":"Stop screen sharing confirmation","data-testid":"confirm-stop-share",children:[f.jsx("p",{className:Fe.confirmationMessage,children:"Stop screen sharing?"}),f.jsxs("div",{className:Fe.confirmationActions,children:[f.jsx("button",{type:"button",className:oe(Fe.confirmationButton,Fe.confirmationButtonCancel),onClick:ge,children:"Cancel"}),f.jsx("button",{type:"button",className:oe(Fe.confirmationButton,Fe.confirmationButtonNeutral),onClick:j,children:"Stop"})]})]}):null]}):null,f.jsx(VE,{languages:g,value:y,onChange:k,defaultLanguageCode:x,variant:"control-bar",disabled:N}),f.jsxs("div",{ref:ee,className:Fe.popoverAnchor,children:[f.jsx(wp,{icon:f.jsx(Mb,{}),label:"Leave",variant:"danger",onClick:H,"aria-label":"Leave meeting"}),P?f.jsxs("div",{className:oe(Fe.confirmationPopover,Fe.confirmationPopoverAlignRight),role:"dialog","aria-label":"Leave meeting confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:Fe.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:Fe.confirmationActions,children:[f.jsx("button",{type:"button",className:oe(Fe.confirmationButton,Fe.confirmationButtonCancel),onClick:ve,children:"Cancel"}),f.jsx("button",{type:"button",className:oe(Fe.confirmationButton,Fe.confirmationButtonDanger),onClick:he,children:"Leave"})]})]}):null]}),R?f.jsx("div",{className:Fe.controlBarSlot,children:R}):null]})})}function T3(t){return f.jsx(YF,{...t})}const KF="_controlBar_1n8jn_1",XF="_controlButton_1n8jn_12",$F="_controlButtonDisabled_1n8jn_35",JF="_controlButtonDanger_1n8jn_62",QF="_controlButtonIconOnly_1n8jn_78",ZF="_screenShareButton_1n8jn_83",eq="_controlButtonContent_1n8jn_88",tq="_controlButtonIcon_1n8jn_78",nq="_controlButtonLabel_1n8jn_103",iq="_controlButtonNotificationDot_1n8jn_108",rq="_popoverAnchor_1n8jn_198",aq="_confirmationPopover_1n8jn_202",oq="_confirmationMessage_1n8jn_216",sq="_confirmationActions_1n8jn_223",lq="_confirmationButton_1n8jn_228",cq="_confirmationButtonCancel_1n8jn_246",uq="_confirmationButtonDanger_1n8jn_254",yt={controlBar:KF,controlButton:XF,controlButtonDisabled:$F,controlButtonDanger:JF,controlButtonIconOnly:QF,screenShareButton:ZF,controlButtonContent:eq,controlButtonIcon:tq,controlButtonLabel:nq,controlButtonNotificationDot:iq,popoverAnchor:rq,confirmationPopover:aq,confirmationMessage:oq,confirmationActions:sq,confirmationButton:lq,confirmationButtonCancel:cq,confirmationButtonDanger:uq};function Ts(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=oe(yt.controlButton,r&&yt.controlButtonDisabled,o&&yt.controlButtonIconOnly,i==="danger"&&yt.controlButtonDanger,a),h=i==="danger"?"outline":"primary",p=i==="danger"?"danger":"default",v=f.jsxs(f.Fragment,{children:[f.jsxs("span",{className:yt.controlButtonContent,children:[e?f.jsx("span",{className:yt.controlButtonIcon,children:fi.isValidElement(e)&&e.props.size===void 0?fi.cloneElement(e,{size:20}):e}):null,o?null:f.jsx("span",{className:yt.controlButtonLabel,children:n})]}),s?f.jsx("span",{className:yt.controlButtonNotificationDot,"aria-hidden":"true"}):null]});return typeof l=="boolean"?f.jsx(hp,{...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:v}):f.jsx(Ro,{...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:v})}function dq(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:v=!0,className:m,testId:S,...g}=t,y=!v||c.length===0,[x,b]=T.useState(!1),k=T.useRef(null);T.useEffect(()=>{const O=X=>{const L=X.composedPath();x&&k.current&&!L.includes(k.current)&&b(!1)},B=X=>{X.key==="Escape"&&x&&b(!1)};if(x)return document.addEventListener("mousedown",O),document.addEventListener("keydown",B),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",B)}},[x]);const w=T.useCallback(()=>{a()},[a]),C=T.useCallback(()=>{s()},[s]),R=T.useCallback(()=>{b(!0)},[]),A=T.useCallback(()=>{b(!1),l()},[l]),N=T.useCallback(()=>{b(!1)},[]);return f.jsx("div",{...g,className:oe(yt.controlBar,m),"data-testid":S,children:f.jsxs(Tp,{gap:"xs",align:"center",justify:"center",wrap:!1,children:[f.jsx(Ts,{icon:e?f.jsx(up,{size:18}):f.jsx(dp,{size:18}),label:"Microphone",iconOnly:!0,isOn:e,onClick:w,"aria-label":e?"Mute microphone":"Unmute microphone"}),f.jsx(Ts,{icon:f.jsx(OE,{}),label:"Chat",iconOnly:!0,isOn:n,onClick:o,"aria-label":"Toggle chat",showNotificationDot:r}),f.jsx(Ts,{icon:f.jsx(LE,{}),label:"Screen share",iconOnly:!0,className:yt.screenShareButton,isOn:i,onClick:C,"aria-label":i?"Stop screen sharing":"Start screen sharing"}),f.jsx(VE,{languages:c,value:u,onChange:p,defaultLanguageCode:d,variant:"pip",disabled:y}),f.jsxs("div",{ref:k,className:yt.popoverAnchor,children:[f.jsx(Ts,{icon:f.jsx(Mb,{size:16}),label:"Hang up",iconOnly:!0,variant:"danger",onClick:R,"aria-label":"Hang up"}),x?f.jsxs("div",{className:yt.confirmationPopover,role:"dialog","aria-label":"Hang up confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:yt.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:yt.confirmationActions,children:[f.jsx("button",{type:"button",className:oe(yt.confirmationButton,yt.confirmationButtonCancel),onClick:N,children:"Cancel"}),f.jsx("button",{type:"button",className:oe(yt.confirmationButton,yt.confirmationButtonDanger),onClick:A,children:"Leave"})]})]}):null]})]})})}function hq(t){return f.jsx(dq,{...t})}const fq="_container_nz2la_1",pq={container:fq},mq="_responsive_14d0j_2",Gu={responsive:mq,"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 w3(t){const{as:e,children:n,showAboveWidth:i,hideAboveWidth:r,showAboveHeight:a,hideAboveHeight:o,className:s,...l}=t,c=[Gu.responsive];return i&&c.push(Gu[`showAboveWidth-${i}`]),r&&c.push(Gu[`hideAboveWidth-${r}`]),a&&c.push(Gu[`showAboveHeight-${a}`]),o&&c.push(Gu[`hideAboveHeight-${o}`]),f.jsx(e??"div",{...l,className:oe(c,s),children:n})}function gq(t){const{isMicrophoneEnabled:e,onMicToggle:n,onLeave:i,onReturnToCourseOutline:r,zIndex:a=1e3,className:o,testId:s}=t,[l,c]=T.useState(!1),u=T.useRef(null);T.useEffect(()=>{const g=x=>{const b=x.composedPath();l&&u.current&&!b.includes(u.current)&&c(!1)},y=x=>{x.key==="Escape"&&l&&c(!1)};if(l)return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y)}},[l]);const d=T.useCallback(()=>{n()},[n]),h=T.useCallback(()=>{r()},[r]),p=T.useCallback(()=>{c(!0)},[]),v=T.useCallback(()=>{c(!1),i()},[i]),m=T.useCallback(()=>{c(!1)},[]),S=T.useMemo(()=>({position:"fixed",left:"50%",transform:"translateX(-50%)",bottom:"calc(var(--space-md, 16px) + env(safe-area-inset-bottom))",zIndex:a,width:"100%",maxWidth:"520px",paddingInline:"var(--space-sm, 8px)",boxSizing:"border-box",display:"flex",justifyContent:"center"}),[a]);return f.jsx(w3,{hideAboveWidth:"md",className:o,style:S,"data-testid":s,children:f.jsx("div",{className:pq.container,children:f.jsx("div",{className:oe(yt.controlBar),children:f.jsxs(Tp,{gap:"xs",align:"center",justify:"center",wrap:!1,children:[f.jsx(Ts,{icon:e?f.jsx(up,{size:18}):f.jsx(dp,{size:18}),label:"Microphone",iconOnly:!0,isOn:e,onClick:d,"aria-label":e?"Mute microphone":"Unmute microphone"}),f.jsx(Ts,{icon:f.jsx(jE,{size:18}),label:"Return to course outline",iconOnly:!0,onClick:h,"aria-label":"Return to course outline"}),f.jsxs("div",{ref:u,className:yt.popoverAnchor,children:[f.jsx(Ts,{icon:f.jsx(Mb,{size:16}),label:"Hang up",iconOnly:!0,variant:"danger",onClick:p,"aria-label":"Hang up"}),l?f.jsxs("div",{className:yt.confirmationPopover,role:"dialog","aria-label":"Hang up confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:yt.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:yt.confirmationActions,children:[f.jsx("button",{type:"button",className:oe(yt.confirmationButton,yt.confirmationButtonCancel),onClick:m,children:"Cancel"}),f.jsx("button",{type:"button",className:oe(yt.confirmationButton,yt.confirmationButtonDanger),onClick:v,children:"Leave"})]})]}):null]})]})})})})}const vq="_container_zht0b_1",bq="_containerGradient_zht0b_14",yq="_containerFlat_zht0b_24",_q="_halo_zht0b_28",xq="_outerRing_zht0b_38",Sq="_circle_zht0b_42",kq="_image_zht0b_72",Tq="_captionContainer_zht0b_88",wq="_captionRegion_zht0b_99",Aa={container:vq,containerGradient:bq,containerFlat:yq,halo:_q,outerRing:xq,circle:Sq,image:kq,captionContainer:Tq,captionRegion:wq},Cq="_statusText_1dkze_6",Eq={statusText:Cq},Rq={idle:null,thinking:"Thinking...",searching:"Searching..."};function Aq(t){const{status:e,size:n="md"}=t,i=e?Rq[e]:null,r=i!==null;return f.jsx("div",{className:Eq.statusText,"data-visible":r,"data-size":n,"aria-live":"polite",children:i})}const Nq="https://obi-static.s3.ap-southeast-2.amazonaws.com/images/obi-avatar.png",Oq={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 C3(t){const{audioPower:e,size:n="md",background:i="gradient",imageSrc:r=Nq,accentColor:a,ariaLabel:o="Avatar placeholder",status:s,captionsText:l,className:c,style:u,...d}=t,h=Oq[n],p=Math.min(1,Math.max(0,e)),v=p>.01,m=v?Math.min(1,p/.5):0,S=v?Math.max(1,m*h.maxBorderWidth):0,g=1.02,y=v?g+p*h.outerRingScalePower:g,x=v?.2+p*.35:0,b={...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},w=l!=null&&l!=="";return f.jsxs("div",{...d,className:oe(Aa.container,i==="gradient"?Aa.containerGradient:Aa.containerFlat,c),style:b,"data-testid":"avatar-fallback","aria-label":o,role:"img",children:[f.jsxs("div",{className:Aa.halo,style:k,children:[f.jsx("div",{className:Aa.outerRing,"aria-hidden":"true"}),f.jsx("div",{className:Aa.circle,children:f.jsx("img",{className:Aa.image,src:r,alt:"","aria-hidden":"true"})}),f.jsx(Aq,{status:s,size:n})]}),w&&f.jsx("div",{className:Aa.captionContainer,children:f.jsx("div",{className:Aa.captionRegion,"data-size":n,role:"status","aria-live":"polite","aria-atomic":"true",children:l})})]})}const Mq="_container_1k3qg_11",Dq="_screenshot_1k3qg_20",Pq="_flash_1k3qg_30",ey={container:Mq,screenshot:Dq,flash:Pq};function Lq(t){const{isActive:e,imageUrl:n,onComplete:i,duration:r=2e3}=t,[a,o]=T.useState(!1),s=T.useRef(null),l=T.useRef(i);return T.useEffect(()=>{l.current=i},[i]),T.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:ey.container,"aria-live":"polite","aria-label":"Screenshot captured",children:[n&&f.jsx("img",{src:n,alt:"Captured screenshot",className:ey.screenshot}),f.jsx("div",{className:ey.flash})]}):null}const Iq="_container_13ukq_1",jq="_dragging_13ukq_5",Bq="_placeholder_13ukq_9",Uq="_handleButton_13ukq_15",zq="_customHandle_13ukq_105",Vl={container:Iq,dragging:jq,placeholder:Bq,handleButton:Uq,"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:zq};function Fq(t){const{disabled:e,lingerMs:n,isDragging:i}=t,[r,a]=T.useState(!1),o=T.useRef(null),s=T.useCallback(()=>{o.current!==null&&(window.clearTimeout(o.current),o.current=null)},[]),l=T.useCallback(()=>{e||(s(),a(!0))},[s,e]),c=T.useCallback(()=>{e||i||(s(),o.current=window.setTimeout(()=>{a(!1),o.current=null},n))},[s,e,i,n]);return T.useEffect(()=>{i&&l()},[i,l]),T.useEffect(()=>s,[s]),{isHandleVisible:r,showHandle:l,scheduleHideHandle:c}}function qq(t){const{initialPosition:e,preserveSpace:n,onPositionChange:i}=t,r=T.useRef(null),[a,o]=T.useState(!!e),[s,l]=T.useState(!1),[c,u]=T.useState(null),[d,h]=T.useState(()=>e??{x:0,y:0}),p=T.useRef(d);s||(p.current=d);const v=T.useRef(null),m=T.useRef(!1),S=T.useRef(!1);T.useEffect(()=>{e&&(S.current||(o(!0),h(e),p.current=e))},[e==null?void 0:e.x,e==null?void 0:e.y]),T.useEffect(()=>{if(e||m.current)return;const b=r.current;if(!b)return;const k=b.getBoundingClientRect(),w={x:k.left,y:k.top};m.current=!0,o(!0),h(w),p.current=w,u(n?{width:k.width,height:k.height}:null)},[e,n]);const g=T.useCallback(b=>{const k=v.current;if(!(!k||b.pointerId!==k.pointerId)){v.current=null,S.current=!0,h(p.current),l(!1);try{b.currentTarget.releasePointerCapture(k.pointerId)}catch{}}},[]),y=T.useCallback(b=>{b.button===0&&(b.preventDefault(),b.currentTarget.setPointerCapture(b.pointerId),v.current={pointerId:b.pointerId,startClientX:b.clientX,startClientY:b.clientY,startX:p.current.x,startY:p.current.y},l(!0))},[]),x=T.useCallback(b=>{const k=v.current;if(!k||b.pointerId!==k.pointerId)return;const w={x:k.startX+(b.clientX-k.startClientX),y:k.startY+(b.clientY-k.startClientY)};p.current=w,r.current&&(r.current.style.transform=`translate3d(${w.x}px, ${w.y}px, 0)`),i==null||i(w)},[i]);return{containerRef:r,isFixed:a,isDragging:s,position:d,placeholderSize:c,onPointerDown:y,onPointerMove:x,endDrag:g}}function Hq(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:v,isDragging:m,position:S,placeholderSize:g,onPointerDown:y,onPointerMove:x,endDrag:b}=qq({initialPosition:r,preserveSpace:o,onPositionChange:l}),{isHandleVisible:k,showHandle:w,scheduleHideHandle:C}=Fq({disabled:a,lingerMs:u,isDragging:m}),R=typeof e=="function",A=T.useMemo(()=>{const O=B=>f.jsx("div",{className:oe(Vl.customHandle,B.className),onPointerDown:y,onPointerMove:x,onPointerUp:b,onPointerCancel:b,children:B.children});return O.displayName="Draggable.Handle",O},[y,x,b]),N={...d,position:v?"fixed":"relative",top:v?0:d==null?void 0:d.top,left:v?0:d==null?void 0:d.left,transform:v?`translate3d(${S.x}px, ${S.y}px, 0)`:d==null?void 0:d.transform,zIndex:v?s:d==null?void 0:d.zIndex};return f.jsxs(f.Fragment,{children:[o&&v&&g?f.jsx("div",{className:Vl.placeholder,style:{width:g.width,height:g.height}}):null,f.jsxs("div",{ref:p,className:oe(Vl.container,m?Vl.dragging:null,n),"data-handle-visible":R?void 0:a?"false":k||m?"true":"false",style:N,onMouseEnter:R?void 0:w,onMouseLeave:R?void 0:C,...h,children:[!R&&!a?f.jsx("button",{type:"button",className:oe(Vl.handleButton,Vl[`handle-${i}`]),"aria-label":c,onMouseEnter:w,onMouseLeave:C,onPointerDown:O=>{w(),y(O)},onPointerMove:x,onPointerUp:b,onPointerCancel:b}):null,R?e({Handle:A}):e]})]})}const Vq="_container_gzwdo_1",Gq="_captionRegion_gzwdo_14",Wq="_status_gzwdo_22",Yq="_captionText_gzwdo_29",Cp={container:Vq,captionRegion:Gq,status:Wq,captionText:Yq},Kq={idle:null,thinking:"Thinking...",searching:"Searching..."};function Xq(t){const{text:e,status:n,className:i,...r}=t,a=n?Kq[n]:null;return f.jsx("div",{...r,className:oe(Cp.container,i),"data-testid":"pip-captions-panel",children:f.jsxs("div",{className:Cp.captionRegion,role:"status","aria-live":"polite","aria-atomic":"true",children:[a?f.jsx("div",{className:Cp.status,children:a}):null,f.jsx("div",{className:Cp.captionText,children:e})]})})}const $q="_panel_1laxg_1",Jq="_row_1laxg_22",Qq="_stepContent_1laxg_29",Zq="_stepLabel_1laxg_37",eH="_currentStep_1laxg_44",tH="_nextStep_1laxg_51",nH="_skipButtonContainer_1laxg_65",iH="_circleButton_1laxg_73",rH="_arrowPlaceholder_1laxg_100",aH="_skipButton_1laxg_65",ir={panel:$q,row:Jq,stepContent:Qq,stepLabel:Zq,currentStep:eH,nextStep:tH,skipButtonContainer:nH,circleButton:iH,arrowPlaceholder:rH,skipButton:aH},oH="_truncatedText_1u580_1",sH={truncatedText:oH};function E3(t){const{children:e,maxLines:n=2,className:i,"data-testid":r}=t;return f.jsx("div",{className:`${sH.truncatedText} ${i||""}`,style:{WebkitLineClamp:n},"data-testid":r,children:e})}function lH(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 ty(t,e){return e<=0||typeof t!="number"||!Number.isFinite(t)?0:Math.min(Math.max(Math.trunc(t),1),e)-1}function cH(t){var A;const{steps:e,currentStep:n,onStepClick:i,hideTrailingConclusionStep:r=!0,className:a,testId:o,...s}=t,{visibleSteps:l,currentIndex:c}=T.useMemo(()=>lH(e,n,r),[n,r,e]),[u,d]=T.useState(()=>ty(n,l.length)),h=T.useRef(!1);T.useEffect(()=>{if(!h.current)d(ty(n,l.length));else{const N=ty(n,l.length);u===N&&(h.current=!1)}},[n,l,u]);const p=l.length,v=l[u],m=u>0,S=u<p-1,g=S?(A=l[u+1])==null?void 0:A.title:void 0,y=p>0,x=y?u+1:0,b=y?`Step ${x}/${p}`:"No steps available",k=c!==null&&v&&u!==c,w=()=>{m&&(h.current=!0,d(N=>Math.max(N-1,0)))},C=()=>{S&&(h.current=!0,d(N=>Math.min(N+1,p-1)))},R=()=>{!k||!v||!i||(h.current=!1,i(u,v))};return f.jsxs("div",{...s,className:oe(ir.panel,a),"data-testid":o,role:"group","aria-label":"Course progress",children:[f.jsxs("div",{className:ir.row,children:[m?f.jsx("button",{type:"button",className:ir.circleButton,"aria-label":"Previous step",onClick:w,children:f.jsx(ME,{size:14})}):f.jsx("span",{className:ir.arrowPlaceholder,"aria-hidden":"true"}),f.jsxs("div",{className:ir.stepContent,children:[f.jsx(Si,{className:ir.stepLabel,"aria-live":"polite",children:b}),f.jsx(E3,{maxLines:2,children:f.jsx(Si,{className:ir.currentStep,"data-testid":"pip-outline-current-step",children:(v==null?void 0:v.title)??"No steps available"})}),g?f.jsx(E3,{maxLines:2,children:f.jsxs(Si,{variant:"muted",className:ir.nextStep,children:["Next: ",g]})}):null]}),S?f.jsx("button",{type:"button",className:ir.circleButton,"aria-label":"Next step",onClick:C,children:f.jsx(tB,{size:14})}):f.jsx("span",{className:ir.arrowPlaceholder,"aria-hidden":"true"})]}),k?f.jsx("div",{className:ir.skipButtonContainer,children:f.jsx("button",{type:"button",className:ir.skipButton,"aria-label":"Skip to this step",onClick:R,children:f.jsx(aB,{size:14})})}):null]})}const uH="_window_zm5au_1",dH="_exitButton_zm5au_14",hH="_content_zm5au_47",fH="_contentTopOverlay_zm5au_58",pH="_dragHandle_zm5au_68",mH="_contentBottomOverlay_zm5au_78",gH="_controls_zm5au_87",vH="_messagesPanelWrapper_zm5au_95",Ao={window:uH,exitButton:dH,content:hH,contentTopOverlay:fH,dragHandle:pH,contentBottomOverlay:mH,controls:gH,messagesPanelWrapper:vH};function bH(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function yH(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:v,...m}=t,S=i,g=n.isChatOpen&&!S&&l,y=c==null?void 0:c.captionsText,x=a&&bH(y),[b,k]=T.useState(!1),w=T.useRef(h),C=T.useCallback(()=>{k(!1)},[]);T.useEffect(()=>{h&&h>0&&h!==w.current&&k(!0),w.current=h},[h]);const R=T.useCallback(()=>f.jsx(C3,{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(cH,{steps:s.steps,currentStep:s.currentStep,onStepClick:s.onStepClick,hideTrailingConclusionStep:s.hideTrailingConclusionStep}):R():g?f.jsx("div",{className:Ao.messagesPanelWrapper,children:l}):x?f.jsx(Xq,{text:y}):R();return f.jsxs("div",{...m,className:oe(Ao.window,p),"data-testid":v,role:"group","aria-label":"Picture-in-Picture",children:[f.jsxs("div",{className:Ao.content,children:[f.jsx("div",{className:Ao.contentTopOverlay,children:u}),f.jsx("button",{type:"button",className:Ao.exitButton,onClick:e,"aria-label":"Exit PiP",children:f.jsx(nB,{size:14})}),A,!g&&f.jsxs("div",{className:Ao.contentBottomOverlay,children:[f.jsx(hp,{isOn:i,onClick:r,variant:"primary",size:"xs","aria-label":"Toggle course outline",children:f.jsx(jE,{size:18})}),f.jsx(hp,{isOn:a,onClick:o,variant:"primary",size:"xs","aria-label":"Toggle captions",children:f.jsx(eB,{size:18})})]}),f.jsx(Lq,{isActive:b,imageUrl:d??null,onComplete:C})]}),f.jsx("div",{className:Ao.controls,children:f.jsx(hq,{...n})})]})}function _H(t){const{initialPosition:e,onPositionChange:n,zIndex:i=1e3,...r}=t;return f.jsx(Hq,{initialPosition:e,onPositionChange:n,zIndex:i,preserveSpace:!1,children:({Handle:a})=>f.jsx(yH,{...r,contentTopOverlaySlot:f.jsx(a,{className:Ao.dragHandle})})})}const xH="_root_ygi3o_1",SH="_overlay_ygi3o_7",kH="_caption_ygi3o_17",ny={root:xH,overlay:SH,caption:kH};function TH(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function wH(t){const{children:e,className:n,text:i}=t,r=TH(i);return f.jsxs("div",{className:oe(ny.root,n),children:[e,r?f.jsx("div",{className:ny.overlay,role:"status","aria-live":"polite","aria-atomic":"true",children:f.jsx("div",{className:ny.caption,children:i})}):null]})}const CH="_box_dc9yv_1",EH={box:CH},R3={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},A3={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 RH(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in R3)return R3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function AH(t){if(t!==void 0){if(t in A3)return A3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function NH(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:v,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:b,marginRight:k,radius:w,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:B,radiusBottomLeft:X,radiusBottomRight:L,background:Y,gap:P,style:V,...K}=t,ee=n??"div",$={...V},U=$,Z={},Q=(H,he)=>{if(he===void 0)return;const ve=kr(he);ve&&($[H]=ve)},le=(H,he)=>{if(he===void 0)return;const ve=kr(he);ve&&($[H]=ve)},j=(H,he)=>{if(he===void 0)return;const ve=RH(he);ve&&($[H]=ve)},ge={sm:d,md:h,lg:p,xl:v};if(r!==void 0){const H=kr(r);H&&(U["--box-padding"]=H)}for(const[H,he]of Object.entries(ge)){if(he===void 0)continue;const ve=kr(he);ve&&(U[`--box-padding-${H}`]=ve,Z[`data-padding-${H}`]="")}if(a!==void 0){const H=kr(a);H&&($.paddingLeft=H,$.paddingRight=H)}if(o!==void 0){const H=kr(o);H&&($.paddingTop=H,$.paddingBottom=H)}if(Q("paddingTop",s),Q("paddingBottom",l),Q("paddingLeft",c),Q("paddingRight",u),m!==void 0){const H=kr(m);H&&($.margin=H)}if(S!==void 0){const H=kr(S);H&&($.marginLeft=H,$.marginRight=H)}if(g!==void 0){const H=kr(g);H&&($.marginTop=H,$.marginBottom=H)}if(le("marginTop",y),le("marginBottom",x),le("marginLeft",b),le("marginRight",k),P!==void 0){const H=kr(P);H&&($.gap=H)}if(j("borderRadius",w),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",X),j("borderBottomRightRadius",L),Y!==void 0){const H=AH(Y);H&&($.background=H)}return f.jsx(ee,{ref:e,className:oe(EH.box,i),style:$,...Z,...K})}const Ep=fi.forwardRef(NH);Ep.displayName="Box";const OH="_panel_eawk4_1",MH="_selected_eawk4_10",N3={panel:OH,selected:MH};function Wu(t){const{children:e,className:n,selected:i,...r}=t;return f.jsx("div",{className:oe(N3.panel,i?N3.selected:null,n),...r,children:e})}const DH="_root_yccm8_1",PH="_header_yccm8_8",LH="_icon_yccm8_15",IH="_text_yccm8_26",jH="_heading_yccm8_33",BH="_description_yccm8_41",UH="_body_yccm8_47",zH="_footer_yccm8_54",No={root:DH,header:PH,icon:LH,text:IH,heading:jH,description:BH,body:UH,footer:zH};function O3(t){const{className:e,...n}=t;return f.jsx("div",{className:oe(No.icon,e),...n})}function M3(t){const{className:e,...n}=t;return f.jsx("h3",{className:oe(No.heading,e),...n})}function D3(t){const{className:e,...n}=t;return f.jsx("p",{className:oe(No.description,e),...n})}function P3(t){const{className:e,...n}=t;return f.jsx("div",{className:oe(No.footer,e),...n})}function FH(t){const e=T.Children.toArray(t),n=[];let i,r,a,o;for(const s of e){if(T.isValidElement(s)&&s.type===O3&&i===void 0){i=s;continue}if(T.isValidElement(s)&&s.type===M3&&r===void 0){r=s;continue}if(T.isValidElement(s)&&s.type===D3&&a===void 0){a=s;continue}if(T.isValidElement(s)&&s.type===P3&&o===void 0){o=s;continue}n.push(s)}return{icon:i,heading:r,description:a,footer:o,body:n}}function qH(t){const{children:e,className:n,...i}=t,r=FH(e),a=r.icon||r.heading||r.description;return f.jsxs(Wu,{className:oe(No.root,n),...i,children:[a?f.jsxs("div",{className:No.header,children:[r.icon,r.heading||r.description?f.jsxs("div",{className:No.text,children:[r.heading,r.description]}):null]}):null,r.body.length?f.jsx("div",{className:No.body,children:r.body}):null,r.footer]})}const iy=Object.assign(qH,{Icon:O3,Heading:M3,Description:D3,Footer:P3}),HH="_panel_f4a69_1",VH="_header_f4a69_10",GH="_title_f4a69_19",WH="_scrollArea_f4a69_29",YH="_scrollable_f4a69_34",KH="_list_f4a69_39",XH="_courseButton_f4a69_45",$H="_courseCard_f4a69_61",JH="_loading_f4a69_65",QH="_spinnerWrapper_f4a69_69",ZH="_spinner_f4a69_69",eV="_contentHidden_f4a69_92",tV="_courseHeading_f4a69_101",nV="_courseDescription_f4a69_107",iV="_empty_f4a69_116",zn={panel:HH,header:VH,title:GH,scrollArea:WH,scrollable:YH,list:KH,courseButton:XH,courseCard:$H,loading:JH,spinnerWrapper:QH,spinner:ZH,contentHidden:eV,courseHeading:tV,courseDescription:nV,empty:iV};function rV(t){const{selectionMode:e,selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r}=t,a=n!==void 0,[o,s]=T.useState(()=>i??[]),l=a?n:o,c=T.useCallback(d=>{a||s(d),r==null||r(d)},[a,r]),u=T.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 aV(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(Wu,{...d,className:oe(zn.panel,i),role:"region","aria-label":n??e,"data-testid":u,children:[f.jsx("div",{className:zn.header,children:f.jsx(Si,{as:"h2",className:zn.title,children:e})}),f.jsx("div",{className:zn.scrollArea,children:f.jsx(ql,{className:zn.scrollable,children:r.length===0?f.jsx(Si,{variant:"muted",className:zn.empty,"data-testid":"course-panel-empty",children:c}):f.jsx("div",{className:zn.list,"data-testid":"course-panel-list",children:r.map(h=>{const p=o.includes(h.id),v=l!=null&&h.id===l,m=h.disabled===!0||l!=null,S=oe(zn.courseButton,v&&zn.loading);return f.jsxs("button",{type:"button",className:S,"aria-pressed":p,"aria-disabled":m,"aria-busy":v||void 0,disabled:m,onClick:()=>s==null?void 0:s(h.id,h),"data-testid":`course-panel-item-${h.id}`,children:[v?f.jsx("span",{className:zn.spinnerWrapper,"aria-hidden":"true","data-testid":`course-panel-item-spinner-${h.id}`,children:f.jsx("span",{className:zn.spinner})}):null,f.jsxs(iy,{selected:p,className:zn.courseCard,children:[f.jsx(iy.Heading,{className:oe(zn.courseHeading,v&&zn.contentHidden),children:h.title}),h.description?f.jsx(iy.Description,{className:oe(zn.courseDescription,v&&zn.contentHidden),children:h.description}):null]})]},h.id)})})})})]})}function L3(t){const{selectionMode:e="multiple",selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r,onCourseToggle:a,...o}=t,{selectedCourseIds:s,toggleCourseId:l}=rV({selectionMode:e,selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r}),c=T.useCallback((u,d)=>{l(u),a==null||a(u,d)},[a,l]);return f.jsx(aV,{...o,selectionMode:e,selectedCourseIds:s,onCourseToggle:c})}const oV="_panel_1je0q_1",sV="_header_1je0q_10",lV="_headerActions_1je0q_19",cV="_popoverAnchor_1je0q_27",uV="_backButton_1je0q_31",dV="_divider_1je0q_38",hV="_title_1je0q_44",fV="_scrollArea_1je0q_54",pV="_scrollable_1je0q_59",mV="_list_1je0q_64",gV="_section_1je0q_70",vV="_sectionHeader_1je0q_76",bV="_sectionTitle_1je0q_80",yV="_sectionTitleCompact_1je0q_88",_V="_item_1je0q_92",xV="_itemClickable_1je0q_106",SV="_itemCompleted_1je0q_110",kV="_itemCurrent_1je0q_114",TV="_itemFuture_1je0q_118",wV="_itemDisabled_1je0q_123",CV="_row_1je0q_137",EV="_stepHeader_1je0q_144",RV="_stepNumber_1je0q_153",AV="_stepTitle_1je0q_159",NV="_checkIcon_1je0q_171",OV="_empty_1je0q_175",MV="_confirmationPopover_1je0q_180",DV="_confirmationMessage_1je0q_204",PV="_confirmationActions_1je0q_211",LV="_confirmationButton_1je0q_216",IV="_confirmationButtonCancel_1je0q_234",jV="_confirmationButtonNeutral_1je0q_242",Re={panel:oV,header:sV,headerActions:lV,popoverAnchor:cV,backButton:uV,divider:dV,title:hV,scrollArea:fV,scrollable:pV,list:mV,section:gV,sectionHeader:vV,sectionTitle:bV,sectionTitleCompact:yV,item:_V,itemClickable:xV,itemCompleted:SV,itemCurrent:kV,itemFuture:TV,itemDisabled:wV,row:CV,stepHeader:EV,stepNumber:RV,stepTitle:AV,checkIcon:NV,empty:OV,confirmationPopover:MV,confirmationMessage:DV,confirmationActions:PV,confirmationButton:LV,confirmationButtonCancel:IV,confirmationButtonNeutral:jV};function BV(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},(v,m)=>m),currentIndex:null,futureIndices:[]};const c=Math.min(Math.max(l,1),s)-1,u=Array.from({length:Math.max(0,c)},(v,m)=>m),d=Math.min(c,s-1),h=Array.from({length:Math.max(0,s-(d+1))},(v,m)=>d+1+m);return{visibleSteps:o,completedIndices:u,currentIndex:d,futureIndices:h}}function UV(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:v="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,b]=T.useState(!1),k=T.useRef(null),w=h||!d,C=T.useCallback(V=>(V+1).toString().padStart(2,"0"),[]),{visibleSteps:R,completedIndices:A,currentIndex:N,futureIndices:O}=T.useMemo(()=>BV({steps:r,currentStep:a,hideTrailingConclusionStep:s}),[a,s,r]),B=c==="compact"?"md":"lg",X=T.useCallback(()=>{w||b(V=>!V)},[w]),L=T.useCallback(()=>{b(!1)},[]),Y=T.useCallback(()=>{b(!1),d&&d()},[d]);T.useEffect(()=>{if(!x)return;const V=ee=>{const $=ee.composedPath();k.current&&!$.includes(k.current)&&b(!1)},K=ee=>{ee.key==="Escape"&&b(!1)};return document.addEventListener("mousedown",V),document.addEventListener("keydown",K),()=>{document.removeEventListener("mousedown",V),document.removeEventListener("keydown",K)}},[x]),T.useEffect(()=>{w&&x&&b(!1)},[w,x]);const P=T.useCallback((V,K)=>{const ee=R[V];if(!ee)return null;const $=typeof o=="function",U=$&&ee.disabled===!0,Z=$&&!U,Q=oe(Re.item,{[Re.itemClickable]:Z,[Re.itemCompleted]:K==="completed",[Re.itemCurrent]:K==="current",[Re.itemFuture]:K==="future",[Re.itemDisabled]:U}),le=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:ee.title})]}),K==="completed"?f.jsx(lp,{size:20,className:Re.checkIcon}):null]});return $?f.jsx(Ep,{as:"button",type:"button",className:Q,onClick:()=>{Z&&o(V,ee)},disabled:U,"aria-current":K==="current"?"step":void 0,"aria-label":`Step ${C(V)}: ${ee.title}`,"data-testid":`course-outline-item-${ee.id}`,padding:B,radius:"panel",gap:"sm",children:le},ee.id):f.jsx(Ep,{className:Q,"aria-current":K==="current"?"step":void 0,"aria-label":`Step ${C(V)}: ${ee.title}`,"data-testid":`course-outline-item-${ee.id}`,padding:B,radius:"panel",gap:"sm",children:le},ee.id)},[C,B,o,R]);return f.jsxs(Wu,{...y,className:oe(Re.panel,i),role:"region","aria-label":n??e,"data-testid":u,children:[f.jsxs("div",{className:Re.header,children:[f.jsx(Si,{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(Ro,{type:"button",variant:"secondary",color:"default",size:"sm",className:Re.backButton,onClick:X,disabled:w,"aria-label":p,"data-testid":"course-outline-back-button",children:[f.jsx(ME,{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:v}),f.jsxs("div",{className:Re.confirmationActions,children:[f.jsx("button",{type:"button",className:oe(Re.confirmationButton,Re.confirmationButtonCancel),onClick:L,"data-testid":"course-outline-back-cancel",children:S}),f.jsx("button",{type:"button",className:oe(Re.confirmationButton,Re.confirmationButtonNeutral),onClick:Y,"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(ql,{className:Re.scrollable,children:R.length===0?f.jsx(Si,{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:oe(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:oe(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:oe(Re.sectionTitle,c==="compact"?Re.sectionTitleCompact:null),children:"Upcoming"})}),O.map(V=>P(V,"future"))]}):null]})})})]})}function zV(t){return f.jsx(UV,{...t})}const FV="_panel_h7cuf_1",qV="_messagesArea_h7cuf_20",HV="_messagesList_h7cuf_46",VV="_messageItem_h7cuf_53",GV="_messageMetadata_h7cuf_59",WV="_senderName_h7cuf_67",YV="_timestamp_h7cuf_71",KV="_messageBubble_h7cuf_75",XV="_agentMessage_h7cuf_85",$V="_agentActions_h7cuf_89",JV="_copyButton_h7cuf_95",QV="_copyButtonCopied_h7cuf_129",ZV="_empty_h7cuf_133",eG="_composer_h7cuf_140",tG="_composerDisabled_h7cuf_160",nG="_composerInput_h7cuf_165",iG="_sendButton_h7cuf_180",Ln={panel:FV,messagesArea:qV,messagesList:HV,messageItem:VV,messageMetadata:GV,senderName:WV,timestamp:YV,messageBubble:KV,agentMessage:XV,agentActions:$V,copyButton:JV,copyButtonCopied:QV,empty:ZV,composer:eG,composerDisabled:tG,composerInput:nG,sendButton:iG};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 oG(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 sG(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 lG(t){const{messages:e,localIdentity:n,onSend:i,isSending:r=!1,inputPlaceholder:a="Type a message...",className:o,testId:s,...l}=t,[c,u]=T.useState(""),[d,h]=T.useState(null),p=T.useRef(null),v=T.useRef(null),m=T.useMemo(()=>{const b=e[e.length-1];return b?b.id??`${b.timestamp}-${e.length-1}`:null},[e]);T.useEffect(()=>{var b,k;(k=(b=p.current)==null?void 0:b.scrollIntoView)==null||k.call(b,{behavior:"smooth"})},[m]),T.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=null)},[]);const S=T.useCallback(async()=>{const b=c.trim();b.length!==0&&(await i(b),u(""))},[c,i]),g=T.useCallback(b=>{b.key==="Enter"&&(b.preventDefault(),S())},[S]),y=T.useCallback(async(b,k)=>{try{await sG(b.message??""),h(k),v.current&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>{h(null),v.current=null},2e3)}catch(w){console.warn("[PiPChatPanel] Failed to copy message",w)}},[]),x=c.trim().length>0&&!r;return f.jsxs("div",{...l,className:oe(Ln.panel,o),"data-testid":s,role:"region","aria-label":"Chat",children:[f.jsx("div",{className:Ln.messagesArea,children:e.length===0?f.jsx("div",{className:Ln.empty,"data-testid":"pip-chat-panel-empty",children:"No messages yet"}):f.jsxs("div",{className:Ln.messagesList,"data-testid":"pip-chat-panel-list",children:[e.map((b,k)=>{const w=b.id??`${b.timestamp}-${k}`,C=aG(b,n),R=d===w;return f.jsxs("div",{className:oe(Ln.messageItem,C&&Ln.agentMessage),"data-testid":`pip-chat-panel-message-${w}`,children:[f.jsxs("div",{className:Ln.messageMetadata,children:[f.jsx("span",{className:Ln.senderName,children:oG(b,n)}),f.jsx("span",{className:Ln.timestamp,children:rG(b.timestamp)})]}),f.jsx("div",{className:Ln.messageBubble,children:b.message}),C?f.jsx("div",{className:Ln.agentActions,children:f.jsx("button",{type:"button",className:oe(Ln.copyButton,R&&Ln.copyButtonCopied),onClick:()=>void y(b,w),"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(DE,{size:14})})}):null]},w)}),f.jsx("div",{ref:p})]})}),f.jsxs("div",{className:oe(Ln.composer,r&&Ln.composerDisabled),children:[f.jsx("input",{type:"text",className:Ln.composerInput,value:c,onChange:b=>u(b.target.value),onKeyDown:g,placeholder:a,disabled:r,"aria-label":"Message"}),f.jsx("button",{type:"button",className:Ln.sendButton,onClick:()=>void S(),disabled:!x,"aria-label":"Send message",children:f.jsx(IE,{size:16})})]})]})}const cG="_panel_k5ick_1",uG="_header_k5ick_11",dG="_title_k5ick_19",hG="_titleCompact_k5ick_29",fG="_headerActions_k5ick_33",pG="_closeButton_k5ick_39",mG="_divider_k5ick_67",gG="_body_k5ick_73",vG="_messagesArea_k5ick_81",bG="_scrollable_k5ick_86",yG="_messagesList_k5ick_90",_G="_messageItem_k5ick_98",xG="_messageMetadata_k5ick_104",SG="_senderName_k5ick_112",kG="_timestamp_k5ick_116",TG="_messageBubble_k5ick_120",wG="_messageText_k5ick_124",CG="_agentMessage_k5ick_130",EG="_agentActions_k5ick_134",RG="_copyButton_k5ick_140",AG="_copyButtonCopied_k5ick_174",NG="_inputRow_k5ick_178",OG="_empty_k5ick_182",MG="_composer_k5ick_188",DG="_composerDefault_k5ick_203",PG="_composerCompact_k5ick_208",LG="_composerDisabled_k5ick_218",IG="_composerInputWrapper_k5ick_223",jG="_composerInput_k5ick_223",BG="_sendButton_k5ick_240",UG="_sendButtonCompact_k5ick_257",rt={panel:cG,header:uG,title:dG,titleCompact:hG,headerActions:fG,closeButton:pG,divider:mG,body:gG,messagesArea:vG,scrollable:bG,messagesList:yG,messageItem:_G,messageMetadata:xG,senderName:SG,timestamp:kG,messageBubble:TG,messageText:wG,agentMessage:CG,agentActions:EG,copyButton:RG,copyButtonCopied:AG,inputRow:NG,empty:OG,composer:MG,composerDefault:DG,composerCompact:PG,composerDisabled:LG,composerInputWrapper:IG,composerInput:jG,sendButton:BG,sendButtonCompact:UG};function zG(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 FG(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 qG(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 HG(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 VG(t){const{disabled:e,placeholder:n,size:i="md",autoFocus:r,onSend:a}=t,[o,s]=T.useState(""),l=T.useCallback(async()=>{const p=o.trim();p.length!==0&&(await a(p),s(""))},[a,o]),c=T.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:oe(rt.composer,u?rt.composerCompact:rt.composerDefault,e?rt.composerDisabled:null),children:[f.jsx("div",{className:rt.composerInputWrapper,children:f.jsx(UE,{value:o,onChange:s,onKeyDown:c,className:rt.composerInput,placeholder:n??"Send a message ...",disabled:e,size:i,autoFocus:r,"aria-label":"Message"})}),f.jsx("button",{type:"button",className:oe(rt.sendButton,u?rt.sendButtonCompact:null),onClick:()=>void l(),disabled:!h,"aria-label":"Send message",children:f.jsx(IE,{size:d})})]})}function I3(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=zG,getSenderName:v,isAgentMessage:m,copyResetDelayMs:S=2e3,showAgentCopyButton:g=!0,inputPlaceholder:y,inputAutoFocus:x,...b}=t,k=T.useRef(null),[w,C]=T.useState(null),R=T.useRef(null),A=T.useCallback(Y=>v?v(Y):qG(Y,o),[v,o]),N=T.useCallback(Y=>m?m(Y,o):FG(Y,o),[m,o]),O=T.useMemo(()=>{const Y=r[r.length-1];return Y?Y.id??`${Y.timestamp}-${r.length-1}`:null},[r]);T.useEffect(()=>{var Y,P;(P=(Y=k.current)==null?void 0:Y.scrollIntoView)==null||P.call(Y,{behavior:"smooth"})},[O]),T.useEffect(()=>()=>{R.current&&(window.clearTimeout(R.current),R.current=null)},[]);const B=T.useCallback(Y=>{C(Y),R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{C(null),R.current=null},S)},[S]),X=T.useCallback(async(Y,P)=>{try{await HG(Y.message??""),B(P)}catch(V){console.warn("[ChatPanel] Failed to copy message",V)}},[B]),L=d==="compact"?"sm":"md";return f.jsxs(Wu,{...b,className:oe(rt.panel,i),role:"region","aria-label":n??e,"data-testid":h,children:[f.jsxs("div",{className:rt.header,children:[f.jsx(Si,{as:"h2",className:oe(rt.title,d==="compact"?rt.titleCompact:null),children:e}),l&&c?f.jsx("div",{className:rt.headerActions,children:f.jsx("button",{type:"button",className:rt.closeButton,onClick:l,"aria-label":`Close ${e}`,children:f.jsx(cp,{size:d==="compact"?18:20})})}):null]}),f.jsx("div",{className:rt.divider,"aria-hidden":"true"}),f.jsxs("div",{className:rt.body,children:[f.jsx("div",{className:rt.messagesArea,children:f.jsx(ql,{className:rt.scrollable,children:r.length===0?f.jsx(Si,{variant:"muted",className:rt.empty,"data-testid":"chat-panel-empty",children:u}):f.jsxs("div",{className:rt.messagesList,"data-testid":"chat-panel-list",children:[r.map((Y,P)=>{const V=Y.id??`${Y.timestamp}-${P}`,K=N(Y),ee=w===V;return f.jsxs("div",{className:oe(rt.messageItem,K?rt.agentMessage:null),"data-testid":`chat-panel-message-${V}`,children:[f.jsxs("div",{className:rt.messageMetadata,children:[f.jsx("span",{className:rt.senderName,children:A(Y)}),f.jsx("span",{className:rt.timestamp,children:p(Y.timestamp)})]}),f.jsx(Ep,{className:rt.messageBubble,padding:"md",radius:"panel",background:K?"surfaceMuted":"surface",children:f.jsx("div",{className:rt.messageText,children:Y.message})}),K&&g?f.jsx("div",{className:rt.agentActions,children:f.jsx("button",{type:"button",className:oe(rt.copyButton,ee?rt.copyButtonCopied:null),onClick:()=>void X(Y,V),"aria-label":ee?"Copied":"Copy agent message",title:ee?"Copied":"Copy agent message","data-testid":"copy-agent-message","data-copied":ee?"true":"false",children:f.jsx(DE,{size:18})})}):null]},V)}),f.jsx("div",{ref:k})]})})}),f.jsx("div",{className:rt.inputRow,children:f.jsx(VG,{onSend:s,disabled:a,placeholder:y,size:L,autoFocus:x})})]})]})}T.createContext("vertical");const GG="_container_1v6ko_1",WG="_video_1v6ko_7",YG="_chip_1v6ko_16",KG="_logo_1v6ko_34",Rp={container:GG,video:WG,chip:YG,logo:KG},XG="https://obi-static.s3.ap-southeast-2.amazonaws.com/videos/greeting.mp4";function $G(t){const{agentName:e="Obi",greetingVideoSrc:n,className:i,...r}=t,a=T.useRef(null),o=()=>{var s;try{(s=a.current)==null||s.pause()}catch{}};return f.jsxs("div",{className:oe(Rp.container,i),...r,children:[f.jsx("video",{ref:a,className:Rp.video,src:n??XG,autoPlay:!0,muted:!0,playsInline:!0,onEnded:o}),f.jsxs("div",{className:Rp.chip,children:[f.jsx(iB,{size:12,className:Rp.logo}),f.jsx("span",{children:e})]})]})}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const j3=50,Gl="?",B3=/\(error: (.*)\)/,U3=/captureMessage|captureException/;function JG(...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(`
134
- `);for(let s=i;s<o.length;s++){const l=o[s];if(l.length>1024)continue;const c=B3.test(l)?l.replace(B3,"$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>=j3+r)break}}return QG(a.slice(r))}}function QG(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(Ap(e).function||"")&&e.pop(),e.reverse(),U3.test(Ap(e).function||"")&&(e.pop(),U3.test(Ap(e).function||"")&&e.pop()),e.slice(0,j3).map(n=>({...n,filename:n.filename||Ap(e).filename,function:n.function||Gl}))}function Ap(t){return t[t.length-1]||{}}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const ZG=30,eW=50;function ry(t,e,n,i){const r={filename:t,function:e==="<anonymous>"?Gl:e,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const tW=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,nW=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,iW=/\((\S*)(?::(\d+))(?::(\d+))\)/,rW=t=>{const e=tW.exec(t);if(e){const[,i,r,a]=e;return ry(i,Gl,+r,+a)}const n=nW.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){const a=iW.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}const[i,r]=z3(n[1]||Gl,n[2]);return ry(r,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},aW=[ZG,rW],oW=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,sW=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;JG(...[aW,[eW,t=>{const e=oW.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=sW.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]||Gl;return[i,n]=z3(i,n),ry(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const z3=(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]:Gl,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const lW={sm:640,md:900,lg:1024,xl:1280};function cW(t){return`(max-width: ${lW[t]-1}px)`}const rr={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 ay(...t){return t.filter(Boolean).join(" ")}function uW(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:ay(rr.shell,p),"data-testid":"course-dialog-content",children:f.jsxs("div",{className:ay(rr.layout,u?rr.layoutThree:null),children:[f.jsxs("div",{className:rr.leftPanel,children:[f.jsxs("div",{className:rr.videoFrame,children:[d&&h&&f.jsx("div",{className:rr.returnToPiPOverlay,children:f.jsx("button",{type:"button",className:rr.returnToPiPButton,onClick:h,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(PE,{size:14})})}),f.jsx(wH,{className:rr.captions,text:e,children:f.jsx(C3,{audioPower:n,size:"lg",background:"flat",imageSrc:i,ariaLabel:r??"Agent avatar placeholder",status:a})})]}),f.jsx("div",{className:rr.controls,children:f.jsx(T3,{...o})})]}),u?f.jsx("div",{className:rr.rightPanel,"data-testid":"course-dialog-right-panel",children:u}):null,f.jsx("div",{className:rr.middlePanel,"data-testid":"course-dialog-middle-panel",children:c??f.jsx(L3,{...l,courses:s,className:ay(rr.coursePanel,l==null?void 0:l.className)})})]})})}function F3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(Pb,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(uW,{...r})})}const dW=80,hW=500,fW=1e3;function pW(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]=T.useState(""),[s,l]=T.useState(!1),c=T.useRef(""),u=T.useRef(null),d=T.useRef(null),h=T.useRef(null),p=m=>{h.current&&(clearTimeout(h.current),h.current=null),n>0?h.current=setTimeout(()=>{o(m)},n):o(m)},v=(m,S)=>m.startsWith(S)?m.slice(S.length).trim():m.trim();return T.useEffect(()=>{if(d.current&&(clearTimeout(d.current),d.current=null),s)return;const m=v(r,c.current);p(m),m.length>dW?(l(!0),u.current=setTimeout(()=>{l(!1),c.current=r},hW+n)):m.length>0&&(d.current=setTimeout(()=>{c.current=r,p("")},fW+n))},[r,s,n]),T.useEffect(()=>()=>{u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current)},[]),{caption:a,hasCaption:a.length>0}}const ws={shell:"_shell_1n2od_1",layout:"_layout_1n2od_11",mainPanel:"_mainPanel_1n2od_25",coursePanel:"_coursePanel_1n2od_39",controls:"_controls_1n2od_44",returnToPipSlot:"_returnToPipSlot_1n2od_49",returnToPipButton:"_returnToPipButton_1n2od_55"};function q3(...t){return t.filter(Boolean).join(" ")}function mW(t){const{controlBarProps:e,courses:n,coursePanelProps:i,mainPanel:r,onReturnToPiP:a,className:o}=t,s=a?f.jsx(Ro,{type:"button",size:"sm",variant:"tertiary",className:ws.returnToPipButton,onClick:a,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(PE,{size:14})}):null,l=s?f.jsxs("span",{className:ws.returnToPipSlot,children:[s,e.leadingControl]}):e.leadingControl,c={...e,browserSupportsScreenSharing:!1,microphoneButtonVariant:"simple",...s?{leadingControl:l}:{}};return f.jsx("div",{className:q3(ws.shell,o),"data-testid":"mobile-course-dialog-content",children:f.jsxs("div",{className:ws.layout,children:[f.jsx("div",{className:ws.mainPanel,"data-testid":"mobile-course-dialog-main-panel",children:r??f.jsx(L3,{...i,courses:n,className:q3(ws.coursePanel,i==null?void 0:i.className)})}),f.jsx("div",{className:ws.controls,children:f.jsx(T3,{...c})})]})})}function H3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(Pb,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(mW,{...r})})}const Tr={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 gW(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(Pb,{open:e,onClose:n,size:"large",showCloseButton:c,className:Tr.dialogWithSmallClose,children:f.jsxs("div",{className:Tr.layout,children:[f.jsxs("div",{className:Tr.left,children:[f.jsxs("div",{className:Tr.copy,children:[f.jsx(Si,{variant:"heading",children:r}),f.jsx(Si,{variant:"subheading",children:a}),f.jsx(Si,{variant:"muted",as:"div",className:Tr.description,children:f.jsx(ql,{className:Tr.descriptionScroller,children:f.jsx(dF,{content:o})})})]}),f.jsxs("div",{className:Tr.cta,children:[f.jsx(Ro,{type:"button",size:"lg",fullWidth:!0,onClick:i,isLoading:u,children:s}),f.jsx(Si,{variant:"subscript",as:"p",className:Tr.disclaimer,children:l})]})]}),f.jsx(w3,{showAboveWidth:"md",children:f.jsx("div",{className:Tr.right,children:f.jsx(Wu,{className:Tr.mediaPanel,children:f.jsx($G,{agentName:r,greetingVideoSrc:d,className:Tr.agentStill})})})})]})})}const vW={launcherPill:"_launcherPill_1fhyr_1"};function bW(t){const{label:e,onClick:n}=t;return f.jsx("button",{type:"button",className:vW.launcherPill,onClick:n,"data-testid":"ai-coach-pill",children:e})}const V3="__ama_course__",yW="ama_course",_W=3e4,G3=cW("md");function xW(t){var Xl,kn,Tn,Po,Lo,Xr,Io,Gt,jo,Bo,Uo,zo,$l,_,I,M,pe,Pe,be,Wt,kt,Tt,$r,Le,Fo,Jl,iR,rR,aR;const{sdk:e,shadowHost:n}=t,i=!!e.passivePlanUuid,r=i?((Xl=e.client)==null?void 0:Xl.selectedPlanUuid)??null:null,a=((kn=e.client)==null?void 0:kn.session)??null,o=!!a&&(i&&!!r||!!((Tn=e.client)!=null&&Tn.selectedPlanUuid)),[s,l]=T.useState(()=>a),[c,u]=T.useState(()=>a!=null&&a.sessionUuid?kW(a.sessionUuid):null),d=(()=>{var W;return a?((W=a.roomId)==null?void 0:W.startsWith("obs-"))&&!c?"course-selection":"pip":r?"start-session":"hidden"})(),[h,p]=T.useState(()=>d),v=T.useRef(d),[m,S]=T.useState(!1),[g,y]=T.useState(!1),[x,b]=T.useState(!1),[k,w]=T.useState([]),[C,R]=T.useState(null),[A,N]=T.useState(null),[O,B]=T.useState(0),[X,L]=T.useState(!1),[Y,P]=T.useState(!1),[V,K]=T.useState(0),[ee,$]=T.useState(null),[U,Z]=T.useState([]),[Q,le]=T.useState(!1),[j,ge]=T.useState(!1),[H,he]=T.useState(()=>o),ve=T.useRef(o),Ye=T.useRef(null),Lt=T.useRef(null),me=T.useRef(!1),Ne=EW(),_t=()=>{p(W=>{const ne=W==="course-selection",Se=W==="course-outline"&&me.current;return ne||Se?(me.current=!1,L(!1),"pip"):W})};T.useEffect(()=>{v.current=h},[h]),T.useEffect(()=>()=>{Ye.current&&clearTimeout(Ye.current)},[]);const dt=()=>{Ye.current&&(clearTimeout(Ye.current),Ye.current=null)},Ht=()=>{dt(),Lt.current=null,N(W=>W===null?W:null)},un=W=>{dt(),Lt.current=W,N(W),Ye.current=setTimeout(()=>{const ne=Lt.current===W,Se=v.current==="course-selection";ne&&Se&&(Lt.current=null,N(null)),Ye.current=null},_W)},Ot=TW((Lo=(Po=e.client)==null?void 0:Po.product)==null?void 0:Lo.widget_url_blacklist),dn=wW(s),{audioDevices:In}=CW();T.useEffect(()=>{s!=null&&s.sessionUuid&&W3(s.sessionUuid,c)},[c,s==null?void 0:s.sessionUuid]);const{caption:ri}=pW(U,{delayMs:0}),ai=typeof navigator<"u"&&!!((Xr=navigator.mediaDevices)!=null&&Xr.getDisplayMedia),ue=((Gt=(Io=s==null?void 0:s.room)==null?void 0:Io.localParticipant)==null?void 0:Gt.isScreenShareEnabled)??!1,Ke=W=>{var Ae;const ne=((Ae=e.client)==null?void 0:Ae.identity)??W.identity,Se=typeof(ne==null?void 0:ne.first_name)=="string"?ne.first_name.trim():"",Ze=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:Se,lastName:Ze,email:xe}},Ce=W=>{const{firstName:ne,lastName:Se,email:Ze}=Ke(W),xe=[ne,Se,Ze].map(ht=>ht.trim());return xe.some(ht=>ht.length>0)?xe.join(":"):""},tt=W=>{const{firstName:ne,lastName:Se,email:Ze}=Ke(W),xe=[ne,Se].filter(Boolean).join(" ").trim();return{name:xe.length>0?xe:void 0,email:Ze.length>0?Ze:void 0,screenShareSupported:ai}},st=(()=>{if(s!=null&&s.speakingState){if(s.speakingState==="thinking")return"thinking";if(s.speakingState==="busy")return"searching"}})(),Fn=((Bo=(jo=e.client)==null?void 0:jo.product)==null?void 0:Bo.avatar_image_url)||((zo=(Uo=e.client)==null?void 0:Uo.product)==null?void 0:zo.logo_url)||void 0,Li=((_=($l=e.client)==null?void 0:$l.product)==null?void 0:_.greeting_video_url)||void 0,Yr=SW({sdk:e,session:s,isBlacklisted:Ot}),q=!i&&Yr,re=!!(s??((I=e.client)==null?void 0:I.session)??null),de=(s==null?void 0:s.clientType)==="meet"?Ce(s):"",qe=(pe=(M=e.client)==null?void 0:M.product)==null?void 0:pe.assistant_subtitle,St=typeof qe=="string"&&qe.trim().length>0?qe:"Onboarding Assistant",hn=()=>B(W=>W+1),Ii=async()=>{var ne,Se;if(!s)return;const W=((Se=(ne=s.room)==null?void 0:ne.localParticipant)==null?void 0:Se.isScreenShareEnabled)??!1;try{W?await s.setScreenShareEnabled(!1):await s.shareScreen()}catch(Ze){console.error("[obi-sdk] failed to toggle screen share",Ze)}finally{hn()}},wr=T.useRef(null),Vt=T.useRef(null),qn=T.useRef(!1),xn=T.useRef({session:null,sessionUuid:null,started:!1}),jn=T.useRef(null),Oo=T.useRef(new WeakMap),Wl=(W,ne)=>{if(!ne)return;let Se=Oo.current.get(W);Se||(Se=new Set,Oo.current.set(W,Se)),Se.add(ne)},Te=W=>{if(!W||wr.current===W)return;Vt.current&&(Vt.current(),Vt.current=null);const ne=()=>hn(),Se=Ie=>{u(Ie),Ht(),W!=null&&W.sessionUuid&&W3(W.sessionUuid,Ie),p(fe=>fe==="pip"||fe==="course-outline"?fe:fe==="course-selection"?(me.current=!0,"course-outline"):fe)},Ze=Ie=>{Ht(),w(Ie.courses),p("course-selection"),me.current=!1,u(null),W!=null&&W.sessionUuid&&Y3(W.sessionUuid),R(null),P(!1)},xe=(Ie,fe)=>{},Ae=Ie=>{Ie.isAgent},ht=Ie=>{$(Ie),K(Date.now())},It=Ie=>{if(!Ie){$(null);return}$(Ie),K(Date.now())};W.on("stateChanged",ne),W.on("speakingStateChanged",ne),W.on("paused",ne),W.on("unpaused",ne),W.on("chatMessagesChanged",ne),W.on("chatMessageReceived",Ae),W.on("courseProgress",Se),W.on("courseSelection",Ze),W.on("transcript",xe),W.on("screenCaptured",ht),W.on("screenCaptureNotification",It),W.on("captions",Z),W.on("introductionComplete",_t),wr.current=W,Vt.current=()=>{W.off("stateChanged",ne),W.off("speakingStateChanged",ne),W.off("paused",ne),W.off("unpaused",ne),W.off("chatMessagesChanged",ne),W.off("chatMessageReceived",Ae),W.off("courseProgress",Se),W.off("courseSelection",Ze),W.off("transcript",xe),W.off("screenCaptured",ht),W.off("screenCaptureNotification",It),W.off("captions",Z),W.off("introductionComplete",_t)}},Sn=W=>{var Se;return W?((Se=W.roomId)==null?void 0:Se.startsWith("obs-"))&&!c?"course-selection":"pip":"hidden"};T.useEffect(()=>{const W=()=>{jn.current&&(jn.current(),jn.current=null)},ne=xe=>{if(xe.clientType!=="meet")return;if(xn.current.session&&xn.current.session===xe||!!xn.current.sessionUuid&&!!xe.sessionUuid&&xn.current.sessionUuid===xe.sessionUuid){if(xn.current.started||jn.current)return}else xn.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!1},W();const ht=async()=>{xn.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!0};const fe=Ce(xe);fe&&Wl(xe,fe);try{await xe.sendHumanJoined(tt(xe))}catch(Xe){console.error("[obi-sdk] failed to send human_joined handshake",Xe)}},It=(fe,Xe)=>{fe==="connecting"||fe==="error"||(W(),ht())},Ie=xe.state;if(Ie&&Ie!=="connecting"&&Ie!=="error"){ht();return}xe.on("stateChanged",It),jn.current=()=>{xe.off("stateChanged",It)}},Se=xe=>{var Ae,ht,It,Ie;if(xe)if((Ae=e.client)!=null&&Ae.session)p(Sn(((It=e.client)==null?void 0:It.session)??null));else{const Xe=!!e.passivePlanUuid,fn=Xe&&!!((ht=e.client)!=null&&ht.selectedPlanUuid);if(Xe&&!fn)return;p("start-session")}else(Ie=e.client)!=null&&Ie.session||p("hidden")},Ze=()=>hn();if(e.on("showMenu",Se),e.on("configUpdated",Ze),e.client){e.client.session&&(l(e.client.session),Te(e.client.session),p(Sn(e.client.session))),e.client.on("sessionStarted",Ae=>{l(Ae),Te(Ae),qn.current=!1,S(!1),y(!1),b(!1),P(!1);const ht=ve.current;ve.current=!1,ht?(me.current=!0,p("course-outline")):(me.current=!1,p(Sn(Ae))),la().track("session-started",{planId:Ae.planId}),ne(Ae)}),e.client.on("sessionResumed",Ae=>{l(Ae),Te(Ae),qn.current=!1,S(!1),y(!1),b(!1),P(!1),me.current=!1,p(Sn(Ae)),ne(Ae)});const xe=()=>{var It;const Ae=(It=e.client)==null?void 0:It.session;Ae!=null&&Ae.sessionUuid&&Y3(Ae.sessionUuid);const ht=wr.current;Vt.current&&(Vt.current(),Vt.current=null),l(null),wr.current=null,S(!1),y(!1),b(!1),P(!1),he(!1),ve.current=!1,Ht(),me.current=!1,W(),xn.current={session:null,sessionUuid:null,started:!1},ht&&Oo.current.delete(ht),qn.current||p("hidden")};e.client.on("sessionStopped",xe),e.client.on("sessionShutdown",xe),e.client.on("stateChanged",hn)}return()=>{e.off("showMenu",Se),e.off("configUpdated",Ze),Vt.current&&Vt.current(),W()}},[e]),T.useEffect(()=>{const W=s;if(!W||W.clientType!=="meet")return;const ne=W.state;if(!ne||ne==="connecting"||ne==="error"||!de)return;const Se=Oo.current.get(W);Se!=null&&Se.has(de)||(Wl(W,de),W.sendHumanJoined(tt(W)).catch(Ze=>console.error("[obi-sdk] failed to send human_joined update",Ze)))},[ai,de,s,s==null?void 0:s.state]),T.useLayoutEffect(()=>{var W,ne;(ne=(W=e.client)==null?void 0:W.product)!=null&&ne.primary_color&&n.style.setProperty("--obi-color-primary",e.client.product.primary_color)},[(be=(Pe=e.client)==null?void 0:Pe.product)==null?void 0:be.primary_color,n]),T.useEffect(()=>{if(i&&!Ot&&!re){if(!r){p("hidden");return}p("start-session")}},[re,i,Ot,r]),T.useEffect(()=>{var It,Ie;ge(!1);const W=(It=e.client)==null?void 0:It.api,ne=(Ie=e.client)==null?void 0:Ie.product;if(!W||!ne)return;const Se=(ne==null?void 0:ne.uuid)??(ne==null?void 0:ne.product_uuid),Ze=(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(Se?Ae.product_uuid=Se:Ze?Ae.product_slug=Ze:xe!=null&&(Ae.product_id=String(xe)),Object.keys(Ae).length===0)return;let ht=!1;return W.getFeatureFlags(Ae).then(fe=>{if(ht)return;const fn=((fe==null?void 0:fe.data)??[]).find(sy=>(sy==null?void 0:sy.slug)===yW);if(!fn)return;const{user_enabled:oi,product_enabled:ki,global_enabled:ji}=fn;let si=!!ji;ki!=null&&(si=!!ki),oi!=null&&(si=!!oi),ge(si)}).catch(fe=>{console.error("[obi-sdk] failed to load AMA feature flag",fe)}),()=>{ht=!0}},[(Wt=e.client)==null?void 0:Wt.api,(kt=e.client)==null?void 0:kt.product]);const Yl=(c==null?void 0:c.stepNames.map((W,ne)=>({id:`step-${ne+1}`,title:W})))??[],Kr=((c==null?void 0:c.totalSteps)??0)>0&&((c==null?void 0:c.stepNames.length)??0)>0?(c==null?void 0:c.currentStep)??null:null,Mo=!0,Do=(W,ne)=>{s==null||s.say(`Can we jump to the section about ${ne.title}?`)};if(Ot||i&&!r&&!re)return null;if(h==="hidden")return q?f.jsx(bW,{label:St,onClick:()=>{e.updateShowMenu(!0)}}):null;if(h==="start-session"){const W=(Tt=e.client)==null?void 0:Tt.product,ne=($r=e.client)==null?void 0:$r.selectedPlan,Se=i&&!!r,Ze=i&&!!r||!!((Le=e.client)!=null&&Le.selectedPlanUuid),xe=(W==null?void 0:W.agent_name)||"Obi",Ae=(W==null?void 0:W.assistant_subtitle)||"AI Assistant",ht=Se&&(ne==null?void 0:ne.description)||(W==null?void 0:W.assistant_description)||"";return f.jsx(gW,{open:!0,onClose:()=>{S(!1),p("hidden")},onStart:()=>{ve.current=Ze,he(Ze),S(!0),e.startSession({withMicrophone:!0})},agentName:xe,agentSubtitle:Ae,description:ht,showCloseButton:!1,startLabel:"Start Session",isStarting:m,greetingVideoSrc:Li})}if(h==="course-selection"){const W=(Fo=s==null?void 0:s.roomId)==null?void 0:Fo.startsWith("obs-"),ne=((Jl=e.client)==null?void 0:Jl.plans)||[],Se=W&&k.length>0,Ze=Se?k.slice().sort((fe,Xe)=>fe.order!==void 0&&Xe.order!==void 0?fe.order-Xe.order:fe.order!==void 0?-1:Xe.order!==void 0?1:fe.name.localeCompare(Xe.name)).map(fe=>({id:fe.uuid,title:fe.name,description:fe.description||fe.overview||"",status:fe.completed?"completed":"available",duration:typeof fe.duration=="number"?`${fe.duration} min`:fe.duration})):ne.map(fe=>{var Xe,fn;return{id:fe.uuid,title:fe.name,description:fe.description,status:(fn=(Xe=e.client)==null?void 0:Xe.planIsCompleted)!=null&&fn[ne.indexOf(fe)]?"completed":"available",duration:fe.estimated_duration?`${fe.estimated_duration} min`:void 0}});Se&&j&&Ze.push({id:V3,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,ht={audioDevices:In,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ue,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:ai,onMicDeviceSelect:async fe=>{e.client&&(e.client.preferredMicrophoneDeviceId=fe),s&&fe&&await s.switchMicrophoneDevice(fe),hn()},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:()=>{b(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Ii,languages:xe,selectedLanguage:Ae,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:fe=>{s==null||s.setLanguage(fe)},isLanguageSelectorEnabled:!0,...x?{screenShareButtonVariant:"compact"}:{}},It=x?f.jsx(I3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((iR=s==null?void 0:s.room)==null?void 0:iR.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async fe=>{var Xe,fn,oi,ki;if(s){const ji=Date.now();s.appendChatMessage({timestamp:ji,message:fe,from:{identity:((fn=(Xe=s.room)==null?void 0:Xe.localParticipant)==null?void 0:fn.identity)??null,name:((ki=(oi=s.room)==null?void 0:oi.localParticipant)==null?void 0:ki.name)??null},isAgent:!1}),await s.say(fe)}},onClose:()=>b(!1)}):void 0,Ie={selectedCourseIds:C?[C]:void 0,loadingCourseId:A,onCourseToggle:async fe=>{var Xe,fn,oi,ki;if(!Lt.current)if(Se){if(fe===V3){un(fe),R(fe);try{await((Xe=s==null?void 0:s.say)==null?void 0:Xe.call(s,"Please start an AMA session."))}catch(si){console.error("[obi-sdk] failed to start AMA course",si),Ht(),R(null)}return}const ji=k.find(si=>si.uuid===fe);if(ji){un(fe),R(fe);try{await((fn=s==null?void 0:s.say)==null?void 0:fn.call(s,`I'd like to take the ${ji.name} course.`))}catch(si){console.error("[obi-sdk] failed to send course selection",si),Ht(),R(null)}}}else{const ji=ne.find(si=>si.uuid===fe);if(ji){un(fe),(oi=e.client)==null||oi.selectPlan(ji),p("pip");try{await((ki=s==null?void 0:s.say)==null?void 0:ki.call(s,`I'd like to take the ${ji.name} course.`))}catch(si){console.error("[obi-sdk] failed to send course selection",si),p("course-selection"),Ht()}}}}};return Ne?f.jsx(H3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:Ze,controlBarProps:ht,coursePanelProps:Ie,mainPanel:It}):f.jsx(F3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:Ze,controlBarProps:ht,coursePanelProps:Ie,rightPanel:It,avatarImageSrc:Fn,avatarAudioPower:dn,avatarStatus:st,captionsText:ri})}if(h==="course-outline"){const W=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Se={audioDevices:In,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ue,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:ai,onMicDeviceSelect:async Ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=Ie),s&&Ie&&await s.switchMicrophoneDevice(Ie),hn()},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:()=>{b(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Ii,languages:W,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"}:{}},Ze=x?f.jsx(I3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((rR=s==null?void 0:s.room)==null?void 0:rR.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async Ie=>{var fe,Xe,fn,oi;if(s){const ki=Date.now();s.appendChatMessage({timestamp:ki,message:Ie,from:{identity:((Xe=(fe=s.room)==null?void 0:fe.localParticipant)==null?void 0:Xe.identity)??null,name:((oi=(fn=s.room)==null?void 0:fn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(Ie)}},onClose:()=>b(!1)}):void 0,xe=!!c,Ae=!H,ht=async()=>{if(!(!(s!=null&&s.endCourse)||Y)){P(!0);try{await s.endCourse("back_to_courses")}catch(Ie){console.error("[obi-sdk] failed to end course",Ie),P(!1)}}},It=f.jsx(zV,{steps:Yl,currentStep:Kr,hideTrailingConclusionStep:Mo,onStepClick:Do,showBackToCourses:Ae,...Ae?{onBackToCoursesConfirm:ht,backToCoursesDisabled:Y}:{}});return Ne?f.jsx(H3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:Se,mainPanel:Ze??It,onReturnToPiP:xe?()=>p("pip"):void 0}):f.jsx(F3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:Se,middlePanel:It,rightPanel:Ze,isCourseOutlineOpen:xe,onReturnToPiP:xe?()=>p("pip"):void 0,avatarImageSrc:Fn,avatarAudioPower:dn,avatarStatus:st,captionsText:ri})}if(h==="pip"){const W=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Se=()=>{s==null||s.stop()},Ze=()=>{if(me.current=!1,c){p("course-outline");return}p("course-selection")},xe={isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isChatOpen:x,isScreenShareActive:ue,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:()=>b(Xe=>!Xe),onScreenShareToggle:Ii,onLeave:Se,languages:W,selectedLanguage:ne,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:Xe=>{s==null||s.setLanguage(Xe)},isLanguageSelectorEnabled:!0};if(Ne)return f.jsx(gq,{isMicrophoneEnabled:xe.isMicrophoneEnabled,onMicToggle:xe.onMicToggle,onLeave:Se,onReturnToCourseOutline:Ze});const Ae=280,ht=250,It=16,Ie={x:window.innerWidth-Ae-It,y:window.innerHeight-ht-It},fe=x?f.jsx(lG,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((aR=s==null?void 0:s.room)==null?void 0:aR.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async Xe=>{var fn,oi,ki,ji;if(s){const si=Date.now();s.appendChatMessage({timestamp:si,message:Xe,from:{identity:((oi=(fn=s.room)==null?void 0:fn.localParticipant)==null?void 0:oi.identity)??null,name:((ji=(ki=s.room)==null?void 0:ki.localParticipant)==null?void 0:ji.name)??null},isAgent:!1}),await s.say(Xe)}},testId:"pip-chat-panel"}):void 0;return f.jsx(_H,{initialPosition:Ie,onExit:Ze,controlBarProps:xe,isCourseOutlineSelected:X&&!!c,onCourseOutlineToggle:c?()=>{L(Xe=>!Xe)}:void 0,isCaptionsEnabled:Q,onCaptionsToggle:()=>le(Xe=>!Xe),courseOutline:c?{steps:Yl,currentStep:Kr,onStepClick:Do,hideTrailingConclusionStep:Mo}:void 0,messagesPanel:fe,avatarFallbackProps:{audioPower:dn,imageSrc:Fn,status:st,captionsText:ri},screenshotUrl:ee,cameraShotTrigger:V})}return null}function SW(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 W3(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 kW(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 Y3(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 TW(t){const[e,n]=T.useState(()=>xs(t));return T.useEffect(()=>{n(xs(t))},[t]),T.useEffect(()=>{const i=()=>{n(xs(t))};return window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[t]),e}function wW(t){const[e,n]=T.useState(0),i=T.useRef(null),r=T.useRef(0),a=T.useRef(0);return T.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 v=0;for(let m=0;m<s.length;m++)v+=s[m];l=Math.min(1,Math.max(0,v/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 CW(){const[t,e]=T.useState({audioDevices:[]});return T.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 EW(){const t=()=>typeof window>"u"||!("matchMedia"in window)?!1:window.matchMedia(G3).matches,[e,n]=T.useState(()=>t());return T.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;const i=window.matchMedia(G3),r=a=>{n(a.matches)};return n(i.matches),i.addEventListener("change",r),()=>i.removeEventListener("change",r)},[]),e}function K3(){const t=window.location.hostname;return t.endsWith(".getcor.ai")||t.endsWith(".getcor.io")||t.endsWith(".clinic1.com")||t.endsWith(".onuptick.com")||t==="app.canibuild.com"||t==="getcor.ai"||t==="getcor.io"||t==="localhost"||t==="127.0.0.1"||t==="::1"}const X3=K3();function RW(t){if(document.querySelector("#obi-host")||document.querySelector("obi-widget"))return;AW();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(H7);const a=[r];if(X3){const s=new CSSStyleSheet;s.replaceSync(z7),a.push(s);const l=new CSSStyleSheet;l.replaceSync(q7),a.push(l)}else{const s=new CSSStyleSheet;s.replaceSync(F7),a.push(s)}n.adoptedStyleSheets=a;const o=U7.createRoot(i);X3?o.render(f.jsx(xW,{sdk:t,shadowHost:e})):o.render(f.jsx(W7,{sdk:t,shadowHost:e})),console.log("[obi-sdk] widget mounted")}function AW(){$3("https://fonts.cdnfonts.com/css/satoshi"),$3("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function $3(t){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}const J3="49206C6F7665204F6269_session",Q3="obi-url-params",oy="obi-client-heartbeat",NW=5e3,Z3=4e4,eR=15e3;function OW(){return K3()?"meet":"sdk"}function MW(){if(typeof window>"u")return!1;const t=navigator.userAgent||"",n=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(t.toLowerCase()),i=typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches;return n||i}class DW extends Dp{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=OW(),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=Rh.deserialise(r,e,i,{apiBaseUrl:"https://app.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 Rh(e,i,{apiBaseUrl:"https://app.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,v,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=(v=this.client)==null?void 0:v.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&&xs(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{la().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&&la().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){const n=MW()?"mobile":"desktop";await this.client.startSession(this.client.selectedPlanUuid||null,i=>{i.on("stateChanged",r=>{r!=="disconnecting"&&r!=="disconnected"&&r!=="error"&&r!=="connecting"&&this.save()}),i.on("paused",()=>{this.save()}),i.on("unpaused",()=>{this.save()})},{...e,environment:n})}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(Q3)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((a,o)=>{e[o]=a});const n=e[J3];if(!n)return null;const i=new URL(window.location.href);i.searchParams.delete(J3),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Q3),this.passivePlanUuid=n}mountWidget(){RW(this)}showMessage(e,n){try{this.emit("showMessage",{text:e,autoCloseMs:n==null?void 0:n.autoCloseMs})}catch{}}async captureScreen(){try{await MO(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await CR(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 uO(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>Z3,reason:s>Z3?"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>eR,reason:o>eR?"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(oy);if(!e)return null;try{return JSON.parse(e)}catch{return null}}trackStaleSessionDiscard(e,n,i){try{la().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)},NW)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}writeHeartbeat(e){const n={sessionUuid:e,updatedAtMs:Date.now()};localStorage.setItem(oy,JSON.stringify(n))}clearHeartbeat(){this.stopHeartbeat(),localStorage.removeItem(oy)}clearCachedClient(){this.clearHeartbeat(),localStorage.removeItem("obi-client")}}async function tR(t,e){let n;try{n=window}catch{console.warn("[obi] no window object found"),n={}}return PW({appToken:t,window:n,init:e})}async function PW({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 DW(t);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function nR(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{tR(void 0,nR)}):tR(void 0,nR)})();
134
+ `);for(let s=i;s<o.length;s++){const l=o[s];if(l.length>1024)continue;const c=B3.test(l)?l.replace(B3,"$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>=j3+r)break}}return QG(a.slice(r))}}function QG(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(Ap(e).function||"")&&e.pop(),e.reverse(),U3.test(Ap(e).function||"")&&(e.pop(),U3.test(Ap(e).function||"")&&e.pop()),e.slice(0,j3).map(n=>({...n,filename:n.filename||Ap(e).filename,function:n.function||Gl}))}function Ap(t){return t[t.length-1]||{}}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const ZG=30,eW=50;function ry(t,e,n,i){const r={filename:t,function:e==="<anonymous>"?Gl:e,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const tW=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,nW=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,iW=/\((\S*)(?::(\d+))(?::(\d+))\)/,rW=t=>{const e=tW.exec(t);if(e){const[,i,r,a]=e;return ry(i,Gl,+r,+a)}const n=nW.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){const a=iW.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}const[i,r]=z3(n[1]||Gl,n[2]);return ry(r,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},aW=[ZG,rW],oW=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,sW=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;JG(...[aW,[eW,t=>{const e=oW.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=sW.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]||Gl;return[i,n]=z3(i,n),ry(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const z3=(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]:Gl,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const lW={sm:640,md:900,lg:1024,xl:1280};function cW(t){return`(max-width: ${lW[t]-1}px)`}const rr={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 ay(...t){return t.filter(Boolean).join(" ")}function uW(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:ay(rr.shell,p),"data-testid":"course-dialog-content",children:f.jsxs("div",{className:ay(rr.layout,u?rr.layoutThree:null),children:[f.jsxs("div",{className:rr.leftPanel,children:[f.jsxs("div",{className:rr.videoFrame,children:[d&&h&&f.jsx("div",{className:rr.returnToPiPOverlay,children:f.jsx("button",{type:"button",className:rr.returnToPiPButton,onClick:h,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(PE,{size:14})})}),f.jsx(wH,{className:rr.captions,text:e,children:f.jsx(C3,{audioPower:n,size:"lg",background:"flat",imageSrc:i,ariaLabel:r??"Agent avatar placeholder",status:a})})]}),f.jsx("div",{className:rr.controls,children:f.jsx(T3,{...o})})]}),u?f.jsx("div",{className:rr.rightPanel,"data-testid":"course-dialog-right-panel",children:u}):null,f.jsx("div",{className:rr.middlePanel,"data-testid":"course-dialog-middle-panel",children:c??f.jsx(L3,{...l,courses:s,className:ay(rr.coursePanel,l==null?void 0:l.className)})})]})})}function F3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(Pb,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(uW,{...r})})}const dW=80,hW=500,fW=1e3;function pW(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]=T.useState(""),[s,l]=T.useState(!1),c=T.useRef(""),u=T.useRef(null),d=T.useRef(null),h=T.useRef(null),p=m=>{h.current&&(clearTimeout(h.current),h.current=null),n>0?h.current=setTimeout(()=>{o(m)},n):o(m)},v=(m,S)=>m.startsWith(S)?m.slice(S.length).trim():m.trim();return T.useEffect(()=>{if(d.current&&(clearTimeout(d.current),d.current=null),s)return;const m=v(r,c.current);p(m),m.length>dW?(l(!0),u.current=setTimeout(()=>{l(!1),c.current=r},hW+n)):m.length>0&&(d.current=setTimeout(()=>{c.current=r,p("")},fW+n))},[r,s,n]),T.useEffect(()=>()=>{u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current)},[]),{caption:a,hasCaption:a.length>0}}const ws={shell:"_shell_1n2od_1",layout:"_layout_1n2od_11",mainPanel:"_mainPanel_1n2od_25",coursePanel:"_coursePanel_1n2od_39",controls:"_controls_1n2od_44",returnToPipSlot:"_returnToPipSlot_1n2od_49",returnToPipButton:"_returnToPipButton_1n2od_55"};function q3(...t){return t.filter(Boolean).join(" ")}function mW(t){const{controlBarProps:e,courses:n,coursePanelProps:i,mainPanel:r,onReturnToPiP:a,className:o}=t,s=a?f.jsx(Ro,{type:"button",size:"sm",variant:"tertiary",className:ws.returnToPipButton,onClick:a,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(PE,{size:14})}):null,l=s?f.jsxs("span",{className:ws.returnToPipSlot,children:[s,e.leadingControl]}):e.leadingControl,c={...e,browserSupportsScreenSharing:!1,microphoneButtonVariant:"simple",...s?{leadingControl:l}:{}};return f.jsx("div",{className:q3(ws.shell,o),"data-testid":"mobile-course-dialog-content",children:f.jsxs("div",{className:ws.layout,children:[f.jsx("div",{className:ws.mainPanel,"data-testid":"mobile-course-dialog-main-panel",children:r??f.jsx(L3,{...i,courses:n,className:q3(ws.coursePanel,i==null?void 0:i.className)})}),f.jsx("div",{className:ws.controls,children:f.jsx(T3,{...c})})]})})}function H3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(Pb,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(mW,{...r})})}const Tr={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 gW(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(Pb,{open:e,onClose:n,size:"large",showCloseButton:c,className:Tr.dialogWithSmallClose,children:f.jsxs("div",{className:Tr.layout,children:[f.jsxs("div",{className:Tr.left,children:[f.jsxs("div",{className:Tr.copy,children:[f.jsx(Si,{variant:"heading",children:r}),f.jsx(Si,{variant:"subheading",children:a}),f.jsx(Si,{variant:"muted",as:"div",className:Tr.description,children:f.jsx(ql,{className:Tr.descriptionScroller,children:f.jsx(dF,{content:o})})})]}),f.jsxs("div",{className:Tr.cta,children:[f.jsx(Ro,{type:"button",size:"lg",fullWidth:!0,onClick:i,isLoading:u,children:s}),f.jsx(Si,{variant:"subscript",as:"p",className:Tr.disclaimer,children:l})]})]}),f.jsx(w3,{showAboveWidth:"md",children:f.jsx("div",{className:Tr.right,children:f.jsx(Wu,{className:Tr.mediaPanel,children:f.jsx($G,{agentName:r,greetingVideoSrc:d,className:Tr.agentStill})})})})]})})}const vW={launcherPill:"_launcherPill_1fhyr_1"};function bW(t){const{label:e,onClick:n}=t;return f.jsx("button",{type:"button",className:vW.launcherPill,onClick:n,"data-testid":"ai-coach-pill",children:e})}const V3="__ama_course__",yW="ama_course",_W=3e4,G3=cW("md");function xW(t){var Xl,kn,Tn,Po,Lo,Xr,Io,Gt,jo,Bo,Uo,zo,$l,_,I,M,pe,Pe,be,Wt,kt,Tt,$r,Le,Fo,Jl,iR,rR,aR;const{sdk:e,shadowHost:n}=t,i=!!e.passivePlanUuid,r=i?((Xl=e.client)==null?void 0:Xl.selectedPlanUuid)??null:null,a=((kn=e.client)==null?void 0:kn.session)??null,o=!!a&&(i&&!!r||!!((Tn=e.client)!=null&&Tn.selectedPlanUuid)),[s,l]=T.useState(()=>a),[c,u]=T.useState(()=>a!=null&&a.sessionUuid?kW(a.sessionUuid):null),d=(()=>{var W;return a?((W=a.roomId)==null?void 0:W.startsWith("obs-"))&&!c?"course-selection":"pip":r?"start-session":"hidden"})(),[h,p]=T.useState(()=>d),v=T.useRef(d),[m,S]=T.useState(!1),[g,y]=T.useState(!1),[x,b]=T.useState(!1),[k,w]=T.useState([]),[C,R]=T.useState(null),[A,N]=T.useState(null),[O,B]=T.useState(0),[X,L]=T.useState(!1),[Y,P]=T.useState(!1),[V,K]=T.useState(0),[ee,$]=T.useState(null),[U,Z]=T.useState([]),[Q,le]=T.useState(!1),[j,ge]=T.useState(!1),[H,he]=T.useState(()=>o),ve=T.useRef(o),Ye=T.useRef(null),Lt=T.useRef(null),me=T.useRef(!1),Ne=EW(),_t=()=>{p(W=>{const ne=W==="course-selection",Se=W==="course-outline"&&me.current;return ne||Se?(me.current=!1,L(!1),"pip"):W})};T.useEffect(()=>{v.current=h},[h]),T.useEffect(()=>()=>{Ye.current&&clearTimeout(Ye.current)},[]);const dt=()=>{Ye.current&&(clearTimeout(Ye.current),Ye.current=null)},Ht=()=>{dt(),Lt.current=null,N(W=>W===null?W:null)},un=W=>{dt(),Lt.current=W,N(W),Ye.current=setTimeout(()=>{const ne=Lt.current===W,Se=v.current==="course-selection";ne&&Se&&(Lt.current=null,N(null)),Ye.current=null},_W)},Ot=TW((Lo=(Po=e.client)==null?void 0:Po.product)==null?void 0:Lo.widget_url_blacklist),dn=wW(s),{audioDevices:In}=CW();T.useEffect(()=>{s!=null&&s.sessionUuid&&W3(s.sessionUuid,c)},[c,s==null?void 0:s.sessionUuid]);const{caption:ri}=pW(U,{delayMs:0}),ai=typeof navigator<"u"&&!!((Xr=navigator.mediaDevices)!=null&&Xr.getDisplayMedia),ue=((Gt=(Io=s==null?void 0:s.room)==null?void 0:Io.localParticipant)==null?void 0:Gt.isScreenShareEnabled)??!1,Ke=W=>{var Ae;const ne=((Ae=e.client)==null?void 0:Ae.identity)??W.identity,Se=typeof(ne==null?void 0:ne.first_name)=="string"?ne.first_name.trim():"",Ze=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:Se,lastName:Ze,email:xe}},Ce=W=>{const{firstName:ne,lastName:Se,email:Ze}=Ke(W),xe=[ne,Se,Ze].map(ht=>ht.trim());return xe.some(ht=>ht.length>0)?xe.join(":"):""},tt=W=>{const{firstName:ne,lastName:Se,email:Ze}=Ke(W),xe=[ne,Se].filter(Boolean).join(" ").trim();return{name:xe.length>0?xe:void 0,email:Ze.length>0?Ze:void 0,screenShareSupported:ai}},st=(()=>{if(s!=null&&s.speakingState){if(s.speakingState==="thinking")return"thinking";if(s.speakingState==="busy")return"searching"}})(),Fn=((Bo=(jo=e.client)==null?void 0:jo.product)==null?void 0:Bo.avatar_image_url)||((zo=(Uo=e.client)==null?void 0:Uo.product)==null?void 0:zo.logo_url)||void 0,Li=((_=($l=e.client)==null?void 0:$l.product)==null?void 0:_.greeting_video_url)||void 0,Yr=SW({sdk:e,session:s,isBlacklisted:Ot}),q=!i&&Yr,re=!!(s??((I=e.client)==null?void 0:I.session)??null),de=(s==null?void 0:s.clientType)==="meet"?Ce(s):"",qe=(pe=(M=e.client)==null?void 0:M.product)==null?void 0:pe.assistant_subtitle,St=typeof qe=="string"&&qe.trim().length>0?qe:"Onboarding Assistant",hn=()=>B(W=>W+1),Ii=async()=>{var ne,Se;if(!s)return;const W=((Se=(ne=s.room)==null?void 0:ne.localParticipant)==null?void 0:Se.isScreenShareEnabled)??!1;try{W?await s.setScreenShareEnabled(!1):await s.shareScreen()}catch(Ze){console.error("[obi-sdk] failed to toggle screen share",Ze)}finally{hn()}},wr=T.useRef(null),Vt=T.useRef(null),qn=T.useRef(!1),xn=T.useRef({session:null,sessionUuid:null,started:!1}),jn=T.useRef(null),Oo=T.useRef(new WeakMap),Wl=(W,ne)=>{if(!ne)return;let Se=Oo.current.get(W);Se||(Se=new Set,Oo.current.set(W,Se)),Se.add(ne)},Te=W=>{if(!W||wr.current===W)return;Vt.current&&(Vt.current(),Vt.current=null);const ne=()=>hn(),Se=Ie=>{u(Ie),Ht(),W!=null&&W.sessionUuid&&W3(W.sessionUuid,Ie),p(fe=>fe==="pip"||fe==="course-outline"?fe:fe==="course-selection"?(me.current=!0,"course-outline"):fe)},Ze=Ie=>{Ht(),w(Ie.courses),p("course-selection"),me.current=!1,u(null),W!=null&&W.sessionUuid&&Y3(W.sessionUuid),R(null),P(!1)},xe=(Ie,fe)=>{},Ae=Ie=>{Ie.isAgent},ht=Ie=>{$(Ie),K(Date.now())},It=Ie=>{if(!Ie){$(null);return}$(Ie),K(Date.now())};W.on("stateChanged",ne),W.on("speakingStateChanged",ne),W.on("paused",ne),W.on("unpaused",ne),W.on("chatMessagesChanged",ne),W.on("chatMessageReceived",Ae),W.on("courseProgress",Se),W.on("courseSelection",Ze),W.on("transcript",xe),W.on("screenCaptured",ht),W.on("screenCaptureNotification",It),W.on("captions",Z),W.on("introductionComplete",_t),wr.current=W,Vt.current=()=>{W.off("stateChanged",ne),W.off("speakingStateChanged",ne),W.off("paused",ne),W.off("unpaused",ne),W.off("chatMessagesChanged",ne),W.off("chatMessageReceived",Ae),W.off("courseProgress",Se),W.off("courseSelection",Ze),W.off("transcript",xe),W.off("screenCaptured",ht),W.off("screenCaptureNotification",It),W.off("captions",Z),W.off("introductionComplete",_t)}},Sn=W=>{var Se;return W?((Se=W.roomId)==null?void 0:Se.startsWith("obs-"))&&!c?"course-selection":"pip":"hidden"};T.useEffect(()=>{const W=()=>{jn.current&&(jn.current(),jn.current=null)},ne=xe=>{if(xe.clientType!=="meet")return;if(xn.current.session&&xn.current.session===xe||!!xn.current.sessionUuid&&!!xe.sessionUuid&&xn.current.sessionUuid===xe.sessionUuid){if(xn.current.started||jn.current)return}else xn.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!1},W();const ht=async()=>{xn.current={session:xe,sessionUuid:xe.sessionUuid??null,started:!0};const fe=Ce(xe);fe&&Wl(xe,fe);try{await xe.sendHumanJoined(tt(xe))}catch(Xe){console.error("[obi-sdk] failed to send human_joined handshake",Xe)}},It=(fe,Xe)=>{fe==="connecting"||fe==="error"||(W(),ht())},Ie=xe.state;if(Ie&&Ie!=="connecting"&&Ie!=="error"){ht();return}xe.on("stateChanged",It),jn.current=()=>{xe.off("stateChanged",It)}},Se=xe=>{var Ae,ht,It,Ie;if(xe)if((Ae=e.client)!=null&&Ae.session)p(Sn(((It=e.client)==null?void 0:It.session)??null));else{const Xe=!!e.passivePlanUuid,fn=Xe&&!!((ht=e.client)!=null&&ht.selectedPlanUuid);if(Xe&&!fn)return;p("start-session")}else(Ie=e.client)!=null&&Ie.session||p("hidden")},Ze=()=>hn();if(e.on("showMenu",Se),e.on("configUpdated",Ze),e.client){e.client.session&&(l(e.client.session),Te(e.client.session),p(Sn(e.client.session))),e.client.on("sessionStarted",Ae=>{l(Ae),Te(Ae),qn.current=!1,S(!1),y(!1),b(!1),P(!1);const ht=ve.current;ve.current=!1,ht?(me.current=!0,p("course-outline")):(me.current=!1,p(Sn(Ae))),la().track("session-started",{planId:Ae.planId}),ne(Ae)}),e.client.on("sessionResumed",Ae=>{l(Ae),Te(Ae),qn.current=!1,S(!1),y(!1),b(!1),P(!1),me.current=!1,p(Sn(Ae)),ne(Ae)});const xe=()=>{var It;const Ae=(It=e.client)==null?void 0:It.session;Ae!=null&&Ae.sessionUuid&&Y3(Ae.sessionUuid);const ht=wr.current;Vt.current&&(Vt.current(),Vt.current=null),l(null),wr.current=null,S(!1),y(!1),b(!1),P(!1),he(!1),ve.current=!1,Ht(),me.current=!1,W(),xn.current={session:null,sessionUuid:null,started:!1},ht&&Oo.current.delete(ht),qn.current||p("hidden")};e.client.on("sessionStopped",xe),e.client.on("sessionShutdown",xe),e.client.on("stateChanged",hn)}return()=>{e.off("showMenu",Se),e.off("configUpdated",Ze),Vt.current&&Vt.current(),W()}},[e]),T.useEffect(()=>{const W=s;if(!W||W.clientType!=="meet")return;const ne=W.state;if(!ne||ne==="connecting"||ne==="error"||!de)return;const Se=Oo.current.get(W);Se!=null&&Se.has(de)||(Wl(W,de),W.sendHumanJoined(tt(W)).catch(Ze=>console.error("[obi-sdk] failed to send human_joined update",Ze)))},[ai,de,s,s==null?void 0:s.state]),T.useLayoutEffect(()=>{var W,ne;(ne=(W=e.client)==null?void 0:W.product)!=null&&ne.primary_color&&n.style.setProperty("--obi-color-primary",e.client.product.primary_color)},[(be=(Pe=e.client)==null?void 0:Pe.product)==null?void 0:be.primary_color,n]),T.useEffect(()=>{if(i&&!Ot&&!re){if(!r){p("hidden");return}p("start-session")}},[re,i,Ot,r]),T.useEffect(()=>{var It,Ie;ge(!1);const W=(It=e.client)==null?void 0:It.api,ne=(Ie=e.client)==null?void 0:Ie.product;if(!W||!ne)return;const Se=(ne==null?void 0:ne.uuid)??(ne==null?void 0:ne.product_uuid),Ze=(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(Se?Ae.product_uuid=Se:Ze?Ae.product_slug=Ze:xe!=null&&(Ae.product_id=String(xe)),Object.keys(Ae).length===0)return;let ht=!1;return W.getFeatureFlags(Ae).then(fe=>{if(ht)return;const fn=((fe==null?void 0:fe.data)??[]).find(sy=>(sy==null?void 0:sy.slug)===yW);if(!fn)return;const{user_enabled:oi,product_enabled:ki,global_enabled:ji}=fn;let si=!!ji;ki!=null&&(si=!!ki),oi!=null&&(si=!!oi),ge(si)}).catch(fe=>{console.error("[obi-sdk] failed to load AMA feature flag",fe)}),()=>{ht=!0}},[(Wt=e.client)==null?void 0:Wt.api,(kt=e.client)==null?void 0:kt.product]);const Yl=(c==null?void 0:c.stepNames.map((W,ne)=>({id:`step-${ne+1}`,title:W})))??[],Kr=((c==null?void 0:c.totalSteps)??0)>0&&((c==null?void 0:c.stepNames.length)??0)>0?(c==null?void 0:c.currentStep)??null:null,Mo=!0,Do=(W,ne)=>{s==null||s.say(`Can we jump to the section about ${ne.title}?`)};if(Ot||i&&!r&&!re)return null;if(h==="hidden")return q?f.jsx(bW,{label:St,onClick:()=>{e.updateShowMenu(!0)}}):null;if(h==="start-session"){const W=(Tt=e.client)==null?void 0:Tt.product,ne=($r=e.client)==null?void 0:$r.selectedPlan,Se=i&&!!r,Ze=i&&!!r||!!((Le=e.client)!=null&&Le.selectedPlanUuid),xe=(W==null?void 0:W.agent_name)||"Obi",Ae=(W==null?void 0:W.assistant_subtitle)||"AI Assistant",ht=Se&&(ne==null?void 0:ne.description)||(W==null?void 0:W.assistant_description)||"";return f.jsx(gW,{open:!0,onClose:()=>{S(!1),p("hidden")},onStart:()=>{ve.current=Ze,he(Ze),S(!0),e.startSession({withMicrophone:!0})},agentName:xe,agentSubtitle:Ae,description:ht,showCloseButton:!1,startLabel:"Start Session",isStarting:m,greetingVideoSrc:Li})}if(h==="course-selection"){const W=(Fo=s==null?void 0:s.roomId)==null?void 0:Fo.startsWith("obs-"),ne=((Jl=e.client)==null?void 0:Jl.plans)||[],Se=W&&k.length>0,Ze=Se?k.slice().sort((fe,Xe)=>fe.order!==void 0&&Xe.order!==void 0?fe.order-Xe.order:fe.order!==void 0?-1:Xe.order!==void 0?1:fe.name.localeCompare(Xe.name)).map(fe=>({id:fe.uuid,title:fe.name,description:fe.description||fe.overview||"",status:fe.completed?"completed":"available",duration:typeof fe.duration=="number"?`${fe.duration} min`:fe.duration})):ne.map(fe=>{var Xe,fn;return{id:fe.uuid,title:fe.name,description:fe.description,status:(fn=(Xe=e.client)==null?void 0:Xe.planIsCompleted)!=null&&fn[ne.indexOf(fe)]?"completed":"available",duration:fe.estimated_duration?`${fe.estimated_duration} min`:void 0}});Se&&j&&Ze.push({id:V3,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,ht={audioDevices:In,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ue,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:ai,onMicDeviceSelect:async fe=>{e.client&&(e.client.preferredMicrophoneDeviceId=fe),s&&fe&&await s.switchMicrophoneDevice(fe),hn()},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:()=>{b(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Ii,languages:xe,selectedLanguage:Ae,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:fe=>{s==null||s.setLanguage(fe)},isLanguageSelectorEnabled:!0,...x?{screenShareButtonVariant:"compact"}:{}},It=x?f.jsx(I3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((iR=s==null?void 0:s.room)==null?void 0:iR.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async fe=>{var Xe,fn,oi,ki;if(s){const ji=Date.now();s.appendChatMessage({timestamp:ji,message:fe,from:{identity:((fn=(Xe=s.room)==null?void 0:Xe.localParticipant)==null?void 0:fn.identity)??null,name:((ki=(oi=s.room)==null?void 0:oi.localParticipant)==null?void 0:ki.name)??null},isAgent:!1}),await s.say(fe)}},onClose:()=>b(!1)}):void 0,Ie={selectedCourseIds:C?[C]:void 0,loadingCourseId:A,onCourseToggle:async fe=>{var Xe,fn,oi,ki;if(!Lt.current)if(Se){if(fe===V3){un(fe),R(fe);try{await((Xe=s==null?void 0:s.say)==null?void 0:Xe.call(s,"Please start an AMA session."))}catch(si){console.error("[obi-sdk] failed to start AMA course",si),Ht(),R(null)}return}const ji=k.find(si=>si.uuid===fe);if(ji){un(fe),R(fe);try{await((fn=s==null?void 0:s.say)==null?void 0:fn.call(s,`I'd like to take the ${ji.name} course.`))}catch(si){console.error("[obi-sdk] failed to send course selection",si),Ht(),R(null)}}}else{const ji=ne.find(si=>si.uuid===fe);if(ji){un(fe),(oi=e.client)==null||oi.selectPlan(ji),p("pip");try{await((ki=s==null?void 0:s.say)==null?void 0:ki.call(s,`I'd like to take the ${ji.name} course.`))}catch(si){console.error("[obi-sdk] failed to send course selection",si),p("course-selection"),Ht()}}}}};return Ne?f.jsx(H3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:Ze,controlBarProps:ht,coursePanelProps:Ie,mainPanel:It}):f.jsx(F3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:Ze,controlBarProps:ht,coursePanelProps:Ie,rightPanel:It,avatarImageSrc:Fn,avatarAudioPower:dn,avatarStatus:st,captionsText:ri})}if(h==="course-outline"){const W=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Se={audioDevices:In,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ue,widgetState:x?"chat":null,canPublishData:!0,browserSupportsScreenSharing:ai,onMicDeviceSelect:async Ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=Ie),s&&Ie&&await s.switchMicrophoneDevice(Ie),hn()},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:()=>{b(!x)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Ii,languages:W,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"}:{}},Ze=x?f.jsx(I3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((rR=s==null?void 0:s.room)==null?void 0:rR.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async Ie=>{var fe,Xe,fn,oi;if(s){const ki=Date.now();s.appendChatMessage({timestamp:ki,message:Ie,from:{identity:((Xe=(fe=s.room)==null?void 0:fe.localParticipant)==null?void 0:Xe.identity)??null,name:((oi=(fn=s.room)==null?void 0:fn.localParticipant)==null?void 0:oi.name)??null},isAgent:!1}),await s.say(Ie)}},onClose:()=>b(!1)}):void 0,xe=!!c,Ae=!H,ht=async()=>{if(!(!(s!=null&&s.endCourse)||Y)){P(!0);try{await s.endCourse("back_to_courses")}catch(Ie){console.error("[obi-sdk] failed to end course",Ie),P(!1)}}},It=f.jsx(zV,{steps:Yl,currentStep:Kr,hideTrailingConclusionStep:Mo,onStepClick:Do,showBackToCourses:Ae,...Ae?{onBackToCoursesConfirm:ht,backToCoursesDisabled:Y}:{}});return Ne?f.jsx(H3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:Se,mainPanel:Ze??It,onReturnToPiP:xe?()=>p("pip"):void 0}):f.jsx(F3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:Se,middlePanel:It,rightPanel:Ze,isCourseOutlineOpen:xe,onReturnToPiP:xe?()=>p("pip"):void 0,avatarImageSrc:Fn,avatarAudioPower:dn,avatarStatus:st,captionsText:ri})}if(h==="pip"){const W=(s==null?void 0:s.languageCodes)||[],ne=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Se=()=>{s==null||s.stop()},Ze=()=>{if(me.current=!1,c){p("course-outline");return}p("course-selection")},xe={isMicrophoneEnabled:!g&&((s==null?void 0:s.isMicShared)??!1),isChatOpen:x,isScreenShareActive:ue,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:()=>b(Xe=>!Xe),onScreenShareToggle:Ii,onLeave:Se,languages:W,selectedLanguage:ne,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:Xe=>{s==null||s.setLanguage(Xe)},isLanguageSelectorEnabled:!0};if(Ne)return f.jsx(gq,{isMicrophoneEnabled:xe.isMicrophoneEnabled,onMicToggle:xe.onMicToggle,onLeave:Se,onReturnToCourseOutline:Ze});const Ae=280,ht=250,It=16,Ie={x:window.innerWidth-Ae-It,y:window.innerHeight-ht-It},fe=x?f.jsx(lG,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((aR=s==null?void 0:s.room)==null?void 0:aR.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async Xe=>{var fn,oi,ki,ji;if(s){const si=Date.now();s.appendChatMessage({timestamp:si,message:Xe,from:{identity:((oi=(fn=s.room)==null?void 0:fn.localParticipant)==null?void 0:oi.identity)??null,name:((ji=(ki=s.room)==null?void 0:ki.localParticipant)==null?void 0:ji.name)??null},isAgent:!1}),await s.say(Xe)}},testId:"pip-chat-panel"}):void 0;return f.jsx(_H,{initialPosition:Ie,onExit:Ze,controlBarProps:xe,isCourseOutlineSelected:X&&!!c,onCourseOutlineToggle:c?()=>{L(Xe=>!Xe)}:void 0,isCaptionsEnabled:Q,onCaptionsToggle:()=>le(Xe=>!Xe),courseOutline:c?{steps:Yl,currentStep:Kr,onStepClick:Do,hideTrailingConclusionStep:Mo}:void 0,messagesPanel:fe,avatarFallbackProps:{audioPower:dn,imageSrc:Fn,status:st,captionsText:ri},screenshotUrl:ee,cameraShotTrigger:V})}return null}function SW(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 W3(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 kW(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 Y3(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 TW(t){const[e,n]=T.useState(()=>xs(t));return T.useEffect(()=>{n(xs(t))},[t]),T.useEffect(()=>{const i=()=>{n(xs(t))};return window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[t]),e}function wW(t){const[e,n]=T.useState(0),i=T.useRef(null),r=T.useRef(0),a=T.useRef(0);return T.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 v=0;for(let m=0;m<s.length;m++)v+=s[m];l=Math.min(1,Math.max(0,v/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 CW(){const[t,e]=T.useState({audioDevices:[]});return T.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 EW(){const t=()=>typeof window>"u"||!("matchMedia"in window)?!1:window.matchMedia(G3).matches,[e,n]=T.useState(()=>t());return T.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;const i=window.matchMedia(G3),r=a=>{n(a.matches)};return n(i.matches),i.addEventListener("change",r),()=>i.removeEventListener("change",r)},[]),e}function K3(){const t=window.location.hostname;return t.endsWith(".getcor.ai")||t.endsWith(".getcor.io")||t.endsWith(".clinic1.com")||t.endsWith(".onuptick.com")||t.endsWith(".gorgias.com")||t==="app.canibuild.com"||t==="getcor.ai"||t==="getcor.io"||t==="localhost"||t==="127.0.0.1"||t==="::1"}const X3=K3();function RW(t){if(document.querySelector("#obi-host")||document.querySelector("obi-widget"))return;AW();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(H7);const a=[r];if(X3){const s=new CSSStyleSheet;s.replaceSync(z7),a.push(s);const l=new CSSStyleSheet;l.replaceSync(q7),a.push(l)}else{const s=new CSSStyleSheet;s.replaceSync(F7),a.push(s)}n.adoptedStyleSheets=a;const o=U7.createRoot(i);X3?o.render(f.jsx(xW,{sdk:t,shadowHost:e})):o.render(f.jsx(W7,{sdk:t,shadowHost:e})),console.log("[obi-sdk] widget mounted")}function AW(){$3("https://fonts.cdnfonts.com/css/satoshi"),$3("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function $3(t){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}const J3="49206C6F7665204F6269_session",Q3="obi-url-params",oy="obi-client-heartbeat",NW=5e3,Z3=4e4,eR=15e3;function OW(){return K3()?"meet":"sdk"}function MW(){if(typeof window>"u")return!1;const t=navigator.userAgent||"",n=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(t.toLowerCase()),i=typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches;return n||i}class DW extends Dp{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=OW(),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=Rh.deserialise(r,e,i,{apiBaseUrl:"https://app.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 Rh(e,i,{apiBaseUrl:"https://app.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,v,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=(v=this.client)==null?void 0:v.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&&xs(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{la().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&&la().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){const n=MW()?"mobile":"desktop";await this.client.startSession(this.client.selectedPlanUuid||null,i=>{i.on("stateChanged",r=>{r!=="disconnecting"&&r!=="disconnected"&&r!=="error"&&r!=="connecting"&&this.save()}),i.on("paused",()=>{this.save()}),i.on("unpaused",()=>{this.save()})},{...e,environment:n})}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(Q3)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((a,o)=>{e[o]=a});const n=e[J3];if(!n)return null;const i=new URL(window.location.href);i.searchParams.delete(J3),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Q3),this.passivePlanUuid=n}mountWidget(){RW(this)}showMessage(e,n){try{this.emit("showMessage",{text:e,autoCloseMs:n==null?void 0:n.autoCloseMs})}catch{}}async captureScreen(){try{await MO(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await CR(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 uO(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>Z3,reason:s>Z3?"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>eR,reason:o>eR?"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(oy);if(!e)return null;try{return JSON.parse(e)}catch{return null}}trackStaleSessionDiscard(e,n,i){try{la().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)},NW)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}writeHeartbeat(e){const n={sessionUuid:e,updatedAtMs:Date.now()};localStorage.setItem(oy,JSON.stringify(n))}clearHeartbeat(){this.stopHeartbeat(),localStorage.removeItem(oy)}clearCachedClient(){this.clearHeartbeat(),localStorage.removeItem("obi-client")}}async function tR(t,e){let n;try{n=window}catch{console.warn("[obi] no window object found"),n={}}return PW({appToken:t,window:n,init:e})}async function PW({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 DW(t);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function nR(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{tR(void 0,nR)}):tR(void 0,nR)})();