@sanseng/livekit-ws-sdk 0.1.8 → 0.1.10

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.
@@ -144,4 +144,4 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
144
144
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
145
145
  `);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function _i(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ki(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Tl=Object.freeze({__proto__:null,removeExtmapAllowMixed:pn,shimAddIceCandidateNullOrEmpty:_i,shimConnectionState:hn,shimMaxMessageSize:yi,shimParameterlessSetLocalDescription:ki,shimRTCIceCandidate:bi,shimRTCIceCandidateRelayProtocol:un,shimSendThrowTypeError:Ti});function _l(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Fr,i=gl(n),s={browserDetails:i,commonShim:Tl,extractVersion:Vt,disableLog:ml,disableWarnings:fl,sdp:yl};switch(i.browser){case"chrome":if(!Yr||!cn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Yr,_i(n,i),ki(n),Wr(n,i),Kr(n),cn(n,i),Gr(n),$r(n,i),Hr(n),zr(n),Qr(n,i),bi(n),un(n),hn(n),yi(n,i),Ti(n),pn(n,i);break;case"firefox":if(!co||!dn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=co,_i(n,i),ki(n),Xr(n,i),dn(n,i),Zr(n),io(n),eo(n),to(n),no(n),so(n),ro(n),oo(n),ao(n),bi(n),hn(n),yi(n,i),Ti(n);break;case"safari":if(!yo||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=yo,_i(n,i),ki(n),fo(n),vo(n),ho(n),lo(n),uo(n),go(n),po(n),bo(n),bi(n),un(n),yi(n,i),Ti(n),pn(n,i);break;default:t("Unsupported browser!");break}return s}_l({window:typeof window>"u"?void 0:window});var mn,ko;class ue extends(ko=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}mn=ue,ue.resolve=n=>Reflect.get(ko,"resolve",mn).call(mn,n);const kl=/version\/(\d+(\.?_?\d+)+)/i;let fn;function be(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(fn===void 0||e){const i=Sl.find(s=>{let{test:r}=s;return r.test(t)});fn=i?.describe(t)}return fn}const Sl=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Si(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:gn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Si(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:gn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Si(kl,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:gn(n)}}}];function Si(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function gn(n){return n.includes("mac os")?Si(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Cl="2.17.1";const El=Cl,Rl=16;class $e extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof i?.cause<"u"&&(this.cause=i?.cause)}}class vn extends $e{}var Q;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(Q||(Q={}));class F extends vn{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=Q[t]}static notAllowed(e,t,i){return new F(e,Q.NotAllowed,t,i)}static timeout(e){return new F(e,Q.Timeout)}static leaveRequest(e,t){return new F(e,Q.LeaveRequest,void 0,t)}static internal(e,t){return new F(e,Q.InternalError,void 0,t)}static cancelled(e){return new F(e,Q.Cancelled)}static serverUnreachable(e,t){return new F(e,Q.ServerUnreachable,t)}static websocket(e,t,i){return new F(e,Q.WebSocket,t,i)}static serviceNotFound(e,t){return new F(e,Q.ServiceNotFound,void 0,t)}}class bn extends $e{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class qe extends $e{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class wl extends $e{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class re extends $e{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class yt extends $e{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class So extends $e{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Co extends vn{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:sn[t]}}var me;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(me||(me={}));class Se extends vn{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=me[t]}}class Tt extends $e{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Ci;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Ci||(Ci={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(Ci||(Ci={}));class de{}de.setTimeout=function(){return setTimeout(...arguments)},de.setInterval=function(){return setInterval(...arguments)},de.clearTimeout=function(){return clearTimeout(...arguments)},de.clearInterval=function(){return clearInterval(...arguments)};var E;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(E||(E={}));var I;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(I||(I={}));var P;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(P||(P={}));var w;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(w||(w={}));function Pl(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class ${constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};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 Il=["vp8","h264"],Dl=["vp8","h264","vp9","av1","h265"];function Al(n){return!!Il.find(e=>e===n)}const Ol=Al;var Eo;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Eo||(Eo={}));var yn;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(yn||(yn={}));const jt={h90:new $(160,90,9e4,20),h180:new $(320,180,16e4,20),h216:new $(384,216,18e4,20),h360:new $(640,360,45e4,20),h540:new $(960,540,8e5,25),h720:new $(1280,720,17e5,30),h1080:new $(1920,1080,3e6,30),h1440:new $(2560,1440,5e6,30),h2160:new $(3840,2160,8e6,30)},Tn={h120:new $(160,120,7e4,20),h180:new $(240,180,125e3,20),h240:new $(320,240,14e4,20),h360:new $(480,360,33e4,20),h480:new $(640,480,5e5,20),h540:new $(720,540,6e5,25),h720:new $(960,720,13e5,30),h1080:new $(1440,1080,23e5,30),h1440:new $(1920,1440,38e5,30)},_n={h360fps3:new $(640,360,2e5,3,"medium"),h360fps15:new $(640,360,4e5,15,"medium"),h720fps5:new $(1280,720,8e5,5,"medium"),h720fps15:new $(1280,720,15e5,15,"medium"),h720fps30:new $(1280,720,2e6,30,"medium"),h1080fps15:new $(1920,1080,25e5,15,"medium"),h1080fps30:new $(1920,1080,5e6,30,"medium"),original:new $(0,0,7e6,30,"medium")};function Ro(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Io(n??{}),l=e?.processor,u=t?.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(kn(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(kn(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function kn(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Sn(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{d==="resolution"?kn(o,c.resolution):o[d]=c[d]}),r.video=a,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function wo(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Po();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield le(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1})()})}function Po(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>p(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function Nl(n){return n==="audioinput"?S.Source.Microphone:n==="videoinput"?S.Source.Camera:S.Source.Unknown}function Cn(n){return n===S.Source.Microphone?"audioinput":n===S.Source.Camera?"videoinput":void 0}function xl(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,dt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function qt(n){return n.split("/")[1].toLowerCase()}function Ml(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Xi({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function W(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?W(n.track):{})}}function Ll(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Ul(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Io(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:Pl(e)}}function Fl(n){switch(n){case oe.CAMERA:return S.Source.Camera;case oe.MICROPHONE:return S.Source.Microphone;case oe.SCREEN_SHARE:return S.Source.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return S.Source.ScreenShareAudio;default:return S.Source.Unknown}}function Do(n,e){return n.width*n.height<e.width*e.height}function Bl(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const Vl=5e3,Wt=[];var Te;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Te||(Te={}));class S extends xe.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=S.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=V,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Vl):this.handleAppVisibilityChanged()},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=S.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),W(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===S.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===S.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Wt.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Wt.splice(Wt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),_t(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?w.AudioPlaybackStarted:w.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?w.AudioPlaybackFailed:w.VideoPlaybackFailed,r):r.name==="AbortError"?V.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):V.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(w.ElementAttached,e),e}detach(e){try{if(e){kt(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(w.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{kt(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(w.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ve(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Wt.forEach(i=>{i.parentElement||(t=!1)}),t&&Wt.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===S.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){ye()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ye()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function _t(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!dt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(dt()||ct())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function kt(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Re.AUDIO;case e.Video:return Re.VIDEO;default:return Re.DATA}}n.kindToProto=s;function r(d){switch(d){case Re.AUDIO:return e.Audio;case Re.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return oe.CAMERA;case t.Microphone:return oe.MICROPHONE;case t.ScreenShare:return oe.SCREEN_SHARE;case t.ScreenShareAudio:return oe.SCREEN_SHARE_AUDIO;default:return oe.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case oe.CAMERA:return t.Camera;case oe.MICROPHONE:return t.Microphone;case oe.SCREEN_SHARE:return t.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case Qi.ACTIVE:return i.Active;case Qi.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(S||(S={}));const jl="|",Ao="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ql(n){const e=n.split(jl);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function le(n){return new ue(e=>de.setTimeout(e,n))}function En(){return"addTransceiver"in RTCPeerConnection.prototype}function Rn(){return"addTrack"in RTCPeerConnection.prototype}function Wl(){if(!("getCapabilities"in RTCRtpSender)||dt()||ct())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function Kl(){if(!("getCapabilities"in RTCRtpSender)||ct())return!1;if(dt()){const t=be();if(t?.version&&Le(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&Le(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ie(n){return n==="av1"||n==="vp9"}function wn(n){return!document||Kt()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function Gl(){return typeof RTCPeerConnection>"u"?!1:En()||Rn()}function ct(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Firefox"}function Oo(){const n=be();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function dt(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Safari"}function Kt(){const n=be();return n?.name==="Safari"||n?.os==="iOS"}function Hl(){const n=be();return n?.name==="Safari"&&n.version.startsWith("17.")||n?.os==="iOS"&&!!n?.osVersion&&Le(n.osVersion,"17")>=0}function zl(n){return n||(n=be()),n?.name==="Safari"&&Le(n.version,"18.3")>0||n?.os==="iOS"&&!!n?.osVersion&&Le(n.osVersion,"18.3")>0}function No(){var n,e;return ye()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Jl(){const n=be(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Le(n.osVersion,e)>=0?!0:n.name==="Safari"&&Le(n.version,e)>=0}function ye(){return typeof document<"u"}function Me(){return navigator.product=="ReactNative"}function St(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Pn(n){return St(n)?n.hostname.split(".")[0]:null}function xo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Mo(){if(!Me())return;let n=xo();if(n)return n.platform}function Lo(){if(ye())return window.devicePixelRatio;if(Me()){let n=xo();if(n)return n.devicePixelRatio}return 1}function Le(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function $l(n){for(const e of n)e.target.handleResize(e)}function Ql(n){for(const e of n)e.target.handleVisibilityChanged(e)}let In=null;const Uo=()=>(In||(In=new ResizeObserver($l)),In);let Dn=null;const Fo=()=>(Dn||(Dn=new IntersectionObserver(Ql,{root:null,rootMargin:"0px"})),Dn);function Yl(){var n;const e=new hr({sdk:pr.JS,protocol:Rl,version:El});return Me()&&(e.os=(n=Mo())!==null&&n!==void 0?n:""),e}function Bo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r?.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Gt;function An(){if(!Gt){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[Gt]=i.stream.getAudioTracks(),!Gt)throw Error("Could not get empty media stream audio track");Gt.enabled=!1}return Gt.clone()}class Ce{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function Xl(n){return Dl.includes(n)}function Qe(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function Zl(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Ht(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function eu(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function tu(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function Vo(n){switch(n.reason){case Q.LeaveRequest:return n.context;case Q.Cancelled:return ke.CLIENT_INITIATED;case Q.NotAllowed:return ke.USER_REJECTED;case Q.ServerUnreachable:return ke.JOIN_FAILURE;default:return ke.UNKNOWN_REASON}}function Ei(n){return n!==void 0?Number(n):void 0}function lt(n){return n!==void 0?BigInt(n):void 0}function Ct(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Ue(n){return!!n&&n.kind==S.Kind.Audio}function Ye(n){return!!n&&n.kind==S.Kind.Video}function Xe(n){return Ct(n)&&Ye(n)}function We(n){return Ct(n)&&Ue(n)}function On(n){return!!n&&!n.isLocal}function iu(n){return!!n&&!n.isLocal}function Nn(n){return On(n)&&Ye(n)}function nu(n){return n.isLocal}function su(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function ru(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function ou(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=au(n,e);return t?i:xn(i,"v1")}function au(n,e){const t=new URL(Zl(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),xn(t,"rtc")}function cu(n){const e=new URL(Ht(n));return xn(e,"validate")}function jo(n){return n.endsWith("/")?n:"".concat(n,"/")}function xn(n,e){return n.pathname="".concat(jo(n.pathname)).concat(e),n}function qo(n){if(typeof n=="string")return yr.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return yr.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function du(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const lu=10,zt="lk_e2ee",uu={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:lu,keyringSize:16};var Ze;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Ze||(Ze={}));var Wo;(function(n){n.KeyRatcheted="keyRatcheted"})(Wo||(Wo={}));var et;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(et||(et={}));var Ko;(function(n){n.Error="cryptorError"})(Ko||(Ko={}));function hu(){return pu()||Mn()}function Mn(){return typeof window.RTCRtpScriptTransform<"u"}function pu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function mu(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new rr({value:n.value})}class op extends xe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,s)=>{V.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},uu),e),this.on(Ze.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(Ze.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Ze.RatchetRequest,e,t)}}var Go;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Go||(Go={}));class fu extends xe.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:a,data:o}=i.data;switch(a){case"error":if(V.error(o.error.message),o.uuid){const l=this.decryptDataRequests.get(o.uuid);if(l?.reject){l.reject(o.error);break}const u=this.encryptDataRequests.get(o.uuid);if(u?.reject){u.reject(o.error);break}}this.emit(et.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(et.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(et.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(Ze.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(o.uuid);c?.resolve&&c.resolve(o);break;case"encryptDataResponse":const d=this.encryptDataRequests.get(o.uuid);d?.resolve&&d.resolve(o);break}},this.onWorkerError=i=>{V.error("e2ee worker encountered an error:",{error:i.error}),this.emit(et.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!hu())throw new bn("tried to setup end-to-end encryption on an unsupported browser");if(V.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:dl.getLevel()}};this.worker&&(V.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){V.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?V.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(E.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==se.NONE,s.identity)),e.on(E.ConnectionStateChanged,i=>{i===J.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==se.NONE,s.identity)})})}).on(E.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(E.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(E.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(i,s)=>p(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(I.LocalTrackPublished,i=>{if(!Ye(i.track)||!Kt())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:qt(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Ze.SetKey,i=>this.postKey(i)).on(Ze.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Ce;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},o=new Ce;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?qt(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Ct(e)||!t){t||V.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(Mn()&&!Oo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(zt in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:zt in e}};this.worker.postMessage(o,[a,r])}e[zt]=!0}})}handleSender(e,t,i){var s;if(!(zt in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Mn()&&!Oo()){V.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{V.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[r.readable,r.writable])}e[zt]=!0}}}const gu=500,vu=15e3;class Et{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Et),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=Pn(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,le(Math.min(gu*Math.pow(2,r),vu)))}getBackOffPromise(e){const t=new URL(e),i=t&&Pn(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Pn(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Et._instance=null;const Ln="default";class ce{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ce),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=ce.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){V.debug("awaiting getUserMedia promise");try{t?yield ce.userMediaPromiseMap.get(t):yield Promise.all(ce.userMediaPromiseMap.values())}catch{V.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(dt()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==Ln)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Ln);if(!r){V.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Ln&&o.groupId===(i??r.groupId));if(!a){V.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?ce.userMediaPromiseMap.has(e):ce.userMediaPromiseMap.size>0}}ce.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ce.userMediaPromiseMap=new Map;var Jt;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Jt||(Jt={}));class bu{constructor(){this.pendingTasks=new Map,this.taskMutex=new he,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Jt.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Jt.RUNNING,yield e()}finally{t.status=Jt.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yu{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let{closeCode:o,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(o,c)};this.opened=new ue((o,c)=>{const d=()=>{c(F.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{o({readable:new ReadableStream({start(l){r.onmessage=u=>{let{data:h}=u;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),this.closed=new ue((o,c)=>{const d=()=>p(this,void 0,void 0,function*(){const l=new ue(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield ue.race([le(250),l]);u?o(u):c(F.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let{code:u,reason:h}=l;o({closeCode:u,reason:h}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const Tu=["syncState","trickle","offer","answer","simulate","leave"];function _u(n){const e=Tu.indexOf(n.case)>=0;return V.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Y;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Y||(Y={}));const ku=250;class Un{get currentState(){return this.state}get isDisconnected(){return this.state===Y.DISCONNECTING||this.state===Y.DISCONNECTED}get isEstablishingConnection(){return this.state===Y.CONNECTING||this.state===Y.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Y.DISCONNECTED,this.log=V,this._requestId=0,this.useV0SignalPath=!1,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=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new bu,this.queuedRequests=[],this.closingLock=new he,this.connectionLock=new he,this.state=Y.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return d.state=Y.CONNECTING,d.options=o,yield d.connect(r,a,o,c,l)})()})}reconnect(e,t,i,s){return p(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=Y.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield d.connectionLock.lock();d.connectOptions=o,d.useV0SignalPath=l;const h=Yl(),f=l?Su(a,h,o):Cu(a,h,o),b=ou(r,f,l).toString(),v=cu(b).toString();return new Promise((R,_)=>p(d,void 0,void 0,function*(){var A,x;try{let y=!1;const T=O=>p(this,void 0,void 0,function*(){if(y)return;y=!0;const L=O instanceof Event?O.currentTarget:O,q=du(L,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(q)).catch(Z=>{this.log.error(Z),this.close()}):this.close(),C(),_(F.cancelled(q))});c?.addEventListener("abort",T);const C=()=>{clearTimeout(N),c?.removeEventListener("abort",T)},N=setTimeout(()=>{T(F.timeout("room connection has timed out (signal)"))},o.websocketTimeout),U=(O,L)=>{this.handleSignalConnected(O,N,L)},M=new URL(b);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:o.reconnect,reconnectReason:o.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yu(b);try{this.ws.closed.then(ge=>{var st;this.isEstablishingConnection&&_(F.internal("Websocket got closed during a (re)connection attempt: ".concat(ge.reason))),ge.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:ge.reason,code:ge.closeCode,wasClean:ge.closeCode===1e3,state:this.state})),this.state===Y.CONNECTED&&this.handleOnClose((st=ge.reason)!==null&&st!==void 0?st:"Unexpected WS error"))}).catch(ge=>{this.isEstablishingConnection&&_(F.internal("Websocket error during a (re)connection attempt: ".concat(ge)))});const O=yield this.ws.opened.catch(ge=>p(this,void 0,void 0,function*(){if(this.state!==Y.CONNECTED){this.state=Y.DISCONNECTED,clearTimeout(N);const st=yield this.handleConnectionError(ge,v);_(st);return}this.handleWSError(ge),_(ge)}));if(clearTimeout(N),!O)return;const L=O.readable.getReader();this.streamWriter=O.writable.getWriter();const q=yield L.read();if(L.releaseLock(),!q.value)throw F.internal("no message received as first message");const Z=qo(q.value),_e=this.validateFirstMessage(Z,(A=o.reconnect)!==null&&A!==void 0?A:!1);if(!_e.isValid){_(_e.error);return}((x=Z.message)===null||x===void 0?void 0:x.case)==="join"&&(this.pingTimeoutDuration=Z.message.value.pingTimeout,this.pingIntervalDuration=Z.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 ut=_e.shouldProcessFirstMessage?Z:void 0;U(O,ut),R(_e.response)}catch(O){_(O)}finally{C()}}finally{u()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield le(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=qo(s);this.handleSignalResponse(r)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=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([Y.DISCONNECTING||Y.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Y.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,le(ku)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=Y.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Rt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Rt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ui({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new hi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new en({requestId:o,metadata:i,name:s,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Er({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Pr({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:X.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ar({timestamp:X.parse(Date.now()),rtt:X.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Zi({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new mi({reason:ke.CLIENT_INITIATED,action:vt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!_u(t)&&i.state===Y.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield le(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t?.case),i.logContext);return}const a=new Id({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=Ho(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=Ho(s.value);this.onOffer&&this.onOffer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===Y.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=de.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&&de.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=de.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&de.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Y.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Y.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.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&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:F.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:F.internal("Unexpected first message")}:{isValid:!1,error:F.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return F.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return F.notAllowed(s,i.status);default:break}return e instanceof F?e:F.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof F?i:F.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function Ho(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Rt(n,e){return new Je({sdp:n.sdp,type:n.type,id:e})}function Su(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Me()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Cu(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new il({clientInfo:e,connectionSettings:new Or({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new nl({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class zo{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 t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Eu{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.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[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var De={},Fn={},Bn={exports:{}},Jo;function Vn(){if(Jo)return Bn.exports;Jo=1;var n=Bn.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Bn.exports}var $o;function Ru(){return $o||($o=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Vn(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var b=0;b<(s[h]||[]).length;b+=1){var v=s[h][b];if(v.reg.test(f))return i(v,l,f)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(Fn)),Fn}var jn,Qo;function wu(){if(Qo)return jn;Qo=1;var n=Vn(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return jn=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||s,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){l.push(i(u,h,f))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(b){l.push(i(h,f,b))})})})}),l.join(`\r
146
146
  `)+`\r
147
- `},jn}var Yo;function Pu(){if(Yo)return De;Yo=1;var n=Ru(),e=wu(),t=Vn();return De.grammar=t,De.write=e,De.parse=n.parse,De.parseParams=n.parseParams,De.parseFmtpConfig=n.parseFmtpConfig,De.parsePayloads=n.parsePayloads,De.parseRemoteCandidates=n.parseRemoteCandidates,De.parseImageAttributes=n.parseImageAttributes,De.parseSimulcastStreamList=n.parseSimulcastStreamList,De}var tt=Pu();function qn(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),b=this;return new Promise(function(v,R){var _=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var x=n.apply(b,f);o&&o(x),l.forEach(function(y){return(0,y.resolve)(x)}),l=[]}},u()),_){var A=n.apply(b,f);return o&&o(A),v(A)}l.push({resolve:v,reject:R})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(b){return(0,b.reject)(f)}),l=[]},h}const Iu=.7,Du=20,wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Xo extends xe.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=V,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=qn(s=>p(this,void 0,void 0,function*(){this.emit(wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Du),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=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new he}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=Au(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=tt.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Wn(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of a.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&a.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=tt.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(wt.NegotiationComplete),e.sdp&&tt.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(wt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);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 s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=tt.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ea(o),o.type==="audio"?Zo(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(Ie(c.codec)&&!dt()&&this.ensureVideoDDExtensionForSVC(o,a),!Ie(c.codec)))return!0;const l=Math.round(c.maxbr*Iu);for(const u of o.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,tt.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=tt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ea(s),s.type==="audio"&&Zo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,tt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new re("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new yt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Ao))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Ao})}}}function Zo(n,e,t){const i=Wn(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Au(n){var e;const t=[],i=[],s=tt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Wn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function ea(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Wn(n){return typeof n=="number"?n.toFixed(0):n}const Kn="vp8",Ou={audioPreset:yn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:_n.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Kn,backupCodec:!0,preConnectBuffer:!1},ta={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ia={deviceId:{ideal:"default"},resolution:jt.h720.resolution},Nu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ul,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Gn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class xu{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Gn.peerConnectionTimeout,this.log=V,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=te.CONNECTED:c.some(d=>d==="failed")?this.state=te.FAILED:c.some(d=>d==="connecting")?this.state=te.CONNECTING:c.every(d=>d==="closed")?this.state=te.CLOSED:c.some(d=>d==="closed")?this.state=te.CLOSING:c.every(d=>d==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new Xo(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new Xo(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=te.NEW,this.connectionLock=new he,this.remoteOfferLock=new he}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===we.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;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 a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=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(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new ue((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new yt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new yt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===we.PUBLISHER?this.publisher.getConnectedAddress():e===we.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,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),de.clearTimeout(u),d(F.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=de.setTimeout(()=>{s?.signal.removeEventListener("abort",l),d(F.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield le(50),s?.signal.aborted){d(F.cancelled("room connection has been cancelled"));return}de.clearTimeout(u),s?.signal.removeEventListener("abort",l),c()}))})()})}}const na=5e3,Mu=3e4;class z{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield z.fetchLock.lock();try{const r=yield fetch("".concat(Lu(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=ru(r.headers),o=a?a*1e3:na;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?F.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):F.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof F?r:i?.aborted?F.cancelled("Region fetching was aborted"):F.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=z.settingsTimeouts.get(e.hostname);clearTimeout(s),z.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield z.fetchRegionSettings(e,t);z.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof F&&r.reason===Q.NotAllowed){V.debug("token is not valid, cancelling auto region refresh");return}V.debug("auto refetching of region settings failed",{error:r}),z.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){z.cache.set(e.hostname,i),z.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=z.settingsTimeouts.get(e);t&&(clearTimeout(t),z.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=z.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=z.connectionTrackers.get(e);i&&i.connectionCount===0&&(V.debug("stopping region refetch after disconnect delay",{hostname:e}),z.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Mu))}static cancelCleanup(e){const t=z.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=z.connectionTrackers.get(e);t||(t={connectionCount:0},z.connectionTrackers.set(e,t)),t.connectionCount++,z.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=z.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&z.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return St(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return z.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=z.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),z.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),V.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){z.updateCachedRegionSettings(this.serverUrl,this.token,e)}}z.cache=new Map,z.settingsTimeouts=new Map,z.connectionTrackers=new Map,z.fetchLock=new he;function Lu(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ie extends Error{constructor(e,t,i){super(t),this.code=e,this.message=ra(t,ie.MAX_MESSAGE_BYTES),this.data=i?ra(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new cr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ie(ie.ErrorCode[e],ie.ErrorMessage[e],t)}}ie.MAX_MESSAGE_BYTES=256,ie.MAX_DATA_BYTES=15360,ie.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},ie.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 sa=15360;function Hn(n){return new TextEncoder().encode(n).length}function ra(n,e){if(Hn(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const zn=2e3;function Ri(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Jn=typeof MediaRecorder<"u";class Uu{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Fu=Jn?MediaRecorder:Uu;class Bu extends Fu{constructor(e,t){if(!Jn)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=c=>{s?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Vu(){return Jn}const ju=1e3,qu=1e4;class oa extends S{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),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=qn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(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(w.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new he,this.pauseUpstreamLock=new he,this.trackChangeLock=new he,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==S.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{kt(this._mediaStreamTrack,r)}),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 s;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&&(_t(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{_t(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ju;return(function*(){var i;if(e.kind===S.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=be())===null||i===void 0?void 0:i.os)==="iOS"&&(yield le(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield le(50)}throw new qe("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Qe(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Qe(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===S.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===S.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new qe("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=hl(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===S.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{kt(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===S.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(w.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.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 p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),No()&&(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 p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(w.UpstreamPaused,this);const i=be();if(i?.name==="Safari"&&Le(i.version,"12.0")<0)throw new bn("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(w.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(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 p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(_t(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(kt(i._mediaStreamTrack,d),_t(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(w.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(w.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Vu()){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 t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Bu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},qu)}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 wi extends oa{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,S.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Ri(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Qe(this._constraints.deviceId);return this.source===S.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=Sn({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ye()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},zn)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Me()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(w.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield wo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(w.AudioSilenceDetected)),e})}}function Wu(n,e,t){switch(n.kind){case"audio":return new wi(n,e,!1,void 0,t);case"video":return new Pi(n,e,!1,t);default:throw new qe("unsupported track type: ".concat(n.kind))}}const Ku=Object.values(jt),Gu=Object.values(Tn),Hu=Object.values(_n),zu=[jt.h180,jt.h360],Ju=[Tn.h180,Tn.h360],$u=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new $(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),$n=["q","h","f"];function Qn(n,e,t,i){var s,r;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);const o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Yu(n,e,t,d),V.debug("using video encoding",a));const l=a.maxFramerate,u=new $(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ie(d)){const b=new da(c),v=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=be();if(Kt()||Me()||R?.name==="Chrome"&&Le(R?.version,"113")<0){const _=b.suffix=="h"?2:3,A=zl(R);for(let x=0;x<b.spatial;x+=1)v.push({rid:$n[2-x],maxBitrate:a.maxBitrate/Math.pow(_,x),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:A?Math.pow(2,x):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),V.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];n?h=(s=ca(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:aa(n,u):h=(r=ca(i?.videoSimulcastLayers))!==null&&r!==void 0?r:aa(n,u);let f;if(h.length>0){const b=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return Yn(e,t,[b,f,u],l);if(v>=480)return Yn(e,t,[b,u],l)}return Yn(e,t,[u])}function Qu(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&V.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===S.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Qn(n.source===S.Source.ScreenShare,c,d,t)}function Yu(n,e,t,i){const s=Xu(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Xu(n,e,t){if(n)return Hu;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Ku:Gu}function aa(n,e){if(n)return $u(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?zu:Ju}function Yn(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=$n.length)return;const o=Math.min(n,e),d={rid:$n[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=ct()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Me()&&Mo()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,V.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),V.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ca(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class da{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Zu(n){return n.source===S.Source.ScreenShare||n.constraints.height&&Qe(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const eh=5e3;class Pi extends oa{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,S.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(w.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=Ri(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new he}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ye())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},zn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Te.LOW;i<=Te.HIGH;i+=1)t.push(new tn({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ie(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Sn({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=je(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=je(s.simulcastCodecs.values()),b;b=yield f.next(),a=b.done,!a;h=!0)d=b.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},eh))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Ie(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=je(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ie(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield la(u.sender,u.encodings,l.qualities,this.senderLock,Ie(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return p(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:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield la(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(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 t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ie(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),No()&&this.isInBackground&&this.source===S.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function la(n,e,t,i,s,r,a){return p(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var b;let v=(b=h.rid)!==null&&b!==void 0?b:"";v===""&&(v="q");const R=ua(v),_=t.find(A=>A.quality===R);_&&h.active!==_.enabled&&(l=!0,h.active=_.enabled,r.debug("setting layer ".concat(_.quality," to ").concat(h.active?"enabled":"disabled"),a),ct()&&(_.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function ua(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function ha(n,e,t,i){if(!t)return[new ze({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new da(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new ze({quality:Math.min(Te.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=ua((a=s.rid)!==null&&a!==void 0?a:"");return new ze({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const pa="_lossy",ma="_reliable",th=2*1e3,Xn="leave-reconnect",ih=3e4,nh=8*1024,sh=256*1024;var Ee;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ee||(Ee={}));class rh extends xe.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Gn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ee.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=V,this.reliableDataSequence=1,this.reliableMessageBuffer=new zo,this.reliableReceivedState=new Eu(ih),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===ma)r.reliableDCSub=a;else if(a.label===pa)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,a,o,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=pe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=rr.fromBinary(h.payload),b=new pe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=b.value)===null||o===void 0?void 0:o.case)==="user"&&fa(b,b.value.value),this.emit(P.DataPacketReceived,b,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&fa(u,u.value.value),this.emit(P.DataPacketReceived,u,se.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?j.LOSSY:j.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(P.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===Xn&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=de.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Ee.Connected&&i();const r=()=>{this.off(P.Disconnected,a),i()},a=()=>{this.off(P.Restarted,r),s()};this.once(P.Restarted,r),this.once(P.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===j.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(P.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(Ht(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Y.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Y.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(rt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ht(this.url),{method:"HEAD"}),le(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ve((t=e.loggerName)!==null&&t!==void 0?t:Pe.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Un(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new he,this.dataProcessLock=new he,this.dcBufferStatus=new Map([[j.LOSSY,!0],[j.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(P.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(P.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(P.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(P.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(P.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(P.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(P.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,a,o,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{V.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(P.SignalConnected,u),u}catch(u){if(u instanceof F){if(u.reason===Q.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,a,o,c,l)}else if(u.reason===Q.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return p(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(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new zo,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 p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(F.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(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,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==te.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new xu(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(P.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,c)=>p(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===te.CONNECTED){const u=this.pcState===Ee.New;this.pcState=Ee.Connected,u&&this.emit(P.Connected,e)}else a===te.FAILED&&(this.pcState===Ee.Connected||this.pcState===Ee.Reconnecting)&&(this.pcState=Ee.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?rt.RR_SUBSCRIBER_FAILED:rt.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Y.RECONNECTING,l=[te.FAILED,te.CLOSING,te.CLOSED].includes(a);d&&l&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(P.MediaTrackAdded,a.track,a.streams[0],a.receiver)},oh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(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,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",rt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:na,regionSettings:e.regions})),e.action){case vt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close();break;case vt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Xn);break;case vt.RESUME:this.handleDisconnect(Xn)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Lt.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(pa,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ma,{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(j.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,nh),sh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(En())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Rn())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(En())return this.createSimulcastTransceiverSender(e,t,i,s);if(Rn())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Ye(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){V.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Lt.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Tt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",rt.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(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Tt;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof F&&a.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):new Tt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new Tt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");if(!this.pcManager)throw new re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof F&&s.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof F&&s.reason===Q.LeaveRequest?s:new Tt(r)}if(this.emit(P.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),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!==Y.CONNECTED)throw new Tt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Ee.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(th),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ee.Connected}catch(e){throw this.pcState=Ee.Disconnected,F.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Ji({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new zi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=mu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new sr({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}t===j.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===j.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){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;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(j.RELIABLE);const t=this.dataChannelForKind(j.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(j.RELIABLE)})}waitForBufferStatusLow(e){return new ue((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new re("engine closed"));for(this.once(P.Closing,s);!this.dcBufferStatus.get(e);)yield le(10);this.off(P.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new re("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw F.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{V.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if(d?.readyState==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield le(50)}throw F.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==te.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new ue((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new yt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new yt("cannot negotiate on closed engine")),this.on(P.Closing,s),this.pcManager.publisher.once(wt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();Xl(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof yt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",rt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(P.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===j.LOSSY)return this.lossyDCSub;if(e===j.RELIABLE)return this.reliableDCSub}else{if(e===j.LOSSY)return this.lossyDC;if(e===j.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(a=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(b=>{b.isDesired!==u&&h.push(b.trackSid),b.isEnabled||f.push(b.trackSid)}),this.client.sendSyncState(new nn({answer:this.pcManager.mode==="publisher-only"?c?Rt({sdp:c.sdp,type:c.type}):void 0:l?Rt({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?Rt({sdp:o.sdp,type:o.type}):void 0:d?Rt({sdp:d.sdp,type:d.type}):void 0,subscription:new pi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ml(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((b,v)=>new Ir({publisherSid:v,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Dr({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),we.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),we.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),we.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),we.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&de.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ye()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ye()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[a]=r;return a===i});if(s)return s[1]}}}function oh(n){return n!==void 0&&n>13}function fa(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class ga{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 Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),me.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),me.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class ah extends ga{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Ce,i=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),i=a}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:d}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class ch extends ga{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ei(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Ce,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,c;try{const{done:d,value:l}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Se("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),me.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw a(),d}}),return(){return p(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class dh{constructor(){this.log=V,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),me.AbnormalEnd);for(const[d,l]of o)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of a)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ei(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new ah(c,d,Ei(e.totalLength),o),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={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,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new ch(c,d,Ei(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class va{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(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 lh extends va{}class uh extends va{}const ba=15e3;class hh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const b=c.reduce((v,R)=>v+R,0);(f=t?.onProgress)===null||f===void 0||f.call(t,b)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),d(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?se.GCM:se.NONE,attachedStreamIds:e?.attachedStreamIds},o=new ci({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:lt(a.timestamp),totalLength:lt(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new vr({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?$i.UPDATE:$i.CREATE})}}),c=e?.destinationIdentities,d=new pe({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,j.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(v){return p(this,void 0,void 0,function*(){for(const R of su(v,ba)){const _=new di({content:R,streamId:r,chunkIndex:lt(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:_}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const v=new li({streamId:r}),R=new pe({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(R,j.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>p(this,void 0,void 0,function*(){yield b.close()});u.once(P.Closing,f);const b=new lh(h,a,()=>this.engine.off(P.Closing,f));return b})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o;const c=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:c,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?se.GCM:se.NONE},u=new ci({totalLength:lt((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:lt(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new br({name:l.name})}}),h=new pe({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,j.RELIABLE);let f=0;const b=new he,v=this.engine,R=this.log,_=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const y=yield b.lock();let T=0;try{for(;T<x.byteLength;){const C=x.slice(T,T+ba),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new di({content:C,streamId:c,chunkIndex:lt(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,T+=C.byteLength}}finally{y()}})},close(){return p(this,void 0,void 0,function*(){const x=new li({streamId:c}),y=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(y,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new uh(_,l)})}}class ya extends S{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(w.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(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(),zn)),Ll()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(w.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class ph extends ya{constructor(e,t,i,s,r,a){super(e,t,S.Kind.Audio,i,a),this.monitorReceiver=()=>p(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=Ri(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Me()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Me())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(wn(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&wn(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),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(w.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(w.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const Zn=100;class mh extends ya{constructor(e,t,i,s,r){super(e,t,S.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Ri(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=qn(()=>{this.updateDimensions()},Zn),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===S.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?kt(this._mediaStreamTrack,t):_t(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new fh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<Zn){de.setTimeout(()=>{this.updateVisibility()},Zn);return}this.lastVisible=o,this.emit(w.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(w.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Lo():t||(Lo()>2?2:1)}}class fh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=$t(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=$t(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=$t(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??es(e),this.isPiP=ye()&&$t(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=es(this.element),this.isPiP=$t(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Fo().observe(this.element),Uo().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Fo())===null||e===void 0||e.unobserve(this.element),(t=Uo())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function $t(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?es(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function es(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class Ke extends xe.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=se.NONE,this.log=V,this.handleMuted=()=>{this.emit(w.Muted)},this.handleUnmuted=()=>{this.emit(w.Unmuted)},this.log=Ve((r=s?.loggerName)!==null&&r!==void 0?r:Pe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=S.Source.Unknown}setTrack(e){this.track&&(this.track.off(w.Muted,this.handleMuted),this.track.off(w.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(w.Muted,this.handleMuted),e.on(w.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),W(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==se.NONE}get audioTrack(){if(Ue(this.track))return this.track}get videoTrack(){if(Ye(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=S.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===S.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ke||(Ke={}));class ts extends Ke{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(w.Ended)},this.handleCpuConstrained=()=>{this.track&&Ye(this.track)&&this.emit(w.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(w.Ended,this.handleTrackEnded),this.track.off(w.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(w.Ended,this.handleTrackEnded),e.on(w.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 p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ue(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ae.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ae.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ae.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ae.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ae.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ae.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Ii(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Io(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Ro(r,ta,ia),d=Sn(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ce.userMediaPromiseMap.set("audioinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("audioinput"))),r.video&&(ce.userMediaPromiseMap.set("videoinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let b=f?c.audio:c.video;(typeof b=="boolean"||!b)&&(b={});let v;const R=f?d.audio:d.video;typeof R!="boolean"&&(v=R);const _=h.getSettings().deviceId;v?.deviceId&&Qe(v.deviceId)!==_?v.deviceId=_:v||(v={deviceId:_});const A=Wu(h,v,e);return A.kind===S.Kind.Video?A.source=S.Source.Camera:A.kind===S.Kind.Audio&&(A.source=S.Source.Microphone),A.mediaStream=u,Ue(A)&&i?yield A.setProcessor(i):Ye(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return Ii(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function gh(n){return p(this,void 0,void 0,function*(){return(yield Ii({audio:!1,video:!0}))[0]})}function vh(n){return p(this,void 0,void 0,function*(){return(yield Ii({audio:!0,video:!1}))[0]})}var it;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(it||(it={}));function bh(n){switch(n){case Mt.EXCELLENT:return it.Excellent;case Mt.GOOD:return it.Good;case Mt.POOR:return it.Poor;case Mt.LOST:return it.Lost;default:return it.Unknown}}class Ta extends xe.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ut.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===ft.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ut.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=it.Unknown,this.log=V,this.log=Ve((c=a?.loggerName)!==null&&c!==void 0?c:Pe.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ce,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(S.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(S.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(S.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ft.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==ft.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=Ul(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(I.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=bh(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ue(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(w.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(w.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case S.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case S.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function yh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new wr({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Th extends Ta{constructor(e,t,i,s,r,a){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=se.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ce)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,d,l,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,d;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:d,message:l}=o,u=this.pendingSignalRequests.get(c);u&&(d!==sn.OK&&u.reject(new Co(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ie.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>yh(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),W(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),W(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),W(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),W(c))),this.emit(I.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,R=je(b),_;_=yield R.next(),c=_.done,!c;v=!0){u=_.value,v=!1;const A=u;Ol(A)&&(this.log.debug("publish ".concat(A," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),W(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,A,f.options))}}catch(A){d={error:A}}finally{try{!v&&!c&&(l=R.return)&&(yield l.call(R))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===S.Source.ScreenShare||o.source===S.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),W(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(We(o)||Xe(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===S.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),W(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),W(o))),We(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),W(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==se.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse).on(P.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:b=>{c(b),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(b=>{let[v,R]=b;return this.attributes[v]===R||R===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield le(50)}c(new Co("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(S.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(S.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(S.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?se.GCM:se.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d?.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case S.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case S.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case S.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new qe(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,Cn(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===S.Source.Microphone&&Ue(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),W(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c?.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===S.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(S.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(S.Source.Camera)||this.pendingPublishing.has(S.Source.Microphone))){this.pendingPublishing.add(S.Source.Camera),this.pendingPublishing.add(S.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(S.Source.Camera),this.pendingPublishing.delete(S.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Ro(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Ii(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Ue(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=S.Source.Microphone,this.emit(I.AudioStreamAcquired)),Ye(o)&&(this.cameraError=void 0,o.source=S.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new bn("getDisplayMedia not supported");e.resolution===void 0&&!Hl()&&(e.resolution=_n.h1080fps30.resolution);const t=xl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new qe("no video track found");const r=new Pi(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=S.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new wi(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=S.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,d,l;We(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Ct(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let _;switch(i.source){case S.Source.Microphone:_="audioinput";break;case S.Source.Camera:_="videoinput"}_&&r.activeDeviceMap.has(_)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(_)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new wi(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Pi(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(_=>{_.track&&_.track===i&&(h=_)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),W(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:b;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),W(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!Jl()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const R=new Promise((_,A)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Y.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:W(i)}));let x=!1;const y=setTimeout(()=>{x=!0,i.stop(),A(new So("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),x)return;const T=yield this.publish(i,f,v);_(T)}else try{const x=yield this.publish(i,f,v);_(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(_){throw _}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),W(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Fl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),W(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new So("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Ct(e)&&M.source===e.source)&&e.source!==S.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),W(e))),t.stopMicTrackOnMute&&Ue(e)&&(e.stopOnMute=!0),e.source===S.Source.ScreenShare&&ct()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Wl()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Kl()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Kn),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===qt(M.mime))||(t.videoCodec=qt(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(w.Muted,this.onTrackMuted),e.on(w.Unmuted,this.onTrackUnmuted),e.on(w.Ended,this.handleTrackEnded),e.on(w.UpstreamPaused,this.onTrackUpstreamPaused),e.on(w.UpstreamResumed,this.onTrackUpstreamResumed),e.on(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const R=[],_=!(!((s=t.dtx)!==null&&s!==void 0)||s),A=e.getSourceTrackSettings();A.autoGainControl&&R.push(ae.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&R.push(ae.TF_ECHO_CANCELLATION),A.noiseSuppression&&R.push(ae.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&R.push(ae.TF_STEREO),_&&R.push(ae.TF_NO_DTX),We(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new Ft({cid:e.mediaStreamTrack.id,name:t.name,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),disableDtx:_,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:R});let y;if(e.kind===S.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const L=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:jt.h720.resolution;M={width:L.width,height:L.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{dims:M}))}x.width=M.width,x.height=M.height,Xe(e)&&(Ie(v)&&(e.source===S.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),W(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),x.simulcastCodecs=[new Yi({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Kn}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Yi({codec:t.backupCodec.codec,cid:""})))),y=Qn(e.source===S.Source.ScreenShare,x.width,x.height,t),x.layers=ha(x.width,x.height,y,Ie(t.videoCodec))}else e.kind===S.Kind.Audio&&(y=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const T=()=>p(this,void 0,void 0,function*(){var M,O,L;if(!this.engine.pcManager)throw new re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(I.LocalSenderCreated,e.sender,e),Xe(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=Zu(e)),e.setDegradationPreference(t.degradationPreference)),y)if(ct()&&e.kind===S.Kind.Audio){let q;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){q=Z;break}q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:q,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Ie(e.codec)&&(!((L=y[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const N=new Promise((M,O)=>p(this,void 0,void 0,function*(){var L;try{C=yield this.engine.addTrack(x),M(C)}catch(q){e.sender&&(!((L=this.engine.pcManager)===null||L===void 0)&&L.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{error:Z}))})),O(q)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([N,T()]))[0];else{C=yield N;let M;if(C.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===S.Kind.Video){const O=qt(M);O!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{codec:O})),t.videoCodec=O,y=Qn(e.source===S.Source.ScreenShare,x.width,x.height,t))}yield T()}const U=new ts(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(U.on(w.CpuConstrained,M=>this.onTrackCpuConstrained(M,U)),U.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:C})),Xe(e)?e.startMonitor(this.engine.client):We(e)&&e.startMonitor(),this.addTrackPublication(U),this.emit(I.LocalTrackPublished,U),We(e)&&C.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,L=>{if(L.trackSid===C.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),W(e))),e.stopPreConnectBuffer()}}),M&&new Promise((q,Z)=>p(this,void 0,void 0,function*(){var _e,ut,ge,st,ns,ss;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),W(e)));const cs=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),sp=yield this.waitUntilActiveAgentPresent();clearTimeout(cs),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),W(e)));const Ia=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[sp.identity],attributes:{trackId:U.trackSid,sampleRate:String((ns=A.sampleRate)!==null&&ns!==void 0?ns:"48000"),channels:String((ss=A.channelCount)!==null&&ss!==void 0?ss:"1")}});try{for(var rs=!0,os=je(M),as;as=yield os.next(),_e=as.done,!_e;rs=!0){st=as.value,rs=!1;const ds=st;yield Ia.write(ds)}}catch(ds){ut={error:ds}}finally{try{!rs&&!_e&&(ge=os.return)&&(yield ge.call(os))}finally{if(ut)throw ut.error}}yield Ia.close(),q()}catch(cs){Z(cs)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),W(e)))}).catch(q=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{error:q}))})}return U})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==se.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new qe("track is not published");if(!Xe(e))throw new qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Qu(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),W(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ft({cid:c.mediaStreamTrack.id,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ha(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(Ct(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),W(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?W(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(w.Muted,this.onTrackMuted),e.off(w.Unmuted,this.onTrackUnmuted),e.off(w.Ended,this.handleTrackEnded),e.off(w.UpstreamPaused,this.onTrackUpstreamPaused),e.off(w.UpstreamResumed,this.onTrackUpstreamResumed),e.off(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Xe(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case S.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case S.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(I.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ue((r,a)=>p(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==S.Source.ScreenShare&&d.source!==S.Source.ScreenShareAudio&&(We(d)||Xe(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?j.RELIABLE:j.LOSSY,a=s.destinationIdentities,o=s.topic;let c=new Gi({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o});const d=new pe({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new ar({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new pe({value:{case:"chatMessage",value:new ai(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new pe({value:{case:"chatMessage",value:new ai(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const a=7e3,o=a+1e3;return new ue((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(Hn(s)>sa){d(ie.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&Le((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ie.builtIn("UNSUPPORTED_SERVER"));return}const b=Math.max(r,o),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,i,s,b);const R=setTimeout(()=>{this.pendingAcks.delete(v),d(ie.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(_)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const _=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(_),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(R)),x?d(x):c(A??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Hi({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,j.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ie.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),W(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ce),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(We(s)||Xe(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield le(20)}})}}class _h extends Ke{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(w.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new pi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new dr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(w.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ke.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ke.SubscriptionStatus.Subscribed:Ke.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ke.PermissionStatus.Allowed:Ke.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 t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Nn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Nn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Te.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(w.VisibilityChanged,this.handleVisibilityChange),s.off(w.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(w.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(w.VisibilityChanged,this.handleVisibilityChange),e.on(w.Ended,this.handleEnded),this.emit(w.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(w.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?w.Muted:w.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(w.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(w.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 Nn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Sr({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===S.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Do(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Bl(this.trackInfo,this.requestedMaxQuality);i&&Do(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.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:Te.HIGH})),e.quality=Te.HIGH)}this.emit(w.UpdateSettings,e)}}class Di extends Ta{static fromParticipantInfo(e,t,i){return new Di(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ut.STANDARD;super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(w.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(w.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(w.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(w.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(w.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(w.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(w.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:S.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:S.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),W(o))),this.emit(I.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new mh(e,t,s,r):d=new ph(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&On(d)&&Ue(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=S.kindFromProto(s.type);if(!c)return;o=new _h(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==S.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:W(d),newTrack:W(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),W(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(I.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case S.Kind.Audio:this.audioTrackPublications.delete(e);break;case S.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Ue(i.track)&&On(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var J;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(J||(J={}));const kh=4*1e3;class Pt extends xe.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=J.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=V,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,d)=>p(this,void 0,void 0,function*(){var l;if(!Gl())throw Me()?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===J.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(J.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==jo(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),St(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new z(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(b=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(b)}).catch(b=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:b}))}));const h=(b,v,R)=>p(this,void 0,void 0,function*(){var _,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Et.getInstance().getBackOffPromise(o),x.signal.aborted)throw F.cancelled("Connection attempt aborted");yield this.attemptConnection(R??o,c,d,x),this.abortController=void 0,b()}catch(y){if(this.regionUrlProvider&&y instanceof F&&y.reason!==Q.Cancelled&&y.reason!==Q.NotAllowed){let T=null;try{this.log.debug("Fetching next region"),T=yield this.regionUrlProvider.getNextBestRegionUrl((_=this.abortController)===null||_===void 0?void 0:_.signal)}catch(C){if(C instanceof F&&(C.status===401||C.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(C);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(y.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Et.getInstance().addFailedConnectionAttempt(o)),T&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(T),this.logContext),this.recreateEngine(),yield h(b,v,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vo(y)),v(y))}else{let T=ke.UNKNOWN_REASON;y instanceof F&&(T=Vo(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),v(y)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ce((b,v)=>{h(b,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,b,v;const R=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let _=R.serverInfo;if(_||(_={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=_,this.log.debug("connected to Livekit Server ".concat(Object.entries(_).map(A=>{let[x,y]=A;return"".concat(x,": ").concat(y)}).join(", ")),{room:(f=R.room)===null||f===void 0?void 0:f.name,roomSid:(b=R.room)===null||b===void 0?void 0:b.sid,identity:(v=R.participant)===null||v===void 0?void 0:v.identity}),!_.version)throw new wl("unknown server version");return _.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),R}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===J.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(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Gn),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const b=l.signal.aborted?F.cancelled("Signal connection aborted"):F.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(b.message="".concat(b.message,": ").concat(f.message)),f instanceof F&&(b.reason=f.reason,b.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),b}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),F.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}ye()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ye()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(J.Connected),this.emit(E.Connected),Et.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,b;const v=yield l.disconnectLock.lock();try{if(l.state===J.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===J.Connecting||l.state===J.Reconnecting||l.isResuming){const R="Abort connection attempt due to user initiated disconnect";l.log.warn(R,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(R),(b=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||b===void 0||b.call(f,F.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,ke.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],c=be();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=An();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(E.Disconnected,()=>{l?.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.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(J.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>p(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(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}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(J.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===ft.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(E.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(E.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=S.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(I.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const d=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(d,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(d,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(d,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(d,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,d);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const l=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(o,c,d,l)=>{this.emit(E.DataReceived,c.payload,o,d,c.topic,l),o?.emit(I.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(E.SipDTMFReceived,c,o),o?.emit(I.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d?.trackPublications.get(c.trackId),u=eu(c,this.transcriptionReceivedTimes);l?.emit(w.TranscriptionReceived,u),d?.emit(I.TranscriptionReceived,u,l),this.emit(E.TranscriptionReceived,u,d,l)},this.handleChatMessage=(o,c)=>{const d=tu(c);this.emit(E.ChatMessage,d,o)},this.handleMetrics=(o,c)=>{this.emit(E.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.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(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o;((o=be())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(E.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(E.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(E.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(E.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(E.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(w.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(E.LocalTrackPublished,o,this.localParticipant),We(o.track)&&(yield o.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,o);const b=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=Cn(o.source);v&&b&&b!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,b),this.emit(E.ActiveDeviceChanged,v,b))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(w.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=Cn(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(E.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(E.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(E.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(E.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(E.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Nu),e),this.log=Ve((i=this.options.loggerName)!==null&&i!==void 0?i:Pe.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ta),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ia),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ou),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new dh,this.outgoingDataStreamManager=new hh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new Th("","",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",Qe(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Qe(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Qe(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ye()){const o=new AbortController;(a=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||a===void 0||a.call(r,"devicechange",this.handleDeviceChange,{signal:o.signal}),Pt.cleanupRegistry&&Pt.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(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 t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new fu(i,t),this.e2eeManager.on(et.ParticipantEncryptionStatusChanged,(s,r)=>{nu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(et.EncryptionError,(s,r)=>{const a=r?this.getParticipantByIdentity(r):void 0;this.emit(E.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===J.Disconnected?ue.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ue.resolve(this.roomInfo.sid):new ue((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(P.RoomUpdate,i),e(s.sid))};this.engine.on(P.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(P.RoomUpdate,i),t(new re("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new rh(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(J.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(J.Connected)&&this.emit(E.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===J.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(I.LocalTrackSubscribed,t),this.emitWhenConnected(E.LocalTrackSubscribed,t,this.localParticipant)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(E.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 t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ce.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===J.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(St(new URL(e))&&t){this.regionUrlProvider=new z(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===J.Disconnected&&(this.regionUrl=i,yield fetch(Ht(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ht(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ne({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ne({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ne({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ne({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=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({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":s=new Ne({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new mi({reason:ke.CLIENT_INITIATED,action:vt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ne({scenario:{case:"subscriberBandwidth",value:lt(t)}});break;case"leave-full-reconnect":s=new Ne({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let b=!0,v=!1;const R=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const _=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===S.Source.Microphone);try{b=(yield Promise.all(A.map(y=>{var T;return(T=y.audioTrack)===null||T===void 0?void 0:T.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=_,y}const x=A.some(y=>{var T,C;return(C=(T=y.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const _=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===S.Source.Camera);try{b=(yield Promise.all(A.map(y=>{var T;return(T=y.videoTrack)===null||T===void 0?void 0:T.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=_,y}const x=A.some(y=>{var T,C;return(C=(T=y.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!wn()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield ce.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const _=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(A=>A.setAudioOutput({deviceId:s})))}catch(A){throw r.options.audioOutput.deviceId=_,A}}return v&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(E.ActiveDeviceChanged,i,s)),b})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===J.Connecting||this.state===J.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(E.Reconnected,u),this.off(E.Connected,u),this.off(E.Disconnected,h)};this.once(E.Reconnected,u),this.once(E.Connected,u),this.once(E.Disconnected,h);return}if(this.state===J.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 s=ql(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}o=u}o.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(r,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:a,trackId:o}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,o,t,i,d);l?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==J.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,c;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()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.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),ye()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(J.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,a){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Hn(l)>sa?(c=ie.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ie?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ie.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=be();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=Nl(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Kt()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Kt())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Po())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),le(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Di.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Di(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(I.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(I.TrackSubscribed,(s,r)=>{s.kind===S.Kind.Audio?(s.on(w.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(w.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===S.Kind.Video&&(s.on(w.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(w.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(I.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(I.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(I.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(I.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(I.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(I.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(I.AttributesChanged,s=>{this.emitWhenConnected(E.ParticipantAttributesChanged,s,i)}).on(I.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(I.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(I.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(I.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(I.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}).on(I.Active,()=>{this.emitWhenConnected(E.ParticipantActive,i),i.kind===Ut.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&iu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=de.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,ke.STATE_MISMATCH))):e=0},kh)}clearConnectionReconcile(){this.connectionReconcileInterval&&de.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===J.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===J.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ri({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ot({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(J.Connected),a.video){const c=new ts(S.Kind.Video,new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO,name:"video-dummy"}),new Pi(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Bo(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}if(a.audio){const c=new ts(S.Kind.Audio,new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO}),new wi(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:An(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new ot({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:ft.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=Bo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=An(),h=new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const r=_a(i).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Pt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function _a(n){return n.map(e=>{if(e)return Array.isArray(e)?_a(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ae;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Ae||(Ae={}));class nt extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ae.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Pt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Ae.IDLE)throw Error("check is running already");this.setStatus(Ae.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Ae.SKIPPED&&this.setStatus(this.isSuccess()?Ae.SUCCESS:Ae.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===J.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==J.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ae.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield le(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 Sh extends nt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new z(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let b=0;b<c;b++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h?.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(f.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const is=1e4;class Ch extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(is/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(is/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,is)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Eh extends nt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield vh();if(yield wo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const 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==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class Rh extends nt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield gh();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const v=f.getImageData(0,0,d.width,d.height).data;let R=!0;for(let _=0;_<v.length;_+=4)if(v[_]!==0||v[_+1]!==0||v[_+2]!==0){R=!1;break}R?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class wh extends nt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==J.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 Ph extends nt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;St(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new z(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new Un,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Ih extends nt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Dh(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),V.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Dh(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Ah extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new Un,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(St(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new z(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===ur.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class ap extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Ae.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Ae.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ah)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ih)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ph)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(wh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Eh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Rh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Ch);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Sh)})}}function K(n,e,t){return(e=Nh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Oh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Nh(n){var e=Oh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class fe extends Error{constructor(e,t){var i;super(e,t),K(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}K(fe,"code","ERR_JOSE_GENERIC");class xh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),K(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),K(this,"claim",void 0),K(this,"reason",void 0),K(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}K(xh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Mh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),K(this,"code","ERR_JWT_EXPIRED"),K(this,"claim",void 0),K(this,"reason",void 0),K(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}K(Mh,"code","ERR_JWT_EXPIRED");class Lh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}K(Lh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Uh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_NOT_SUPPORTED")}}K(Uh,"code","ERR_JOSE_NOT_SUPPORTED");class Fh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWE_DECRYPTION_FAILED")}}K(Fh,"code","ERR_JWE_DECRYPTION_FAILED");class Bh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWE_INVALID")}}K(Bh,"code","ERR_JWE_INVALID");class Vh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWS_INVALID")}}K(Vh,"code","ERR_JWS_INVALID");class jh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWT_INVALID")}}K(jh,"code","ERR_JWT_INVALID");class qh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWK_INVALID")}}K(qh,"code","ERR_JWK_INVALID");class Wh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWKS_INVALID")}}K(Wh,"code","ERR_JWKS_INVALID");class Kh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}K(Kh,"code","ERR_JWKS_NO_MATCHING_KEY");class Gh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,Symbol.asyncIterator,void 0),K(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}K(Gh,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Hh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWKS_TIMEOUT")}}K(Hh,"code","ERR_JWKS_TIMEOUT");class zh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}K(zh,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var ka;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(ka||(ka={}));var Sa;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Sa||(Sa={}));var Ca;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Ca||(Ca={}));var Ai;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Ai||(Ai={})),Ai.UserTimestamp,Ai.E2ee;var Ea;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Ea||(Ea={}));class Jh extends G{constructor(e){super(),this._room=null,this._context=e,this._trackRegistry=new Tc,this._eventAdapter=new _c(e,this._trackRegistry),this._maxAttempts=e.options.reconnect?.maxAttempts||It,this._maxDelay=(e.options.reconnect?.delay??Ni)*Dt,m.info("LiveKit Service created")}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._room&&this._room.isConnected()){m.warn("Already connected to LiveKit room");return}try{m.info(`Connecting to LiveKit room: ${i} at ${e}`);const r=new Pt({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(Dt*Math.pow(2,a.retryCount),this._maxDelay):null}});r.prepareConnection(e,t),r.on(E.TrackSubscribed,(a,o,c)=>{this._handleTrackSubscribed(a,o,c)}),r.on(E.TrackUnsubscribed,(a,o,c)=>{this._handleTrackUnsubscribed(a,o,c)}),r.on(E.TrackMuted,(a,o)=>{this._handleTrackMuted(a,o)}),r.on(E.TrackUnmuted,(a,o)=>{this._handleTrackUnmuted(a,o)}),r.on(E.Connected,()=>{m.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),r.on(E.Disconnected,a=>{a?m.info(`LiveKit room disconnected: ${a}`):m.info("LiveKit room disconnected"),a!==ke.CLIENT_INITIATED&&this._context.eventBus.emit("inner:rtc:disconnected",{reason:a?String(a):void 0}),this._room=null}),m.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||It}),this._eventAdapter.setRoom(r),this._room=r}catch(r){throw H.fromError(r,B.LIVEKIT_CONNECT_FAILED)}}_handleTrackSubscribed(e,t,i){try{if(!e.mediaStreamTrack){m.warn("Track does not have MediaStreamTrack");return}e.kind==="audio"&&i.on(I.IsSpeakingChanged,o=>{console.log("\u8F68\u9053 \u8BF4\u8BDD\u72B6\u6001:",o)});const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){m.error("Error handling track subscribed:",s)}}_handleTrackUnsubscribed(e,t,i){try{const s=t,r=i,a=s.trackSid,o=r.identity;this._trackRegistry.getTrack(a)?.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0),this._eventAdapter.handleTrackUnsubscribed(a,o)}catch(s){m.error("Error handling track unsubscribed:",s)}}_handleTrackMuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)}catch(i){m.error("Error handling track muted:",i)}}_handleTrackUnmuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:available",void 0)}catch(i){m.error("Error handling track unmuted:",i)}}async disconnect(){if(this._room)try{await this._room.disconnect(),this._room=null,this._context.eventBus.emit("inner:rtc:disconnected",{reason:"Disconnected from LiveKit room"}),m.info("Disconnected from LiveKit room")}catch(e){m.error("Error disconnecting from LiveKit room:",e),this._room=null}}isConnected(){return this._room?this._room.state===J.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),m.info("LiveKit Service disposed")}}class $h extends G{constructor(e){super(),this._conversationManager=null,this._context=e,m.info("WebSocket Dispatcher created")}setConversationManager(e){this._conversationManager=e,m.debug("Conversation manager set in dispatcher")}dispatch(e){this.ensureNotDisposed();try{if(e.type==="ws"){this._handleWSServerMessage(e);return}if(e.type==="text"){this._handleServerTextMessage(e);return}}catch(t){m.error("Error dispatching message:",t)}}_handleWSServerMessage(e){e.code===101?(this._conversationManager?.handleServerPong(),m.debug("Received pingpong response")):e.code===102&&(m.warn("Server will disconnect"),this._conversationManager?.willDisconnect())}_handleServerTextMessage(e){if(!this._conversationManager){m.warn("Conversation manager not set, text message ignored");return}const{uid:t,payload:i,code:s}=e;s===200?(this._conversationManager.handleAnswerChunk(t,i,!1),m.debug(`Answer received (code 401) for uid: ${t}`)):s===201?(this._conversationManager.handleAnswerChunk(t,"",!0),m.debug(`Answer completed (code 411) for uid: ${t}`)):s===300?(this._conversationManager.handleAsrTextReceived(t,i),m.debug(`ASR text chunk received (code 410) for uid: ${t}`)):s===400&&(this._conversationManager.handleServerInitiatedMessage(t,i),m.debug(`Server initiated message received (code 412) for uid: ${t}`))}onDispose(){m.info("WebSocket Dispatcher disposed")}}class Qh extends G{constructor(e){super(),this._ws=null,this._dispatcher=null,this._isConnecting=!1,this._activeTimers=new Set,this._retryCount=0,this._maxRetries=It,this._pingTimer=void 0,this._pongTimer=void 0,this._isExplicitDisconnect=!1,this._context=e,this._maxRetries=e.options.reconnect?.maxAttempts??It,this._maxDelay=(e.options.reconnect?.delay??Ni)*Dt,this._dispatcher=new $h(e)}setConversationManager(e){this._dispatcher&&this._dispatcher.setConversationManager(e)}async connect(){if(this.ensureNotDisposed(),this._stopHeartbeat(),!(this._isConnecting||this.isConnected||this._ws?.readyState===WebSocket.OPEN)){this._isConnecting=!0,this._isExplicitDisconnect=!1;try{return this._ws=new WebSocket(this._context.wsUrl),new Promise((e,t)=>{this._ws.onopen=()=>{this._isConnecting=!1,this._retryCount=0,this.sendPing(),this._context.eventBus.emit("inner:ws:connected",void 0),m.info("Conversation transport connected"),e()},this._ws.onerror=i=>{this._isConnecting=!1,m.error("Conversation transport error:",i),this._context.eventBus.emit("inner:sdk:error",{error:new H("WebSocket connection error",B.WS_CONNECT_ERROR,i)}),t(new H("WebSocket connection error",B.WS_CONNECT_ERROR,i))},this._ws.onclose=i=>{const s=i.code,r=i.reason?i.reason:i.wasClean?"Clean close":"Closed by remote";this._handleDisconnect(s,r)},this._ws.onmessage=i=>{this._handleMessage(i.data)}})}catch(e){throw this._isConnecting=!1,this._context.emitError(e,B.WS_CONNECT_FAILED)}}}disconnect(){this._isExplicitDisconnect=!0,this._stopHeartbeat(),this._ws&&(this._ws.close(),this._ws=null),this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client disconnect"}),m.info("Conversation transport disconnected")}_handleDisconnect(e,t){if(this._stopHeartbeat(),this._isConnecting=!1,e!==void 0&&new Set([1e3,1001,1002,1003,1007,1008]).has(e)){this._isExplicitDisconnect=!0;const s=`WebSocket closed (code ${e}): ${t??""}`;this._context.eventBus.emit("inner:ws:disconnected",{reason:s}),m.info(`Conversation transport closed with non-retry code ${e}: ${t??""}`);return}if(!this._isExplicitDisconnect&&this._retryCount<this._maxRetries){this._retryCount++;const s=Math.min(Dt*Math.pow(2,this._retryCount-1),this._maxDelay);m.warn(`Connection lost. Retry ${this._retryCount} in ${s}ms`);const r=setTimeout(()=>{!this._isExplicitDisconnect&&!this.isDisposed&&this.connect().catch(()=>{})},s);this._registerTimer(r)}else this._context.eventBus.emit("inner:ws:disconnected",{reason:"Closed"})}_registerTimer(e){return this._activeTimers.add(e),e}_clearTimer(e){e&&(clearTimeout(e),this._activeTimers.delete(e))}sendPing(){if(!this.isConnected)return;const e={type:"ws",code:101,payload:"ping"};this._ws?.send(JSON.stringify(e)),clearTimeout(this._pongTimer),this._pongTimer=setTimeout(()=>{m.error(`Pong timeout (${hs/Dt}s). Reconnecting...`),this._ws?.close()},hs)}handlePongReceived(){clearTimeout(this._pongTimer),this._clearTimer(this._pingTimer),this._pingTimer=setTimeout(()=>{this.sendPing()},Na)}willDisconnect(){if(this.ensureNotDisposed(),this._ws&&this._ws.readyState===WebSocket.OPEN){const t=JSON.stringify({type:"ws",code:102,payload:"will disconnect"});this._ws.send(t),this._isExplicitDisconnect=!0,this._ws.close(),this._ws=null,this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client responsive to server's disconnect message."})}}sendText(e,t,i=200,s){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN)throw new H("WebSocket is not connected",B.WS_NOT_CONNECTED);try{const a=JSON.stringify({type:"text",code:i,uid:e,metadata:s,payload:t});this._ws.send(a),m.debug("Text message sent via transport:",e)}catch(r){throw this._context.emitError(r,B.WS_TEXT_SEND_FAILED)}}_handleMessage(e){try{if(typeof e!="string")return;const t=JSON.parse(e);m.debug("Message received:",t.type),this._dispatcher?this._dispatcher.dispatch(t):m.warn("Dispatcher not set, message ignored")}catch(t){m.error("Error parsing message:",t),this._context.emitError(t,B.WS_PARSE_ERROR)}}sendBinary(e){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN){m.debug("WebSocket not connected, binary data dropped");return}try{this._ws.send(e),m.debug("Binary data sent via transport")}catch(t){m.error("Error sending binary data:",t)}}get isConnected(){return this._ws?.readyState===WebSocket.OPEN}_stopHeartbeat(){this._clearTimer(this._pingTimer),this._clearTimer(this._pongTimer)}onDispose(){this._stopHeartbeat(),this.disconnect(),this._dispatcher&&(this._dispatcher.dispose(),this._dispatcher=null),m.info("Conversation transport disposed")}}const Oi=["sdk:connected","sdk:disconnected","sdk:error","media:video:available","media:video:unavailable","media:video:trackAdded","media:video:trackRemoved","media:audio:trackAdded","media:audio:trackRemoved","media:audio:captureStarted","media:audio:captureStopped","media:audio:volumeChanged","media:audio:muted","media:audio:unmuted","conversation:question:sent","conversation:answer:waiting","conversation:server:message","conversation:asr:received","conversation:answer:chunk","conversation:answer:completed"],Ra=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class Yh{constructor(e){this.inner=e,this.listeners=new Map,this.forwardedVideoTrackIds=new Set,this.wsConnected=!1,this.livekitConnected=!1,this.httpConnected=!1,this.internalMap={"inner:sdk:error":{public:"sdk:error",sanitizer:t=>({message:t?.error?.message,code:t?.error?.code})},"inner:rtc:video:available":{public:"media:video:available"},"inner:rtc:video:unavailable":{public:"media:video:unavailable"},"inner:video:track:added":{public:"media:video:trackAdded"},"inner:video:track:removed":{public:"media:video:trackRemoved"},"inner:audio:track:added":{public:"media:audio:trackAdded"},"inner:audio:track:removed":{public:"media:audio:trackRemoved"},"inner:audio:input:started":{public:"media:audio:captureStarted"},"inner:audio:input:stopped":{public:"media:audio:captureStopped"},"inner:audio:volume:changed":{public:"media:audio:volumeChanged",sanitizer:t=>({volume:t?.volume})},"inner:audio:muted":{public:"media:audio:muted"},"inner:audio:unmuted":{public:"media:audio:unmuted"},"inner:conversation:question:sent":{public:"conversation:question:sent",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:waiting":{public:"conversation:answer:waiting",sanitizer:t=>({questionId:t?.questionId})},"inner:conversation:server:message":{public:"conversation:server:message",sanitizer:t=>({questionId:t?.questionId,message:String(t?.message||""),type:String(t?.type||"")})},"inner:conversation:asr:received":{public:"conversation:asr:received",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:chunk":{public:"conversation:answer:chunk",sanitizer:t=>({questionId:t?.questionId,chunk:String(t?.chunk||"")})},"inner:conversation:answer:completed":{public:"conversation:answer:completed",sanitizer:t=>({questionId:t?.questionId,fullAnswer:String(t?.fullAnswer||"")})}},Object.keys(this.internalMap).forEach(t=>{this.inner.on(t,i=>this.handleInternalEvent(t,i))}),this.inner.on("inner:sdk:connected",t=>this.handleConnected(t,!0)),this.inner.on("inner:sdk:disconnected",t=>this.handleConnected(t,!1)),Oi.forEach(t=>{this.inner.on(t,i=>this.handlePublicEvent(t,i))})}publicAPI(){return{on:this.on.bind(this),off:this.off.bind(this),once:this.once.bind(this)}}on(e,t){const i=String(e);return this.assertAllowed(i),this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t),()=>this.off(e,t)}once(e,t){const i=String(e);this.assertAllowed(i);const s=r=>{try{t(r)}finally{this.off(e,s)}};return this.on(e,s)}off(e,t){const i=String(e);this.assertAllowed(i);const s=this.listeners.get(i);s&&(s.delete(t),s.size===0&&this.listeners.delete(i))}handleInternalEvent(e,t){const i=this.internalMap[e];if(!i)return;const s=i.public;if(Oi.indexOf(s)===-1)return;if(s==="media:video:trackAdded"){const o=t?.trackId||t?.id;if(typeof o=="string"){if(this.forwardedVideoTrackIds.has(o))return;this.forwardedVideoTrackIds.add(o)}}const r=i.sanitizer?i.sanitizer(t):t;if(!Ra.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){console.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Oi.indexOf(e)===-1)return;const i=Object.values(this.internalMap).find(a=>a.public===e),s=i&&i.sanitizer?i.sanitizer(t):t;if(e==="media:video:trackAdded"){const a=t?.trackId||t?.id;if(typeof a=="string"){if(this.forwardedVideoTrackIds.has(a))return;this.forwardedVideoTrackIds.add(a)}}const r=this.listeners.get(e);!r||r.size===0||r.forEach(a=>{try{a(s)}catch(o){console.error("PublicEventEmitter listener error",o)}})}handleConnected(e,t){e.source==="livekit"?this.livekitConnected=t:e.source==="ws"?this.wsConnected=t:e.source==="http"&&(this.httpConnected=t),this.maybeEmitSdkConnected(t?"connected":"disconnected")}maybeEmitSdkConnected(e){const t=e==="connected",i=t?!!this.livekitConnected:!this.livekitConnected,s=t?!!this.wsConnected:!this.wsConnected,r=t?!!this.httpConnected:!this.httpConnected,a={livekit:i,ws:s,http:r,all:i&&s&&r},o=JSON.stringify(a);this.lastConnectedPayloadJson!==o&&(this.lastConnectedPayloadJson=o,this.inner.emit(`sdk:${e}`,a))}assertAllowed(e){if(Oi.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!Ra.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class Xh extends G{constructor(e,t,i){super(),this._requestCounter=0,this._context=e,this._baseURL=t||"",this._defaultHeaders=i||{},m.info(`HTTP Service created with baseURL: ${this._baseURL||"none"}`)}setAuthToken(e){this._defaultHeaders.Authorization=`Bearer ${e}`}request(e){this.ensureNotDisposed();const t=e.requestId||`req_${Date.now()}_${++this._requestCounter}`,i=this._buildURL(e.url,e.params),s=this._mergeHeaders(e.headers),r={method:e.method||"GET",headers:s};e.data!==void 0&&(e.method||"GET")!=="GET"&&(typeof e.data=="string"?r.body=e.data:(r.body=JSON.stringify(e.data),!s["Content-Type"]&&!s["content-type"]&&(s["Content-Type"]="application/json")));const a=e.timeout||3e4,o=new AbortController;return r.signal=o.signal,new Promise((c,d)=>{const l=setTimeout(()=>o.abort(),a);fetch(i,r).then(async u=>{clearTimeout(l);const h={};u.headers.forEach((R,_)=>{h[_]=R});let f;const b=u.headers.get("content-type");b&&b.includes("application/json")?f=await u.json():f=await u.text();const v={requestId:t,status:u.status,headers:h,data:f,config:e};m.debug(`HTTP request succeeded: ${e.method} ${i} [${t}]`),c(v)}).catch(u=>{clearTimeout(l);const h=u&&u.name==="AbortError",f={requestId:t,status:u&&u.status||void 0,message:h?"Request aborted (timeout)":u&&u.message||"HTTP request failed",error:u,config:e};m.error(`HTTP request failed: ${e.method} ${i} [${t}]`,u),d(f)})})}get(e,t,i){return this.request({...i,url:e,method:"GET",params:t})}post(e,t,i){return this.request({...i,url:e,method:"POST",data:t})}put(e,t,i){return this.request({...i,url:e,method:"PUT",data:t})}delete(e,t){return this.request({...t,url:e,method:"DELETE"})}patch(e,t,i){return this.request({...i,url:e,method:"PATCH",data:t})}_buildURL(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return this._appendParams(e,t);let i=this._baseURL;return i&&!i.endsWith("/")&&!e.startsWith("/")?i+="/":i&&i.endsWith("/")&&e.startsWith("/")&&(i=i.slice(0,-1)),i+=e,this._appendParams(i,t)}_appendParams(e,t){if(!t||Object.keys(t).length===0)return e;const i=new URLSearchParams;for(const[r,a]of Object.entries(t))i.append(r,String(a));const s=e.includes("?")?"&":"?";return`${e}${s}${i.toString()}`}_mergeHeaders(e){const t={...this._defaultHeaders};return e&&Object.assign(t,e),t}onDispose(){m.info("HTTP Service disposed")}}function Zh(n,e="https"){return n.startsWith(e)?n:`${e}://${n}`}class ep extends G{constructor(e,t){super(),this._context=e,this._httpService=new Xh(e,t||La)}getAuthToken(){return this.ensureNotDisposed(),this._httpService?.request({url:"/auth/login",method:"GET",data:{}}).then(e=>{e.data.code===At&&this._httpService?.setAuthToken(e.data.data.token)}).catch(e=>{throw this._context.emitError(e,B.SDK_AUTH_TOKEN_FAILED)})}getLivekitConfig(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/start",method:"POST",data:{avatarName:this._context.options.avatarName,voice:this._context.options.avatarVoice}}).then(e=>{if(e.data.code===At){const t=e.data.data;return this._context.setLivekitConfig(Zh(t.livekitUrl,"wss"),t.roomToken,t.roomId),this._context.setWsUrl(`${this._context.options.wsUrlPrefix||Fa}/${t.roomId}/${this._context.options.avatarName}`),this._context.setVideoOptions({renderMode:t.greenScreen.enabled?"processed":"raw",greenScreen:t.greenScreen||{}}),this._context.eventBus.emit("inner:sdk:connected",{source:"http"}),!0}else throw new H(e.data.msg,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}).catch(e=>{throw this._context.eventBus.emit("inner:sdk:error",{error:new H(e.message,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}),H.fromError(e,B.SDK_GET_LIVEKIT_CONFIG_FAILED)})}switchVideo({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._httpService?.request({url:"/avatar/v1/switch-video",method:"POST",data:{roomId:this._context.roomId,onceActions:e,loopActions:t}}).then(i=>{if(i.data.code===At)return!0;throw this._context.emitError(i.data.message,B.SDK_SWITCH_VIDEO_FAILED)})}interruptConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/interrupt",method:"POST",data:{roomId:this._context.roomId}}).then(e=>{if(e.data.code===At)return!0;throw this._context.emitError(e.data.message,B.SDK_INTERRUPT_CONVERSATION_FAILED)}).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}disconnectConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/stop",method:"POST",data:{roomId:this._context.roomId}}).then(e=>e.data.code===At).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}onDispose(){this._httpService.dispose()}}class wa extends G{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._liveKitService=null,this._conversationTransport=null,this._connectionCoordinator=null,this._httpController=null,this._preConnectPromise=null,this._lastPreConnectSuccessAt=null,this._context=new Va(e),m.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new Yh(this._context.eventBus),this._publicEventAPI=this._publicEmitter.publicAPI()),this._publicEventAPI}pushActions({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.switchVideo({onceActions:e,loopActions:t})}interruptConnection(){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.interruptConversation()}sendTextQuestion(e){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.sendQuestion(e);throw new H("Conversation controller is not available",B.CONVERSATION_CONTROLLER_NOT_AVAILABLE)}setRenderFitMode(e){this.ensureNotDisposed(),this._ensureConnected(),this._videoController&&this._videoController.setRenderFitMode(e)}async startAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.startCapture()}async stopAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.stopCapture()}setVolume(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.setVolume(e)}getVolume(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController?.getVolume()||1}mute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.mute()}unmute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.unmute()}get isMuted(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController.isMuted()}get isAudioCapturing(){return this.ensureNotDisposed(),this._ensureConnected(),this._audioController?this._audioController.isCapturing:!1}async preConnect(){if(this.ensureNotDisposed(),this._preConnectPromise)return this._preConnectPromise;const e=Date.now();return this._lastPreConnectSuccessAt!==null&&e-this._lastPreConnectSuccessAt<Ba?Promise.resolve(!0):(this._preConnectPromise=(async()=>{try{if(m.info("Creating HTTP controller..."),this._httpController=this._httpController??new ep(this._context,this._context.options.http?.baseURL),m.info("Getting auth token..."),await this._httpController.getAuthToken(),m.info("Getting livekit config..."),!!!await this._httpController?.getLivekitConfig())throw new Error("Config missing");return this._lastPreConnectSuccessAt=Date.now(),!0}catch(t){throw this._context.emitError(t,B.SDK_PRECONNECT_FAILED)}finally{this._preConnectPromise=null}})(),this._preConnectPromise)}async connect(){if(this.ensureNotDisposed(),this._connectionCoordinator&&this._context.sessionState.isConnected){m.warn("SDK already initialized");return}try{if(!await this.preConnect())throw new H("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED)}catch(e){throw this._context.emitError(e,B.SDK_CONNECT_FAILED)}try{if(m.info("Initializing SDK..."),this._connectionCoordinator=new qa(this._context),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._videoController=new Ja(this._context,this._context.options.video),this._audioController=new mc(this._context,this._context.options.audio),this._conversationController=new yc(this._context),this._liveKitService=new Jh(this._context),this._conversationTransport=new Qh(this._context),this._liveKitService&&this._videoController&&this._audioController){const e=this._liveKitService.getEventAdapter();e&&(typeof e.setVideoController=="function"&&e.setVideoController(this._videoController),typeof e.setAudioController=="function"&&e.setAudioController(this._audioController))}this._audioController&&this._conversationTransport&&this._audioController.setWebSocketSender({sendBinary:e=>{this._conversationTransport.sendBinary(e)},isConnected:()=>this._conversationTransport.isConnected}),this._conversationTransport&&this._conversationController&&(this._conversationTransport.setConversationManager(this._conversationController.manager),this._conversationController.setTransport(this._conversationTransport)),await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),this._conversationTransport&&await this._conversationTransport.connect(),m.info("SDK initialized and connected")}catch(e){throw this._connectionCoordinator&&this._connectionCoordinator.transitionToIdle(),await this._cleanup(),this._context.emitError(e,B.SDK_INITIALIZATION_FAILED)}}async disconnect(){if(this.ensureNotDisposed(),!(!this._connectionCoordinator||this._connectionCoordinator.getState()==="idle"||this._connectionCoordinator.getState()==="disposed")){m.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService&&await this._liveKitService.disconnect(),this._audioController&&this._audioController.stopCapture(),this._httpController&&await this._httpController.disconnectConversation(),this._preConnectPromise=null,this._connectionCoordinator.completeDisconnecting(),m.info("SDK disconnected")}catch(e){throw m.error("Error during disconnect:",e),this._context.emitError(e,B.SDK_DISCONNECT_FAILED)}}}async reconnect(){this.ensureNotDisposed();const e=this._connectionCoordinator;if(!e?.canStartReconnectingManual()){const i=e?e.getSnapshot():this.connectionSnapshot;return m.warn("SDK reconnect not allowed in current state, returning current snapshot"),i}const t=e.captureSnapshotAndStartReconnectingManual();try{if(this._audioController&&this._audioController.stopCapture(),t.rtc.connected&&!t.rtc.hasVideoTrack&&(await this._liveKitService?.disconnect(),await this._conversationTransport?.disconnect()),this._conversationTransport&&!this._conversationTransport.isConnected){if(!await this.preConnect())throw new H("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED);await this._conversationTransport.connect()}return this._liveKitService&&!this._liveKitService.isConnected()&&await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),t}catch(i){throw m.error("Error during reconnect:",i),this._context.emitError(i,B.SDK_RECONNECT_FAILED)}}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():fs(ms("idle"))}async _cleanup(){if(this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){m.error("Error disconnecting LiveKit:",e)}this._audioController&&this._audioController.stopCapture()}get isConnected(){return this.ensureNotDisposed(),this._context.sessionState.isConnected}_ensureConnected(){if(!this._context.sessionState.isConnected)throw new H("SDK is not connected. Call connect() first.",B.SDK_NOT_CONNECTED)}onDispose(){this.disconnect().catch(e=>{m.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._conversationController&&(this._conversationController.dispose(),this._conversationController=null),this._liveKitService&&(this._liveKitService.dispose(),this._liveKitService=null),this._conversationTransport&&(this._conversationTransport.dispose(),this._conversationTransport=null),this._httpController&&(this._httpController.dispose(),this._httpController=null),this._connectionCoordinator&&(this._connectionCoordinator.transitionToDisposed(),this._connectionCoordinator.dispose(),this._connectionCoordinator=null),this._context.dispose(),m.info("SDK Client disposed")}}function tp(n){if(!n.avatarName)throw new H("avatarName is required",B.NO_AVATARNAME);return m.info("Creating SDK client with options:",{avatarName:n.avatarName}),new wa(n)}class Pa extends G{constructor(e,t){super(),this._videoElement=null,this._videoUrl=null,this._isPlaying=!1,this._frameCallbackId=null,this._videoUrl=e,t?this._videoElement=t:(this._videoElement=document.createElement("video"),this._videoElement.style.opacity="0",this._videoElement.muted=!0,this._videoElement.playsInline=!0,this._videoElement.loop=!0,document.querySelector("#video-container")?.appendChild(this._videoElement)),m.info("Local Video Debug Source created")}get videoElement(){return this._videoElement}async load(){if(!this._videoElement)throw new Error("Video element or URL not set");return new Promise((e,t)=>{const i=this._videoElement,s=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),m.info(`Video loaded: ${i.videoWidth}x${i.videoHeight}`),e()},r=a=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),t(new Error(`Failed to load video: ${a}`))};i.addEventListener("loadedmetadata",s),i.addEventListener("error",r),i.src=this._videoUrl||"",i.load()})}async play(){if(!this._videoElement)throw new Error("Video element not set");if(!this._isPlaying)try{await this._videoElement.play(),this._videoElement.style.opacity="0",this._videoElement.setAttribute("loop","true"),this._isPlaying=!0,m.info("Video playback started")}catch(e){throw m.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,m.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,m.info("Video playback stopped"))}get isPlaying(){return this._isPlaying&&this._videoElement!==null&&!this._videoElement.paused}get videoWidth(){return this._videoElement?.videoWidth||0}get videoHeight(){return this._videoElement?.videoHeight||0}async captureFrame(){if(!this._videoElement||this._videoElement.readyState<2)return null;try{if("VideoFrame"in window&&typeof window.VideoFrame=="function")try{return new VideoFrame(this._videoElement,{timestamp:this._videoElement.currentTime*1e6})}catch(i){m.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return m.error("Failed to capture video frame:",e),null}}onFrame(e){if(!this._videoElement)return;this.offFrame();const t=this._videoElement;if("requestVideoFrameCallback"in t){const i=(s,r)=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(a=>{a&&(e(a),a.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=t.requestVideoFrameCallback(i))}).catch(a=>{m.error("Error in frame callback:",a)})};this._frameCallbackId=t.requestVideoFrameCallback(i)}else{const i=()=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(s=>{s&&(e(s),s.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=requestAnimationFrame(i))}).catch(s=>{m.error("Error in frame callback:",s)})};this._frameCallbackId=requestAnimationFrame(i)}}offFrame(){this._frameCallbackId!==null&&(this._videoElement&&"cancelVideoFrameCallback"in this._videoElement?this._videoElement.cancelVideoFrameCallback(this._frameCallbackId):cancelAnimationFrame(this._frameCallbackId),this._frameCallbackId=null)}onDispose(){this.stop(),this.offFrame(),this._videoElement&&this._videoElement.parentElement===document.body&&document.body.removeChild(this._videoElement),this._videoElement=null,this._videoUrl=null,m.info("Local Video Debug Source disposed")}}class ip extends G{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new vs;const s={...e,renderMode:"processed"};this._pipeline=new Ts(this._source,s),this._outputRenderer=new Mi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),m.info("Video Pipeline Runner created")}get outputCanvas(){return this._outputCanvas}get processor(){return this._pipeline.strategy.getProcessors()[0]||null}setProcessor(e){this._pipeline.setProcessor(e),m.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){m.error("Output renderer not available"),e.close();return}try{const t=this._pipeline.strategy.getProcessors()[0]||null;let i=null;if(t){try{i=t.process(e)}catch(s){m.error("Error processing frame:",s),i=e}if(i===null&&"getImageData"in t){const s=t.getImageData();if(s&&this._outputCanvas&&this._outputRenderer.getContext()){const r=this._outputRenderer.getContext();r&&((this._outputCanvas.width!==s.width||this._outputCanvas.height!==s.height)&&(this._outputCanvas.width=s.width,this._outputCanvas.height=s.height),r.putImageData(s,0,0))}e.close();return}i&&i!==e?(this._outputRenderer.render(i),e.close()):i===e?this._outputRenderer.render(e):e.close()}else this._outputRenderer.render(e)}catch(t){m.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,m.info(`Output canvas size set to ${e}x${t}`))}onDispose(){this._pipeline.dispose(),this._outputRenderer&&(this._outputRenderer.dispose(),this._outputRenderer=null),this._outputCanvas&&this._outputCanvas.parentElement===document.body&&document.body.removeChild(this._outputCanvas),this._outputCanvas=null,m.info("Video Pipeline Runner disposed")}}class np extends G{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Pa(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new ip(this._options,t,i),this._options.greenScreen?.enabled){const r=new Li(this._options.greenScreen);this._pipelineRunner.setProcessor(r),m.info("Green screen processor enabled in debugger")}m.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Pa(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{m.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){console.warn("Error disposing old video source during switch:",c)}const a=this._videoSource.videoWidth,o=this._videoSource.videoHeight;a>0&&o>0&&this._pipelineRunner.setOutputSize(a,o)}catch(a){m.error("Failed to switch video source:",a);try{r.dispose()}catch(o){console.warn("Error disposing new video source after failed switch:",o)}throw a}}get outputCanvas(){return this._pipelineRunner.outputCanvas}get videoSource(){return this._videoSource}get processor(){return this._pipelineRunner.processor}setProcessor(e){this._pipelineRunner.setProcessor(e)}updateGreenScreenOptions(e){const t=this._pipelineRunner.processor;if(t&&"updateOptions"in t&&typeof t.updateOptions=="function")t.updateOptions(e),m.info("Green screen options updated");else{const i=this._options.greenScreen||{enabled:!1},s={...i,...e,enabled:e.enabled!==void 0?e.enabled:i.enabled},r=new Li(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,m.info("Green screen processor recreated with new options")}}async initialize(){this.ensureNotDisposed();try{await this._videoSource.load();const e=this._videoSource.videoWidth,t=this._videoSource.videoHeight;e>0&&t>0&&this._pipelineRunner.setOutputSize(e,t),m.info("Video debugger initialized")}catch(e){throw m.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Debugger is already running");return}try{this._videoSource.videoWidth===0&&await this.initialize(),await this._videoSource.play(),this._videoSource.onFrame(e=>{this._pipelineRunner.processFrame(e).catch(t=>{m.error("Error processing frame:",t)})}),this._isRunning=!0,m.info("Video debugger started")}catch(e){throw m.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,m.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),m.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),m.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),m.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ma,D.DEFAULT_AUDIO_CHANNELS=xa,D.DEFAULT_AUDIO_SAMPLE_RATE=xi,D.DEFAULT_RECONNECT_ATTEMPTS=It,D.DEFAULT_RECONNECT_DELAY=Ni,D.DEFAULT_WS_TIMEOUT=Oa,D.Disposable=G,D.EventBus=ls,D.Logger=m,D.SDKClient=wa,D.SDKError=H,D.SessionState=us,D.StandaloneVideoDebugger=np,D.createClient=tp}));
147
+ `},jn}var Yo;function Pu(){if(Yo)return De;Yo=1;var n=Ru(),e=wu(),t=Vn();return De.grammar=t,De.write=e,De.parse=n.parse,De.parseParams=n.parseParams,De.parseFmtpConfig=n.parseFmtpConfig,De.parsePayloads=n.parsePayloads,De.parseRemoteCandidates=n.parseRemoteCandidates,De.parseImageAttributes=n.parseImageAttributes,De.parseSimulcastStreamList=n.parseSimulcastStreamList,De}var tt=Pu();function qn(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),b=this;return new Promise(function(v,R){var _=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var x=n.apply(b,f);o&&o(x),l.forEach(function(y){return(0,y.resolve)(x)}),l=[]}},u()),_){var A=n.apply(b,f);return o&&o(A),v(A)}l.push({resolve:v,reject:R})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(b){return(0,b.reject)(f)}),l=[]},h}const Iu=.7,Du=20,wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Xo extends xe.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=V,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=qn(s=>p(this,void 0,void 0,function*(){this.emit(wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Du),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=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new he}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=Au(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=tt.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Wn(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of a.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&a.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=tt.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(wt.NegotiationComplete),e.sdp&&tt.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(wt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);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 s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=tt.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ea(o),o.type==="audio"?Zo(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(Ie(c.codec)&&!dt()&&this.ensureVideoDDExtensionForSVC(o,a),!Ie(c.codec)))return!0;const l=Math.round(c.maxbr*Iu);for(const u of o.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,tt.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=tt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ea(s),s.type==="audio"&&Zo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,tt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new re("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new yt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Ao))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Ao})}}}function Zo(n,e,t){const i=Wn(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Au(n){var e;const t=[],i=[],s=tt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Wn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function ea(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Wn(n){return typeof n=="number"?n.toFixed(0):n}const Kn="vp8",Ou={audioPreset:yn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:_n.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Kn,backupCodec:!0,preConnectBuffer:!1},ta={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ia={deviceId:{ideal:"default"},resolution:jt.h720.resolution},Nu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ul,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Gn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class xu{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Gn.peerConnectionTimeout,this.log=V,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=te.CONNECTED:c.some(d=>d==="failed")?this.state=te.FAILED:c.some(d=>d==="connecting")?this.state=te.CONNECTING:c.every(d=>d==="closed")?this.state=te.CLOSED:c.some(d=>d==="closed")?this.state=te.CLOSING:c.every(d=>d==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new Xo(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new Xo(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=te.NEW,this.connectionLock=new he,this.remoteOfferLock=new he}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===we.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;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 a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=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(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new ue((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new yt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new yt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===we.PUBLISHER?this.publisher.getConnectedAddress():e===we.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,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),de.clearTimeout(u),d(F.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=de.setTimeout(()=>{s?.signal.removeEventListener("abort",l),d(F.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield le(50),s?.signal.aborted){d(F.cancelled("room connection has been cancelled"));return}de.clearTimeout(u),s?.signal.removeEventListener("abort",l),c()}))})()})}}const na=5e3,Mu=3e4;class z{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield z.fetchLock.lock();try{const r=yield fetch("".concat(Lu(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=ru(r.headers),o=a?a*1e3:na;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?F.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):F.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof F?r:i?.aborted?F.cancelled("Region fetching was aborted"):F.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=z.settingsTimeouts.get(e.hostname);clearTimeout(s),z.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield z.fetchRegionSettings(e,t);z.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof F&&r.reason===Q.NotAllowed){V.debug("token is not valid, cancelling auto region refresh");return}V.debug("auto refetching of region settings failed",{error:r}),z.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){z.cache.set(e.hostname,i),z.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=z.settingsTimeouts.get(e);t&&(clearTimeout(t),z.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=z.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=z.connectionTrackers.get(e);i&&i.connectionCount===0&&(V.debug("stopping region refetch after disconnect delay",{hostname:e}),z.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Mu))}static cancelCleanup(e){const t=z.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=z.connectionTrackers.get(e);t||(t={connectionCount:0},z.connectionTrackers.set(e,t)),t.connectionCount++,z.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=z.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&z.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return St(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return z.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=z.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),z.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),V.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){z.updateCachedRegionSettings(this.serverUrl,this.token,e)}}z.cache=new Map,z.settingsTimeouts=new Map,z.connectionTrackers=new Map,z.fetchLock=new he;function Lu(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ie extends Error{constructor(e,t,i){super(t),this.code=e,this.message=ra(t,ie.MAX_MESSAGE_BYTES),this.data=i?ra(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new cr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ie(ie.ErrorCode[e],ie.ErrorMessage[e],t)}}ie.MAX_MESSAGE_BYTES=256,ie.MAX_DATA_BYTES=15360,ie.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},ie.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 sa=15360;function Hn(n){return new TextEncoder().encode(n).length}function ra(n,e){if(Hn(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const zn=2e3;function Ri(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Jn=typeof MediaRecorder<"u";class Uu{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Fu=Jn?MediaRecorder:Uu;class Bu extends Fu{constructor(e,t){if(!Jn)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=c=>{s?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Vu(){return Jn}const ju=1e3,qu=1e4;class oa extends S{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),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=qn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(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(w.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new he,this.pauseUpstreamLock=new he,this.trackChangeLock=new he,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==S.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{kt(this._mediaStreamTrack,r)}),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 s;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&&(_t(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{_t(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ju;return(function*(){var i;if(e.kind===S.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=be())===null||i===void 0?void 0:i.os)==="iOS"&&(yield le(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield le(50)}throw new qe("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Qe(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Qe(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===S.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===S.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new qe("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=hl(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===S.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{kt(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===S.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(w.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.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 p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),No()&&(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 p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(w.UpstreamPaused,this);const i=be();if(i?.name==="Safari"&&Le(i.version,"12.0")<0)throw new bn("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(w.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(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 p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(_t(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(kt(i._mediaStreamTrack,d),_t(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(w.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(w.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Vu()){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 t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Bu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},qu)}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 wi extends oa{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,S.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Ri(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Qe(this._constraints.deviceId);return this.source===S.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=Sn({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ye()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},zn)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Me()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(w.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield wo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(w.AudioSilenceDetected)),e})}}function Wu(n,e,t){switch(n.kind){case"audio":return new wi(n,e,!1,void 0,t);case"video":return new Pi(n,e,!1,t);default:throw new qe("unsupported track type: ".concat(n.kind))}}const Ku=Object.values(jt),Gu=Object.values(Tn),Hu=Object.values(_n),zu=[jt.h180,jt.h360],Ju=[Tn.h180,Tn.h360],$u=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new $(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),$n=["q","h","f"];function Qn(n,e,t,i){var s,r;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);const o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Yu(n,e,t,d),V.debug("using video encoding",a));const l=a.maxFramerate,u=new $(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ie(d)){const b=new da(c),v=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=be();if(Kt()||Me()||R?.name==="Chrome"&&Le(R?.version,"113")<0){const _=b.suffix=="h"?2:3,A=zl(R);for(let x=0;x<b.spatial;x+=1)v.push({rid:$n[2-x],maxBitrate:a.maxBitrate/Math.pow(_,x),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:A?Math.pow(2,x):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),V.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];n?h=(s=ca(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:aa(n,u):h=(r=ca(i?.videoSimulcastLayers))!==null&&r!==void 0?r:aa(n,u);let f;if(h.length>0){const b=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return Yn(e,t,[b,f,u],l);if(v>=480)return Yn(e,t,[b,u],l)}return Yn(e,t,[u])}function Qu(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&V.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===S.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Qn(n.source===S.Source.ScreenShare,c,d,t)}function Yu(n,e,t,i){const s=Xu(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Xu(n,e,t){if(n)return Hu;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Ku:Gu}function aa(n,e){if(n)return $u(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?zu:Ju}function Yn(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=$n.length)return;const o=Math.min(n,e),d={rid:$n[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=ct()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Me()&&Mo()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,V.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),V.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ca(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class da{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Zu(n){return n.source===S.Source.ScreenShare||n.constraints.height&&Qe(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const eh=5e3;class Pi extends oa{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,S.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(w.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=Ri(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new he}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ye())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},zn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Te.LOW;i<=Te.HIGH;i+=1)t.push(new tn({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ie(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Sn({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=je(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=je(s.simulcastCodecs.values()),b;b=yield f.next(),a=b.done,!a;h=!0)d=b.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},eh))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Ie(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=je(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ie(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield la(u.sender,u.encodings,l.qualities,this.senderLock,Ie(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return p(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:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield la(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(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 t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ie(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),No()&&this.isInBackground&&this.source===S.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function la(n,e,t,i,s,r,a){return p(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var b;let v=(b=h.rid)!==null&&b!==void 0?b:"";v===""&&(v="q");const R=ua(v),_=t.find(A=>A.quality===R);_&&h.active!==_.enabled&&(l=!0,h.active=_.enabled,r.debug("setting layer ".concat(_.quality," to ").concat(h.active?"enabled":"disabled"),a),ct()&&(_.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function ua(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function ha(n,e,t,i){if(!t)return[new ze({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new da(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new ze({quality:Math.min(Te.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=ua((a=s.rid)!==null&&a!==void 0?a:"");return new ze({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const pa="_lossy",ma="_reliable",th=2*1e3,Xn="leave-reconnect",ih=3e4,nh=8*1024,sh=256*1024;var Ee;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ee||(Ee={}));class rh extends xe.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Gn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ee.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=V,this.reliableDataSequence=1,this.reliableMessageBuffer=new zo,this.reliableReceivedState=new Eu(ih),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===ma)r.reliableDCSub=a;else if(a.label===pa)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,a,o,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=pe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=rr.fromBinary(h.payload),b=new pe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=b.value)===null||o===void 0?void 0:o.case)==="user"&&fa(b,b.value.value),this.emit(P.DataPacketReceived,b,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&fa(u,u.value.value),this.emit(P.DataPacketReceived,u,se.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?j.LOSSY:j.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(P.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===Xn&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=de.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Ee.Connected&&i();const r=()=>{this.off(P.Disconnected,a),i()},a=()=>{this.off(P.Restarted,r),s()};this.once(P.Restarted,r),this.once(P.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===j.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(P.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(Ht(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Y.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Y.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(rt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ht(this.url),{method:"HEAD"}),le(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ve((t=e.loggerName)!==null&&t!==void 0?t:Pe.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Un(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new he,this.dataProcessLock=new he,this.dcBufferStatus=new Map([[j.LOSSY,!0],[j.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(P.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(P.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(P.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(P.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(P.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(P.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(P.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,a,o,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{V.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(P.SignalConnected,u),u}catch(u){if(u instanceof F){if(u.reason===Q.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,a,o,c,l)}else if(u.reason===Q.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return p(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(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new zo,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 p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(F.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(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,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==te.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new xu(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(P.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,c)=>p(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===te.CONNECTED){const u=this.pcState===Ee.New;this.pcState=Ee.Connected,u&&this.emit(P.Connected,e)}else a===te.FAILED&&(this.pcState===Ee.Connected||this.pcState===Ee.Reconnecting)&&(this.pcState=Ee.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?rt.RR_SUBSCRIBER_FAILED:rt.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Y.RECONNECTING,l=[te.FAILED,te.CLOSING,te.CLOSED].includes(a);d&&l&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(P.MediaTrackAdded,a.track,a.streams[0],a.receiver)},oh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(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,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",rt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:na,regionSettings:e.regions})),e.action){case vt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close();break;case vt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Xn);break;case vt.RESUME:this.handleDisconnect(Xn)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Lt.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(pa,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ma,{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(j.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,nh),sh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(En())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Rn())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(En())return this.createSimulcastTransceiverSender(e,t,i,s);if(Rn())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Ye(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){V.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Lt.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Tt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",rt.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(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Tt;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof F&&a.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):new Tt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new Tt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");if(!this.pcManager)throw new re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof F&&s.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof F&&s.reason===Q.LeaveRequest?s:new Tt(r)}if(this.emit(P.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),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!==Y.CONNECTED)throw new Tt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Ee.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(th),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ee.Connected}catch(e){throw this.pcState=Ee.Disconnected,F.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Ji({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new zi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=mu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new sr({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}t===j.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===j.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){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;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(j.RELIABLE);const t=this.dataChannelForKind(j.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(j.RELIABLE)})}waitForBufferStatusLow(e){return new ue((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new re("engine closed"));for(this.once(P.Closing,s);!this.dcBufferStatus.get(e);)yield le(10);this.off(P.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new re("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw F.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{V.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if(d?.readyState==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield le(50)}throw F.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==te.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new ue((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new yt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new yt("cannot negotiate on closed engine")),this.on(P.Closing,s),this.pcManager.publisher.once(wt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();Xl(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof yt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",rt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(P.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===j.LOSSY)return this.lossyDCSub;if(e===j.RELIABLE)return this.reliableDCSub}else{if(e===j.LOSSY)return this.lossyDC;if(e===j.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(a=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(b=>{b.isDesired!==u&&h.push(b.trackSid),b.isEnabled||f.push(b.trackSid)}),this.client.sendSyncState(new nn({answer:this.pcManager.mode==="publisher-only"?c?Rt({sdp:c.sdp,type:c.type}):void 0:l?Rt({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?Rt({sdp:o.sdp,type:o.type}):void 0:d?Rt({sdp:d.sdp,type:d.type}):void 0,subscription:new pi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ml(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((b,v)=>new Ir({publisherSid:v,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Dr({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),we.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),we.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),we.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),we.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&de.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ye()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ye()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[a]=r;return a===i});if(s)return s[1]}}}function oh(n){return n!==void 0&&n>13}function fa(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class ga{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 Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),me.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),me.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class ah extends ga{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Ce,i=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),i=a}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:d}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class ch extends ga{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ei(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Ce,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,c;try{const{done:d,value:l}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Se("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),me.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw a(),d}}),return(){return p(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class dh{constructor(){this.log=V,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),me.AbnormalEnd);for(const[d,l]of o)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of a)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ei(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new ah(c,d,Ei(e.totalLength),o),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={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,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new ch(c,d,Ei(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class va{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(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 lh extends va{}class uh extends va{}const ba=15e3;class hh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const b=c.reduce((v,R)=>v+R,0);(f=t?.onProgress)===null||f===void 0||f.call(t,b)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),d(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?se.GCM:se.NONE,attachedStreamIds:e?.attachedStreamIds},o=new ci({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:lt(a.timestamp),totalLength:lt(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new vr({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?$i.UPDATE:$i.CREATE})}}),c=e?.destinationIdentities,d=new pe({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,j.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(v){return p(this,void 0,void 0,function*(){for(const R of su(v,ba)){const _=new di({content:R,streamId:r,chunkIndex:lt(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:_}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const v=new li({streamId:r}),R=new pe({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(R,j.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>p(this,void 0,void 0,function*(){yield b.close()});u.once(P.Closing,f);const b=new lh(h,a,()=>this.engine.off(P.Closing,f));return b})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o;const c=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:c,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?se.GCM:se.NONE},u=new ci({totalLength:lt((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:lt(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new br({name:l.name})}}),h=new pe({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,j.RELIABLE);let f=0;const b=new he,v=this.engine,R=this.log,_=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const y=yield b.lock();let T=0;try{for(;T<x.byteLength;){const C=x.slice(T,T+ba),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new di({content:C,streamId:c,chunkIndex:lt(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,T+=C.byteLength}}finally{y()}})},close(){return p(this,void 0,void 0,function*(){const x=new li({streamId:c}),y=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(y,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new uh(_,l)})}}class ya extends S{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(w.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(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(),zn)),Ll()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(w.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class ph extends ya{constructor(e,t,i,s,r,a){super(e,t,S.Kind.Audio,i,a),this.monitorReceiver=()=>p(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=Ri(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Me()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Me())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(wn(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&wn(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),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(w.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(w.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const Zn=100;class mh extends ya{constructor(e,t,i,s,r){super(e,t,S.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Ri(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=qn(()=>{this.updateDimensions()},Zn),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===S.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?kt(this._mediaStreamTrack,t):_t(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new fh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<Zn){de.setTimeout(()=>{this.updateVisibility()},Zn);return}this.lastVisible=o,this.emit(w.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(w.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Lo():t||(Lo()>2?2:1)}}class fh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=$t(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=$t(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=$t(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??es(e),this.isPiP=ye()&&$t(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=es(this.element),this.isPiP=$t(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Fo().observe(this.element),Uo().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Fo())===null||e===void 0||e.unobserve(this.element),(t=Uo())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function $t(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?es(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function es(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class Ke extends xe.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=se.NONE,this.log=V,this.handleMuted=()=>{this.emit(w.Muted)},this.handleUnmuted=()=>{this.emit(w.Unmuted)},this.log=Ve((r=s?.loggerName)!==null&&r!==void 0?r:Pe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=S.Source.Unknown}setTrack(e){this.track&&(this.track.off(w.Muted,this.handleMuted),this.track.off(w.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(w.Muted,this.handleMuted),e.on(w.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),W(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==se.NONE}get audioTrack(){if(Ue(this.track))return this.track}get videoTrack(){if(Ye(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=S.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===S.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ke||(Ke={}));class ts extends Ke{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(w.Ended)},this.handleCpuConstrained=()=>{this.track&&Ye(this.track)&&this.emit(w.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(w.Ended,this.handleTrackEnded),this.track.off(w.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(w.Ended,this.handleTrackEnded),e.on(w.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 p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ue(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ae.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ae.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ae.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ae.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ae.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ae.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Ii(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Io(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Ro(r,ta,ia),d=Sn(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ce.userMediaPromiseMap.set("audioinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("audioinput"))),r.video&&(ce.userMediaPromiseMap.set("videoinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let b=f?c.audio:c.video;(typeof b=="boolean"||!b)&&(b={});let v;const R=f?d.audio:d.video;typeof R!="boolean"&&(v=R);const _=h.getSettings().deviceId;v?.deviceId&&Qe(v.deviceId)!==_?v.deviceId=_:v||(v={deviceId:_});const A=Wu(h,v,e);return A.kind===S.Kind.Video?A.source=S.Source.Camera:A.kind===S.Kind.Audio&&(A.source=S.Source.Microphone),A.mediaStream=u,Ue(A)&&i?yield A.setProcessor(i):Ye(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return Ii(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function gh(n){return p(this,void 0,void 0,function*(){return(yield Ii({audio:!1,video:!0}))[0]})}function vh(n){return p(this,void 0,void 0,function*(){return(yield Ii({audio:!0,video:!1}))[0]})}var it;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(it||(it={}));function bh(n){switch(n){case Mt.EXCELLENT:return it.Excellent;case Mt.GOOD:return it.Good;case Mt.POOR:return it.Poor;case Mt.LOST:return it.Lost;default:return it.Unknown}}class Ta extends xe.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ut.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===ft.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ut.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=it.Unknown,this.log=V,this.log=Ve((c=a?.loggerName)!==null&&c!==void 0?c:Pe.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ce,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(S.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(S.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(S.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ft.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==ft.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=Ul(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(I.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=bh(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ue(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(w.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(w.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case S.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case S.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function yh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new wr({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Th extends Ta{constructor(e,t,i,s,r,a){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=se.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ce)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,d,l,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,d;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:d,message:l}=o,u=this.pendingSignalRequests.get(c);u&&(d!==sn.OK&&u.reject(new Co(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ie.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>yh(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),W(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),W(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),W(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),W(c))),this.emit(I.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,R=je(b),_;_=yield R.next(),c=_.done,!c;v=!0){u=_.value,v=!1;const A=u;Ol(A)&&(this.log.debug("publish ".concat(A," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),W(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,A,f.options))}}catch(A){d={error:A}}finally{try{!v&&!c&&(l=R.return)&&(yield l.call(R))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===S.Source.ScreenShare||o.source===S.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),W(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(We(o)||Xe(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===S.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),W(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),W(o))),We(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),W(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==se.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse).on(P.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:b=>{c(b),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(b=>{let[v,R]=b;return this.attributes[v]===R||R===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield le(50)}c(new Co("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(S.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(S.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(S.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?se.GCM:se.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d?.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case S.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case S.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case S.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new qe(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,Cn(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===S.Source.Microphone&&Ue(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),W(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c?.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===S.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(S.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(S.Source.Camera)||this.pendingPublishing.has(S.Source.Microphone))){this.pendingPublishing.add(S.Source.Camera),this.pendingPublishing.add(S.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(S.Source.Camera),this.pendingPublishing.delete(S.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Ro(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Ii(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Ue(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=S.Source.Microphone,this.emit(I.AudioStreamAcquired)),Ye(o)&&(this.cameraError=void 0,o.source=S.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new bn("getDisplayMedia not supported");e.resolution===void 0&&!Hl()&&(e.resolution=_n.h1080fps30.resolution);const t=xl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new qe("no video track found");const r=new Pi(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=S.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new wi(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=S.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,d,l;We(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Ct(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let _;switch(i.source){case S.Source.Microphone:_="audioinput";break;case S.Source.Camera:_="videoinput"}_&&r.activeDeviceMap.has(_)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(_)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new wi(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Pi(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(_=>{_.track&&_.track===i&&(h=_)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),W(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:b;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),W(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!Jl()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const R=new Promise((_,A)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Y.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:W(i)}));let x=!1;const y=setTimeout(()=>{x=!0,i.stop(),A(new So("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),x)return;const T=yield this.publish(i,f,v);_(T)}else try{const x=yield this.publish(i,f,v);_(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(_){throw _}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),W(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Fl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),W(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new So("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Ct(e)&&M.source===e.source)&&e.source!==S.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),W(e))),t.stopMicTrackOnMute&&Ue(e)&&(e.stopOnMute=!0),e.source===S.Source.ScreenShare&&ct()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Wl()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Kl()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Kn),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===qt(M.mime))||(t.videoCodec=qt(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(w.Muted,this.onTrackMuted),e.on(w.Unmuted,this.onTrackUnmuted),e.on(w.Ended,this.handleTrackEnded),e.on(w.UpstreamPaused,this.onTrackUpstreamPaused),e.on(w.UpstreamResumed,this.onTrackUpstreamResumed),e.on(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const R=[],_=!(!((s=t.dtx)!==null&&s!==void 0)||s),A=e.getSourceTrackSettings();A.autoGainControl&&R.push(ae.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&R.push(ae.TF_ECHO_CANCELLATION),A.noiseSuppression&&R.push(ae.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&R.push(ae.TF_STEREO),_&&R.push(ae.TF_NO_DTX),We(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new Ft({cid:e.mediaStreamTrack.id,name:t.name,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),disableDtx:_,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:R});let y;if(e.kind===S.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const L=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:jt.h720.resolution;M={width:L.width,height:L.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{dims:M}))}x.width=M.width,x.height=M.height,Xe(e)&&(Ie(v)&&(e.source===S.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),W(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),x.simulcastCodecs=[new Yi({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Kn}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Yi({codec:t.backupCodec.codec,cid:""})))),y=Qn(e.source===S.Source.ScreenShare,x.width,x.height,t),x.layers=ha(x.width,x.height,y,Ie(t.videoCodec))}else e.kind===S.Kind.Audio&&(y=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const T=()=>p(this,void 0,void 0,function*(){var M,O,L;if(!this.engine.pcManager)throw new re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(I.LocalSenderCreated,e.sender,e),Xe(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=Zu(e)),e.setDegradationPreference(t.degradationPreference)),y)if(ct()&&e.kind===S.Kind.Audio){let q;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){q=Z;break}q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:q,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Ie(e.codec)&&(!((L=y[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const N=new Promise((M,O)=>p(this,void 0,void 0,function*(){var L;try{C=yield this.engine.addTrack(x),M(C)}catch(q){e.sender&&(!((L=this.engine.pcManager)===null||L===void 0)&&L.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{error:Z}))})),O(q)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([N,T()]))[0];else{C=yield N;let M;if(C.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===S.Kind.Video){const O=qt(M);O!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{codec:O})),t.videoCodec=O,y=Qn(e.source===S.Source.ScreenShare,x.width,x.height,t))}yield T()}const U=new ts(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(U.on(w.CpuConstrained,M=>this.onTrackCpuConstrained(M,U)),U.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:C})),Xe(e)?e.startMonitor(this.engine.client):We(e)&&e.startMonitor(),this.addTrackPublication(U),this.emit(I.LocalTrackPublished,U),We(e)&&C.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,L=>{if(L.trackSid===C.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),W(e))),e.stopPreConnectBuffer()}}),M&&new Promise((q,Z)=>p(this,void 0,void 0,function*(){var _e,ut,ge,st,ns,ss;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),W(e)));const cs=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),sp=yield this.waitUntilActiveAgentPresent();clearTimeout(cs),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),W(e)));const Ia=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[sp.identity],attributes:{trackId:U.trackSid,sampleRate:String((ns=A.sampleRate)!==null&&ns!==void 0?ns:"48000"),channels:String((ss=A.channelCount)!==null&&ss!==void 0?ss:"1")}});try{for(var rs=!0,os=je(M),as;as=yield os.next(),_e=as.done,!_e;rs=!0){st=as.value,rs=!1;const ds=st;yield Ia.write(ds)}}catch(ds){ut={error:ds}}finally{try{!rs&&!_e&&(ge=os.return)&&(yield ge.call(os))}finally{if(ut)throw ut.error}}yield Ia.close(),q()}catch(cs){Z(cs)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),W(e)))}).catch(q=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{error:q}))})}return U})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==se.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new qe("track is not published");if(!Xe(e))throw new qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Qu(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),W(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ft({cid:c.mediaStreamTrack.id,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ha(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(Ct(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),W(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?W(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(w.Muted,this.onTrackMuted),e.off(w.Unmuted,this.onTrackUnmuted),e.off(w.Ended,this.handleTrackEnded),e.off(w.UpstreamPaused,this.onTrackUpstreamPaused),e.off(w.UpstreamResumed,this.onTrackUpstreamResumed),e.off(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Xe(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case S.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case S.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(I.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ue((r,a)=>p(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==S.Source.ScreenShare&&d.source!==S.Source.ScreenShareAudio&&(We(d)||Xe(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?j.RELIABLE:j.LOSSY,a=s.destinationIdentities,o=s.topic;let c=new Gi({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o});const d=new pe({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new ar({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new pe({value:{case:"chatMessage",value:new ai(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new pe({value:{case:"chatMessage",value:new ai(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const a=7e3,o=a+1e3;return new ue((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(Hn(s)>sa){d(ie.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&Le((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ie.builtIn("UNSUPPORTED_SERVER"));return}const b=Math.max(r,o),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,i,s,b);const R=setTimeout(()=>{this.pendingAcks.delete(v),d(ie.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(_)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const _=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(_),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(R)),x?d(x):c(A??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Hi({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,j.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ie.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),W(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ce),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(We(s)||Xe(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield le(20)}})}}class _h extends Ke{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(w.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new pi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new dr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(w.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ke.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ke.SubscriptionStatus.Subscribed:Ke.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ke.PermissionStatus.Allowed:Ke.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 t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Nn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Nn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Te.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(w.VisibilityChanged,this.handleVisibilityChange),s.off(w.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(w.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(w.VisibilityChanged,this.handleVisibilityChange),e.on(w.Ended,this.handleEnded),this.emit(w.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(w.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?w.Muted:w.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(w.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(w.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 Nn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Sr({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===S.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Do(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Bl(this.trackInfo,this.requestedMaxQuality);i&&Do(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.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:Te.HIGH})),e.quality=Te.HIGH)}this.emit(w.UpdateSettings,e)}}class Di extends Ta{static fromParticipantInfo(e,t,i){return new Di(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ut.STANDARD;super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(w.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(w.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(w.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(w.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(w.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(w.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(w.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:S.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:S.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),W(o))),this.emit(I.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new mh(e,t,s,r):d=new ph(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&On(d)&&Ue(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=S.kindFromProto(s.type);if(!c)return;o=new _h(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==S.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:W(d),newTrack:W(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),W(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(I.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case S.Kind.Audio:this.audioTrackPublications.delete(e);break;case S.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Ue(i.track)&&On(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var J;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(J||(J={}));const kh=4*1e3;class Pt extends xe.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=J.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=V,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,d)=>p(this,void 0,void 0,function*(){var l;if(!Gl())throw Me()?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===J.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(J.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==jo(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),St(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new z(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(b=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(b)}).catch(b=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:b}))}));const h=(b,v,R)=>p(this,void 0,void 0,function*(){var _,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Et.getInstance().getBackOffPromise(o),x.signal.aborted)throw F.cancelled("Connection attempt aborted");yield this.attemptConnection(R??o,c,d,x),this.abortController=void 0,b()}catch(y){if(this.regionUrlProvider&&y instanceof F&&y.reason!==Q.Cancelled&&y.reason!==Q.NotAllowed){let T=null;try{this.log.debug("Fetching next region"),T=yield this.regionUrlProvider.getNextBestRegionUrl((_=this.abortController)===null||_===void 0?void 0:_.signal)}catch(C){if(C instanceof F&&(C.status===401||C.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(C);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(y.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Et.getInstance().addFailedConnectionAttempt(o)),T&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(T),this.logContext),this.recreateEngine(),yield h(b,v,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vo(y)),v(y))}else{let T=ke.UNKNOWN_REASON;y instanceof F&&(T=Vo(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),v(y)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ce((b,v)=>{h(b,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,b,v;const R=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let _=R.serverInfo;if(_||(_={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=_,this.log.debug("connected to Livekit Server ".concat(Object.entries(_).map(A=>{let[x,y]=A;return"".concat(x,": ").concat(y)}).join(", ")),{room:(f=R.room)===null||f===void 0?void 0:f.name,roomSid:(b=R.room)===null||b===void 0?void 0:b.sid,identity:(v=R.participant)===null||v===void 0?void 0:v.identity}),!_.version)throw new wl("unknown server version");return _.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),R}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===J.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(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Gn),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const b=l.signal.aborted?F.cancelled("Signal connection aborted"):F.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(b.message="".concat(b.message,": ").concat(f.message)),f instanceof F&&(b.reason=f.reason,b.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),b}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),F.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}ye()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ye()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(J.Connected),this.emit(E.Connected),Et.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,b;const v=yield l.disconnectLock.lock();try{if(l.state===J.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===J.Connecting||l.state===J.Reconnecting||l.isResuming){const R="Abort connection attempt due to user initiated disconnect";l.log.warn(R,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(R),(b=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||b===void 0||b.call(f,F.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,ke.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],c=be();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=An();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(E.Disconnected,()=>{l?.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.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(J.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>p(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(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}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(J.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===ft.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(E.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(E.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=S.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(I.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const d=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(d,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(d,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(d,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(d,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,d);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const l=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(o,c,d,l)=>{this.emit(E.DataReceived,c.payload,o,d,c.topic,l),o?.emit(I.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(E.SipDTMFReceived,c,o),o?.emit(I.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d?.trackPublications.get(c.trackId),u=eu(c,this.transcriptionReceivedTimes);l?.emit(w.TranscriptionReceived,u),d?.emit(I.TranscriptionReceived,u,l),this.emit(E.TranscriptionReceived,u,d,l)},this.handleChatMessage=(o,c)=>{const d=tu(c);this.emit(E.ChatMessage,d,o)},this.handleMetrics=(o,c)=>{this.emit(E.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.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(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o;((o=be())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(E.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(E.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(E.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(E.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(E.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(w.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(E.LocalTrackPublished,o,this.localParticipant),We(o.track)&&(yield o.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,o);const b=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=Cn(o.source);v&&b&&b!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,b),this.emit(E.ActiveDeviceChanged,v,b))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(w.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=Cn(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(E.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(E.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(E.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(E.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(E.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Nu),e),this.log=Ve((i=this.options.loggerName)!==null&&i!==void 0?i:Pe.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ta),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ia),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ou),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new dh,this.outgoingDataStreamManager=new hh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new Th("","",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",Qe(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Qe(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Qe(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ye()){const o=new AbortController;(a=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||a===void 0||a.call(r,"devicechange",this.handleDeviceChange,{signal:o.signal}),Pt.cleanupRegistry&&Pt.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(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 t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new fu(i,t),this.e2eeManager.on(et.ParticipantEncryptionStatusChanged,(s,r)=>{nu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(et.EncryptionError,(s,r)=>{const a=r?this.getParticipantByIdentity(r):void 0;this.emit(E.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===J.Disconnected?ue.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ue.resolve(this.roomInfo.sid):new ue((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(P.RoomUpdate,i),e(s.sid))};this.engine.on(P.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(P.RoomUpdate,i),t(new re("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new rh(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(J.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(J.Connected)&&this.emit(E.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===J.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(I.LocalTrackSubscribed,t),this.emitWhenConnected(E.LocalTrackSubscribed,t,this.localParticipant)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(E.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 t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ce.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===J.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(St(new URL(e))&&t){this.regionUrlProvider=new z(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===J.Disconnected&&(this.regionUrl=i,yield fetch(Ht(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ht(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ne({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ne({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ne({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ne({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=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({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":s=new Ne({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new mi({reason:ke.CLIENT_INITIATED,action:vt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ne({scenario:{case:"subscriberBandwidth",value:lt(t)}});break;case"leave-full-reconnect":s=new Ne({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let b=!0,v=!1;const R=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const _=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===S.Source.Microphone);try{b=(yield Promise.all(A.map(y=>{var T;return(T=y.audioTrack)===null||T===void 0?void 0:T.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=_,y}const x=A.some(y=>{var T,C;return(C=(T=y.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const _=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===S.Source.Camera);try{b=(yield Promise.all(A.map(y=>{var T;return(T=y.videoTrack)===null||T===void 0?void 0:T.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=_,y}const x=A.some(y=>{var T,C;return(C=(T=y.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!wn()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield ce.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const _=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(A=>A.setAudioOutput({deviceId:s})))}catch(A){throw r.options.audioOutput.deviceId=_,A}}return v&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(E.ActiveDeviceChanged,i,s)),b})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===J.Connecting||this.state===J.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(E.Reconnected,u),this.off(E.Connected,u),this.off(E.Disconnected,h)};this.once(E.Reconnected,u),this.once(E.Connected,u),this.once(E.Disconnected,h);return}if(this.state===J.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 s=ql(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}o=u}o.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(r,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:a,trackId:o}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,o,t,i,d);l?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==J.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,c;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()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.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),ye()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(J.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,a){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Hn(l)>sa?(c=ie.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ie?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ie.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=be();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=Nl(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Kt()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Kt())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Po())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),le(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Di.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Di(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(I.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(I.TrackSubscribed,(s,r)=>{s.kind===S.Kind.Audio?(s.on(w.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(w.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===S.Kind.Video&&(s.on(w.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(w.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(I.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(I.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(I.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(I.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(I.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(I.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(I.AttributesChanged,s=>{this.emitWhenConnected(E.ParticipantAttributesChanged,s,i)}).on(I.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(I.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(I.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(I.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(I.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}).on(I.Active,()=>{this.emitWhenConnected(E.ParticipantActive,i),i.kind===Ut.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&iu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=de.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,ke.STATE_MISMATCH))):e=0},kh)}clearConnectionReconcile(){this.connectionReconcileInterval&&de.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===J.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===J.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ri({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ot({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(J.Connected),a.video){const c=new ts(S.Kind.Video,new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO,name:"video-dummy"}),new Pi(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Bo(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}if(a.audio){const c=new ts(S.Kind.Audio,new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO}),new wi(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:An(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new ot({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:ft.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=Bo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=An(),h=new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const r=_a(i).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Pt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function _a(n){return n.map(e=>{if(e)return Array.isArray(e)?_a(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ae;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Ae||(Ae={}));class nt extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ae.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Pt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Ae.IDLE)throw Error("check is running already");this.setStatus(Ae.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Ae.SKIPPED&&this.setStatus(this.isSuccess()?Ae.SUCCESS:Ae.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===J.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==J.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ae.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield le(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 Sh extends nt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new z(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let b=0;b<c;b++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h?.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(f.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const is=1e4;class Ch extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(is/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(is/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,is)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Eh extends nt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield vh();if(yield wo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const 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==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class Rh extends nt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield gh();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const v=f.getImageData(0,0,d.width,d.height).data;let R=!0;for(let _=0;_<v.length;_+=4)if(v[_]!==0||v[_+1]!==0||v[_+2]!==0){R=!1;break}R?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class wh extends nt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==J.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 Ph extends nt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;St(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new z(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new Un,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Ih extends nt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Dh(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),V.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Dh(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Ah extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new Un,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(St(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new z(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===ur.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class ap extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Ae.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Ae.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ah)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ih)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ph)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(wh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Eh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Rh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Ch);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Sh)})}}function K(n,e,t){return(e=Nh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Oh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Nh(n){var e=Oh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class fe extends Error{constructor(e,t){var i;super(e,t),K(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}K(fe,"code","ERR_JOSE_GENERIC");class xh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),K(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),K(this,"claim",void 0),K(this,"reason",void 0),K(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}K(xh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Mh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),K(this,"code","ERR_JWT_EXPIRED"),K(this,"claim",void 0),K(this,"reason",void 0),K(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}K(Mh,"code","ERR_JWT_EXPIRED");class Lh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}K(Lh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Uh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_NOT_SUPPORTED")}}K(Uh,"code","ERR_JOSE_NOT_SUPPORTED");class Fh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWE_DECRYPTION_FAILED")}}K(Fh,"code","ERR_JWE_DECRYPTION_FAILED");class Bh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWE_INVALID")}}K(Bh,"code","ERR_JWE_INVALID");class Vh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWS_INVALID")}}K(Vh,"code","ERR_JWS_INVALID");class jh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWT_INVALID")}}K(jh,"code","ERR_JWT_INVALID");class qh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWK_INVALID")}}K(qh,"code","ERR_JWK_INVALID");class Wh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWKS_INVALID")}}K(Wh,"code","ERR_JWKS_INVALID");class Kh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}K(Kh,"code","ERR_JWKS_NO_MATCHING_KEY");class Gh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,Symbol.asyncIterator,void 0),K(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}K(Gh,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Hh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWKS_TIMEOUT")}}K(Hh,"code","ERR_JWKS_TIMEOUT");class zh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}K(zh,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var ka;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(ka||(ka={}));var Sa;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Sa||(Sa={}));var Ca;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Ca||(Ca={}));var Ai;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Ai||(Ai={})),Ai.UserTimestamp,Ai.E2ee;var Ea;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Ea||(Ea={}));class Jh extends G{constructor(e){super(),this._room=null,this._context=e,this._trackRegistry=new Tc,this._eventAdapter=new _c(e,this._trackRegistry),this._maxAttempts=e.options.reconnect?.maxAttempts||It,this._maxDelay=(e.options.reconnect?.delay??Ni)*Dt,m.info("LiveKit Service created")}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._room&&this._room.isConnected()){m.warn("Already connected to LiveKit room");return}try{m.info(`Connecting to LiveKit room: ${i} at ${e}`);const r=new Pt({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(Dt*Math.pow(2,a.retryCount),this._maxDelay):null}});r.prepareConnection(e,t),r.on(E.TrackSubscribed,(a,o,c)=>{this._handleTrackSubscribed(a,o,c)}),r.on(E.TrackUnsubscribed,(a,o,c)=>{this._handleTrackUnsubscribed(a,o,c)}),r.on(E.TrackMuted,(a,o)=>{this._handleTrackMuted(a,o)}),r.on(E.TrackUnmuted,(a,o)=>{this._handleTrackUnmuted(a,o)}),r.on(E.Connected,()=>{m.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),r.on(E.Disconnected,a=>{a?m.info(`LiveKit room disconnected: ${a}`):m.info("LiveKit room disconnected"),a!==ke.CLIENT_INITIATED&&this._context.eventBus.emit("inner:rtc:disconnected",{reason:a?String(a):void 0}),this._room=null}),m.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||It}),this._eventAdapter.setRoom(r),this._room=r}catch(r){throw H.fromError(r,B.LIVEKIT_CONNECT_FAILED)}}_handleTrackSubscribed(e,t,i){try{if(!e.mediaStreamTrack){m.warn("Track does not have MediaStreamTrack");return}e.kind==="audio"&&i.on(I.IsSpeakingChanged,o=>{console.log("\u8F68\u9053 \u8BF4\u8BDD\u72B6\u6001:",o)});const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){m.error("Error handling track subscribed:",s)}}_handleTrackUnsubscribed(e,t,i){try{const s=t,r=i,a=s.trackSid,o=r.identity;this._trackRegistry.getTrack(a)?.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0),this._eventAdapter.handleTrackUnsubscribed(a,o)}catch(s){m.error("Error handling track unsubscribed:",s)}}_handleTrackMuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)}catch(i){m.error("Error handling track muted:",i)}}_handleTrackUnmuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:available",void 0)}catch(i){m.error("Error handling track unmuted:",i)}}async disconnect(){if(this._room)try{await this._room.disconnect(),this._room=null,this._context.eventBus.emit("inner:rtc:disconnected",{reason:"Disconnected from LiveKit room"}),m.info("Disconnected from LiveKit room")}catch(e){m.error("Error disconnecting from LiveKit room:",e),this._room=null}}isConnected(){return this._room?this._room.state===J.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),m.info("LiveKit Service disposed")}}class $h extends G{constructor(e){super(),this._conversationManager=null,this._context=e,m.info("WebSocket Dispatcher created")}setConversationManager(e){this._conversationManager=e,m.debug("Conversation manager set in dispatcher")}dispatch(e){this.ensureNotDisposed();try{if(e.type==="ws"){this._handleWSServerMessage(e);return}if(e.type==="text"){this._handleServerTextMessage(e);return}}catch(t){m.error("Error dispatching message:",t)}}_handleWSServerMessage(e){e.code===101?(this._conversationManager?.handleServerPong(),m.debug("Received pingpong response")):e.code===102&&(m.warn("Server will disconnect"),this._conversationManager?.willDisconnect())}_handleServerTextMessage(e){if(!this._conversationManager){m.warn("Conversation manager not set, text message ignored");return}const{uid:t,payload:i,code:s}=e;s===200?(this._conversationManager.handleAnswerChunk(t,i,!1),m.debug(`Answer received (code 401) for uid: ${t}`)):s===201?(this._conversationManager.handleAnswerChunk(t,"",!0),m.debug(`Answer completed (code 411) for uid: ${t}`)):s===300?(this._conversationManager.handleAsrTextReceived(t,i),m.debug(`ASR text chunk received (code 410) for uid: ${t}`)):s===400&&(this._conversationManager.handleServerInitiatedMessage(t,i),m.debug(`Server initiated message received (code 412) for uid: ${t}`))}onDispose(){m.info("WebSocket Dispatcher disposed")}}class Qh extends G{constructor(e){super(),this._ws=null,this._dispatcher=null,this._isConnecting=!1,this._activeTimers=new Set,this._retryCount=0,this._maxRetries=It,this._pingTimer=void 0,this._pongTimer=void 0,this._isExplicitDisconnect=!1,this._context=e,this._maxRetries=e.options.reconnect?.maxAttempts??It,this._maxDelay=(e.options.reconnect?.delay??Ni)*Dt,this._dispatcher=new $h(e)}setConversationManager(e){this._dispatcher&&this._dispatcher.setConversationManager(e)}async connect(){if(this.ensureNotDisposed(),this._stopHeartbeat(),!(this._isConnecting||this.isConnected||this._ws?.readyState===WebSocket.OPEN)){this._isConnecting=!0,this._isExplicitDisconnect=!1;try{return this._ws=new WebSocket(this._context.wsUrl),new Promise((e,t)=>{this._ws.onopen=()=>{this._isConnecting=!1,this._retryCount=0,this.sendPing(),this._context.eventBus.emit("inner:ws:connected",void 0),m.info("Conversation transport connected"),e()},this._ws.onerror=i=>{this._isConnecting=!1,m.error("Conversation transport error:",i),this._context.eventBus.emit("inner:sdk:error",{error:new H("WebSocket connection error",B.WS_CONNECT_ERROR,i)}),t(new H("WebSocket connection error",B.WS_CONNECT_ERROR,i))},this._ws.onclose=i=>{const s=i.code,r=i.reason?i.reason:i.wasClean?"Clean close":"Closed by remote";this._handleDisconnect(s,r)},this._ws.onmessage=i=>{this._handleMessage(i.data)}})}catch(e){throw this._isConnecting=!1,this._context.emitError(e,B.WS_CONNECT_FAILED)}}}disconnect(){this._isExplicitDisconnect=!0,this._stopHeartbeat(),this._ws&&(this._ws.close(),this._ws=null),this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client disconnect"}),m.info("Conversation transport disconnected")}_handleDisconnect(e,t){if(this._stopHeartbeat(),this._isConnecting=!1,e!==void 0&&new Set([1e3,1001,1002,1003,1007,1008]).has(e)){this._isExplicitDisconnect=!0;const s=`WebSocket closed (code ${e}): ${t??""}`;this._context.eventBus.emit("inner:ws:disconnected",{reason:s}),m.info(`Conversation transport closed with non-retry code ${e}: ${t??""}`);return}if(!this._isExplicitDisconnect&&this._retryCount<this._maxRetries){this._retryCount++;const s=Math.min(Dt*Math.pow(2,this._retryCount-1),this._maxDelay);m.warn(`Connection lost. Retry ${this._retryCount} in ${s}ms`);const r=setTimeout(()=>{!this._isExplicitDisconnect&&!this.isDisposed&&this.connect().catch(()=>{})},s);this._registerTimer(r)}else this._context.eventBus.emit("inner:ws:disconnected",{reason:"Closed"})}_registerTimer(e){return this._activeTimers.add(e),e}_clearTimer(e){e&&(clearTimeout(e),this._activeTimers.delete(e))}sendPing(){if(!this.isConnected)return;const e={type:"ws",code:101,payload:"ping"};this._ws?.send(JSON.stringify(e)),clearTimeout(this._pongTimer),this._pongTimer=setTimeout(()=>{m.error(`Pong timeout (${hs/Dt}s). Reconnecting...`),this._ws?.close()},hs)}handlePongReceived(){clearTimeout(this._pongTimer),this._clearTimer(this._pingTimer),this._pingTimer=setTimeout(()=>{this.sendPing()},Na)}willDisconnect(){if(this.ensureNotDisposed(),this._ws&&this._ws.readyState===WebSocket.OPEN){const t=JSON.stringify({type:"ws",code:102,payload:"will disconnect"});this._ws.send(t),this._isExplicitDisconnect=!0,this._ws.close(),this._ws=null,this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client responsive to server's disconnect message."})}}sendText(e,t,i=200,s){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN)throw new H("WebSocket is not connected",B.WS_NOT_CONNECTED);try{const a=JSON.stringify({type:"text",code:i,uid:e,metadata:s,payload:t});this._ws.send(a),m.debug("Text message sent via transport:",e)}catch(r){throw this._context.emitError(r,B.WS_TEXT_SEND_FAILED)}}_handleMessage(e){try{if(typeof e!="string")return;const t=JSON.parse(e);m.debug("Message received:",t.type),this._dispatcher?this._dispatcher.dispatch(t):m.warn("Dispatcher not set, message ignored")}catch(t){m.error("Error parsing message:",t),this._context.emitError(t,B.WS_PARSE_ERROR)}}sendBinary(e){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN){m.debug("WebSocket not connected, binary data dropped");return}try{this._ws.send(e),m.debug("Binary data sent via transport")}catch(t){m.error("Error sending binary data:",t)}}get isConnected(){return this._ws?.readyState===WebSocket.OPEN}_stopHeartbeat(){this._clearTimer(this._pingTimer),this._clearTimer(this._pongTimer)}onDispose(){this._stopHeartbeat(),this.disconnect(),this._dispatcher&&(this._dispatcher.dispose(),this._dispatcher=null),m.info("Conversation transport disposed")}}const Oi=["sdk:connected","sdk:disconnected","sdk:error","media:video:available","media:video:unavailable","media:video:trackAdded","media:video:trackRemoved","media:audio:trackAdded","media:audio:trackRemoved","media:audio:captureStarted","media:audio:captureStopped","media:audio:volumeChanged","media:audio:muted","media:audio:unmuted","conversation:question:sent","conversation:answer:waiting","conversation:server:message","conversation:asr:received","conversation:answer:chunk","conversation:answer:completed"],Ra=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class Yh{constructor(e){this.inner=e,this.listeners=new Map,this.forwardedVideoTrackIds=new Set,this.wsConnected=!1,this.livekitConnected=!1,this.httpConnected=!1,this.internalMap={"inner:sdk:error":{public:"sdk:error",sanitizer:t=>({message:t?.error?.message,code:t?.error?.code})},"inner:rtc:video:available":{public:"media:video:available"},"inner:rtc:video:unavailable":{public:"media:video:unavailable"},"inner:video:track:added":{public:"media:video:trackAdded"},"inner:video:track:removed":{public:"media:video:trackRemoved"},"inner:audio:track:added":{public:"media:audio:trackAdded"},"inner:audio:track:removed":{public:"media:audio:trackRemoved"},"inner:audio:input:started":{public:"media:audio:captureStarted"},"inner:audio:input:stopped":{public:"media:audio:captureStopped"},"inner:audio:volume:changed":{public:"media:audio:volumeChanged",sanitizer:t=>({volume:t?.volume})},"inner:audio:muted":{public:"media:audio:muted"},"inner:audio:unmuted":{public:"media:audio:unmuted"},"inner:conversation:question:sent":{public:"conversation:question:sent",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:waiting":{public:"conversation:answer:waiting",sanitizer:t=>({questionId:t?.questionId})},"inner:conversation:server:message":{public:"conversation:server:message",sanitizer:t=>({questionId:t?.questionId,message:String(t?.message||""),type:String(t?.type||"")})},"inner:conversation:asr:received":{public:"conversation:asr:received",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:chunk":{public:"conversation:answer:chunk",sanitizer:t=>({questionId:t?.questionId,chunk:String(t?.chunk||"")})},"inner:conversation:answer:completed":{public:"conversation:answer:completed",sanitizer:t=>({questionId:t?.questionId,fullAnswer:String(t?.fullAnswer||"")})}},Object.keys(this.internalMap).forEach(t=>{this.inner.on(t,i=>this.handleInternalEvent(t,i))}),this.inner.on("inner:sdk:connected",t=>this.handleConnected(t,!0)),this.inner.on("inner:sdk:disconnected",t=>this.handleConnected(t,!1)),Oi.forEach(t=>{this.inner.on(t,i=>this.handlePublicEvent(t,i))})}publicAPI(){return{on:this.on.bind(this),off:this.off.bind(this),once:this.once.bind(this)}}on(e,t){const i=String(e);return this.assertAllowed(i),this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t),()=>this.off(e,t)}once(e,t){const i=String(e);this.assertAllowed(i);const s=r=>{try{t(r)}finally{this.off(e,s)}};return this.on(e,s)}off(e,t){const i=String(e);this.assertAllowed(i);const s=this.listeners.get(i);s&&(s.delete(t),s.size===0&&this.listeners.delete(i))}handleInternalEvent(e,t){const i=this.internalMap[e];if(!i)return;const s=i.public;if(Oi.indexOf(s)===-1)return;if(s==="media:video:trackAdded"){const o=t?.trackId||t?.id;if(typeof o=="string"){if(this.forwardedVideoTrackIds.has(o))return;this.forwardedVideoTrackIds.add(o)}}const r=i.sanitizer?i.sanitizer(t):t;if(!Ra.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){console.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Oi.indexOf(e)===-1)return;const i=Object.values(this.internalMap).find(a=>a.public===e),s=i&&i.sanitizer?i.sanitizer(t):t;if(e==="media:video:trackAdded"){const a=t?.trackId||t?.id;if(typeof a=="string"){if(this.forwardedVideoTrackIds.has(a))return;this.forwardedVideoTrackIds.add(a)}}const r=this.listeners.get(e);!r||r.size===0||r.forEach(a=>{try{a(s)}catch(o){console.error("PublicEventEmitter listener error",o)}})}handleConnected(e,t){e.source==="livekit"?this.livekitConnected=t:e.source==="ws"?this.wsConnected=t:e.source==="http"&&(this.httpConnected=t),this.maybeEmitSdkConnected(t?"connected":"disconnected")}maybeEmitSdkConnected(e){const t=e==="connected",i=t?!!this.livekitConnected:!this.livekitConnected,s=t?!!this.wsConnected:!this.wsConnected,r=t?!!this.httpConnected:!this.httpConnected,a={livekit:i,ws:s,http:r,all:i&&s&&r},o=JSON.stringify(a);this.lastConnectedPayloadJson!==o&&(this.lastConnectedPayloadJson=o,this.inner.emit(`sdk:${e}`,a))}assertAllowed(e){if(Oi.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!Ra.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class Xh extends G{constructor(e,t,i){super(),this._requestCounter=0,this._context=e,this._baseURL=t||"",this._defaultHeaders=i||{},m.info(`HTTP Service created with baseURL: ${this._baseURL||"none"}`)}setAuthToken(e){this._defaultHeaders.Authorization=`Bearer ${e}`}request(e){this.ensureNotDisposed();const t=e.requestId||`req_${Date.now()}_${++this._requestCounter}`,i=this._buildURL(e.url,e.params),s=this._mergeHeaders(e.headers),r={method:e.method||"GET",headers:s};e.data!==void 0&&(e.method||"GET")!=="GET"&&(typeof e.data=="string"?r.body=e.data:(r.body=JSON.stringify(e.data),!s["Content-Type"]&&!s["content-type"]&&(s["Content-Type"]="application/json")));const a=e.timeout||3e4,o=new AbortController;return r.signal=o.signal,new Promise((c,d)=>{const l=setTimeout(()=>o.abort(),a);fetch(i,r).then(async u=>{clearTimeout(l);const h={};u.headers.forEach((R,_)=>{h[_]=R});let f;const b=u.headers.get("content-type");b&&b.includes("application/json")?f=await u.json():f=await u.text();const v={requestId:t,status:u.status,headers:h,data:f,config:e};m.debug(`HTTP request succeeded: ${e.method} ${i} [${t}]`),c(v)}).catch(u=>{clearTimeout(l);const h=u&&u.name==="AbortError",f={requestId:t,status:u&&u.status||void 0,message:h?"Request aborted (timeout)":u&&u.message||"HTTP request failed",error:u,config:e};m.error(`HTTP request failed: ${e.method} ${i} [${t}]`,u),d(f)})})}get(e,t,i){return this.request({...i,url:e,method:"GET",params:t})}post(e,t,i){return this.request({...i,url:e,method:"POST",data:t})}put(e,t,i){return this.request({...i,url:e,method:"PUT",data:t})}delete(e,t){return this.request({...t,url:e,method:"DELETE"})}patch(e,t,i){return this.request({...i,url:e,method:"PATCH",data:t})}_buildURL(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return this._appendParams(e,t);let i=this._baseURL;return i&&!i.endsWith("/")&&!e.startsWith("/")?i+="/":i&&i.endsWith("/")&&e.startsWith("/")&&(i=i.slice(0,-1)),i+=e,this._appendParams(i,t)}_appendParams(e,t){if(!t||Object.keys(t).length===0)return e;const i=new URLSearchParams;for(const[r,a]of Object.entries(t))i.append(r,String(a));const s=e.includes("?")?"&":"?";return`${e}${s}${i.toString()}`}_mergeHeaders(e){const t={...this._defaultHeaders};return e&&Object.assign(t,e),t}onDispose(){m.info("HTTP Service disposed")}}function Zh(n,e="https"){return n.startsWith(e)?n:`${e}://${n}`}class ep extends G{constructor(e,t){super(),this._context=e,this._httpService=new Xh(e,t||La)}getAuthToken(){return this.ensureNotDisposed(),this._httpService?.request({url:"/auth/login",method:"GET",data:{}}).then(e=>{e.data.code===At&&this._httpService?.setAuthToken(e.data.data.token)}).catch(e=>{throw this._context.emitError(e,B.SDK_AUTH_TOKEN_FAILED)})}getLivekitConfig(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/start",method:"POST",data:{avatarName:this._context.options.avatarName,voice:this._context.options.avatarVoice||""}}).then(e=>{if(e.data.code===At){const t=e.data.data;return this._context.setLivekitConfig(Zh(t.livekitUrl,"wss"),t.roomToken,t.roomId),this._context.setWsUrl(`${this._context.options.wsUrlPrefix||Fa}/${t.roomId}/${this._context.options.avatarName}`),this._context.setVideoOptions({renderMode:t.greenScreen.enabled?"processed":"raw",greenScreen:t.greenScreen||{}}),this._context.eventBus.emit("inner:sdk:connected",{source:"http"}),!0}else throw new H(e.data.msg,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}).catch(e=>{throw this._context.eventBus.emit("inner:sdk:error",{error:new H(e.message,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}),H.fromError(e,B.SDK_GET_LIVEKIT_CONFIG_FAILED)})}switchVideo({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._httpService?.request({url:"/avatar/v1/switch-video",method:"POST",data:{roomId:this._context.roomId,onceActions:e,loopActions:t}}).then(i=>{if(i.data.code===At)return!0;throw this._context.emitError(i.data.message,B.SDK_SWITCH_VIDEO_FAILED)})}interruptConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/interrupt",method:"POST",data:{roomId:this._context.roomId}}).then(e=>{if(e.data.code===At)return!0;throw this._context.emitError(e.data.message,B.SDK_INTERRUPT_CONVERSATION_FAILED)}).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}disconnectConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/stop",method:"POST",data:{roomId:this._context.roomId}}).then(e=>e.data.code===At).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}onDispose(){this._httpService.dispose()}}class wa extends G{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._liveKitService=null,this._conversationTransport=null,this._connectionCoordinator=null,this._httpController=null,this._preConnectPromise=null,this._lastPreConnectSuccessAt=null,this._context=new Va(e),m.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new Yh(this._context.eventBus),this._publicEventAPI=this._publicEmitter.publicAPI()),this._publicEventAPI}pushActions({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.switchVideo({onceActions:e,loopActions:t})}interruptConnection(){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.interruptConversation()}sendTextQuestion(e){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.sendQuestion(e);throw new H("Conversation controller is not available",B.CONVERSATION_CONTROLLER_NOT_AVAILABLE)}setRenderFitMode(e){this.ensureNotDisposed(),this._ensureConnected(),this._videoController&&this._videoController.setRenderFitMode(e)}async startAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.startCapture()}async stopAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.stopCapture()}setVolume(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.setVolume(e)}getVolume(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController?.getVolume()||1}mute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.mute()}unmute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.unmute()}get isMuted(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController.isMuted()}get isAudioCapturing(){return this.ensureNotDisposed(),this._ensureConnected(),this._audioController?this._audioController.isCapturing:!1}async preConnect(){if(this.ensureNotDisposed(),this._preConnectPromise)return this._preConnectPromise;const e=Date.now();return this._lastPreConnectSuccessAt!==null&&e-this._lastPreConnectSuccessAt<Ba?Promise.resolve(!0):(this._preConnectPromise=(async()=>{try{if(m.info("Creating HTTP controller..."),this._httpController=this._httpController??new ep(this._context,this._context.options.http?.baseURL),m.info("Getting auth token..."),await this._httpController.getAuthToken(),m.info("Getting livekit config..."),!!!await this._httpController?.getLivekitConfig())throw new Error("Config missing");return this._lastPreConnectSuccessAt=Date.now(),!0}catch(t){throw this._context.emitError(t,B.SDK_PRECONNECT_FAILED)}finally{this._preConnectPromise=null}})(),this._preConnectPromise)}async connect(){if(this.ensureNotDisposed(),this._connectionCoordinator&&this._context.sessionState.isConnected){m.warn("SDK already initialized");return}try{if(!await this.preConnect())throw new H("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED)}catch(e){throw this._context.emitError(e,B.SDK_CONNECT_FAILED)}try{if(m.info("Initializing SDK..."),this._connectionCoordinator=new qa(this._context),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._videoController=new Ja(this._context,this._context.options.video),this._audioController=new mc(this._context,this._context.options.audio),this._conversationController=new yc(this._context),this._liveKitService=new Jh(this._context),this._conversationTransport=new Qh(this._context),this._liveKitService&&this._videoController&&this._audioController){const e=this._liveKitService.getEventAdapter();e&&(typeof e.setVideoController=="function"&&e.setVideoController(this._videoController),typeof e.setAudioController=="function"&&e.setAudioController(this._audioController))}this._audioController&&this._conversationTransport&&this._audioController.setWebSocketSender({sendBinary:e=>{this._conversationTransport.sendBinary(e)},isConnected:()=>this._conversationTransport.isConnected}),this._conversationTransport&&this._conversationController&&(this._conversationTransport.setConversationManager(this._conversationController.manager),this._conversationController.setTransport(this._conversationTransport)),await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),this._conversationTransport&&await this._conversationTransport.connect(),m.info("SDK initialized and connected")}catch(e){throw this._connectionCoordinator&&this._connectionCoordinator.transitionToIdle(),await this._cleanup(),this._context.emitError(e,B.SDK_INITIALIZATION_FAILED)}}async disconnect(){if(this.ensureNotDisposed(),!(!this._connectionCoordinator||this._connectionCoordinator.getState()==="idle"||this._connectionCoordinator.getState()==="disposed")){m.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService&&await this._liveKitService.disconnect(),this._audioController&&this._audioController.stopCapture(),this._httpController&&await this._httpController.disconnectConversation(),this._preConnectPromise=null,this._connectionCoordinator.completeDisconnecting(),m.info("SDK disconnected")}catch(e){throw m.error("Error during disconnect:",e),this._context.emitError(e,B.SDK_DISCONNECT_FAILED)}}}async reconnect(){this.ensureNotDisposed();const e=this._connectionCoordinator;if(!e?.canStartReconnectingManual()){const i=e?e.getSnapshot():this.connectionSnapshot;return m.warn("SDK reconnect not allowed in current state, returning current snapshot"),i}const t=e.captureSnapshotAndStartReconnectingManual();try{if(this._audioController&&this._audioController.stopCapture(),t.rtc.connected&&!t.rtc.hasVideoTrack&&(await this._liveKitService?.disconnect(),await this._conversationTransport?.disconnect()),this._conversationTransport&&!this._conversationTransport.isConnected){if(!await this.preConnect())throw new H("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED);await this._conversationTransport.connect()}return this._liveKitService&&!this._liveKitService.isConnected()&&await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),t}catch(i){throw m.error("Error during reconnect:",i),this._context.emitError(i,B.SDK_RECONNECT_FAILED)}}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():fs(ms("idle"))}async _cleanup(){if(this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){m.error("Error disconnecting LiveKit:",e)}this._audioController&&this._audioController.stopCapture()}get isConnected(){return this.ensureNotDisposed(),this._context.sessionState.isConnected}_ensureConnected(){if(!this._context.sessionState.isConnected)throw new H("SDK is not connected. Call connect() first.",B.SDK_NOT_CONNECTED)}onDispose(){this.disconnect().catch(e=>{m.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._conversationController&&(this._conversationController.dispose(),this._conversationController=null),this._liveKitService&&(this._liveKitService.dispose(),this._liveKitService=null),this._conversationTransport&&(this._conversationTransport.dispose(),this._conversationTransport=null),this._httpController&&(this._httpController.dispose(),this._httpController=null),this._connectionCoordinator&&(this._connectionCoordinator.transitionToDisposed(),this._connectionCoordinator.dispose(),this._connectionCoordinator=null),this._context.dispose(),m.info("SDK Client disposed")}}function tp(n){if(!n.avatarName)throw new H("avatarName is required",B.NO_AVATARNAME);return m.info("Creating SDK client with options:",{avatarName:n.avatarName}),new wa(n)}class Pa extends G{constructor(e,t){super(),this._videoElement=null,this._videoUrl=null,this._isPlaying=!1,this._frameCallbackId=null,this._videoUrl=e,t?this._videoElement=t:(this._videoElement=document.createElement("video"),this._videoElement.style.opacity="0",this._videoElement.muted=!0,this._videoElement.playsInline=!0,this._videoElement.loop=!0,document.querySelector("#video-container")?.appendChild(this._videoElement)),m.info("Local Video Debug Source created")}get videoElement(){return this._videoElement}async load(){if(!this._videoElement)throw new Error("Video element or URL not set");return new Promise((e,t)=>{const i=this._videoElement,s=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),m.info(`Video loaded: ${i.videoWidth}x${i.videoHeight}`),e()},r=a=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),t(new Error(`Failed to load video: ${a}`))};i.addEventListener("loadedmetadata",s),i.addEventListener("error",r),i.src=this._videoUrl||"",i.load()})}async play(){if(!this._videoElement)throw new Error("Video element not set");if(!this._isPlaying)try{await this._videoElement.play(),this._videoElement.style.opacity="0",this._videoElement.setAttribute("loop","true"),this._isPlaying=!0,m.info("Video playback started")}catch(e){throw m.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,m.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,m.info("Video playback stopped"))}get isPlaying(){return this._isPlaying&&this._videoElement!==null&&!this._videoElement.paused}get videoWidth(){return this._videoElement?.videoWidth||0}get videoHeight(){return this._videoElement?.videoHeight||0}async captureFrame(){if(!this._videoElement||this._videoElement.readyState<2)return null;try{if("VideoFrame"in window&&typeof window.VideoFrame=="function")try{return new VideoFrame(this._videoElement,{timestamp:this._videoElement.currentTime*1e6})}catch(i){m.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return m.error("Failed to capture video frame:",e),null}}onFrame(e){if(!this._videoElement)return;this.offFrame();const t=this._videoElement;if("requestVideoFrameCallback"in t){const i=(s,r)=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(a=>{a&&(e(a),a.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=t.requestVideoFrameCallback(i))}).catch(a=>{m.error("Error in frame callback:",a)})};this._frameCallbackId=t.requestVideoFrameCallback(i)}else{const i=()=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(s=>{s&&(e(s),s.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=requestAnimationFrame(i))}).catch(s=>{m.error("Error in frame callback:",s)})};this._frameCallbackId=requestAnimationFrame(i)}}offFrame(){this._frameCallbackId!==null&&(this._videoElement&&"cancelVideoFrameCallback"in this._videoElement?this._videoElement.cancelVideoFrameCallback(this._frameCallbackId):cancelAnimationFrame(this._frameCallbackId),this._frameCallbackId=null)}onDispose(){this.stop(),this.offFrame(),this._videoElement&&this._videoElement.parentElement===document.body&&document.body.removeChild(this._videoElement),this._videoElement=null,this._videoUrl=null,m.info("Local Video Debug Source disposed")}}class ip extends G{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new vs;const s={...e,renderMode:"processed"};this._pipeline=new Ts(this._source,s),this._outputRenderer=new Mi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),m.info("Video Pipeline Runner created")}get outputCanvas(){return this._outputCanvas}get processor(){return this._pipeline.strategy.getProcessors()[0]||null}setProcessor(e){this._pipeline.setProcessor(e),m.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){m.error("Output renderer not available"),e.close();return}try{const t=this._pipeline.strategy.getProcessors()[0]||null;let i=null;if(t){try{i=t.process(e)}catch(s){m.error("Error processing frame:",s),i=e}if(i===null&&"getImageData"in t){const s=t.getImageData();if(s&&this._outputCanvas&&this._outputRenderer.getContext()){const r=this._outputRenderer.getContext();r&&((this._outputCanvas.width!==s.width||this._outputCanvas.height!==s.height)&&(this._outputCanvas.width=s.width,this._outputCanvas.height=s.height),r.putImageData(s,0,0))}e.close();return}i&&i!==e?(this._outputRenderer.render(i),e.close()):i===e?this._outputRenderer.render(e):e.close()}else this._outputRenderer.render(e)}catch(t){m.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,m.info(`Output canvas size set to ${e}x${t}`))}onDispose(){this._pipeline.dispose(),this._outputRenderer&&(this._outputRenderer.dispose(),this._outputRenderer=null),this._outputCanvas&&this._outputCanvas.parentElement===document.body&&document.body.removeChild(this._outputCanvas),this._outputCanvas=null,m.info("Video Pipeline Runner disposed")}}class np extends G{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Pa(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new ip(this._options,t,i),this._options.greenScreen?.enabled){const r=new Li(this._options.greenScreen);this._pipelineRunner.setProcessor(r),m.info("Green screen processor enabled in debugger")}m.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Pa(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{m.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){console.warn("Error disposing old video source during switch:",c)}const a=this._videoSource.videoWidth,o=this._videoSource.videoHeight;a>0&&o>0&&this._pipelineRunner.setOutputSize(a,o)}catch(a){m.error("Failed to switch video source:",a);try{r.dispose()}catch(o){console.warn("Error disposing new video source after failed switch:",o)}throw a}}get outputCanvas(){return this._pipelineRunner.outputCanvas}get videoSource(){return this._videoSource}get processor(){return this._pipelineRunner.processor}setProcessor(e){this._pipelineRunner.setProcessor(e)}updateGreenScreenOptions(e){const t=this._pipelineRunner.processor;if(t&&"updateOptions"in t&&typeof t.updateOptions=="function")t.updateOptions(e),m.info("Green screen options updated");else{const i=this._options.greenScreen||{enabled:!1},s={...i,...e,enabled:e.enabled!==void 0?e.enabled:i.enabled},r=new Li(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,m.info("Green screen processor recreated with new options")}}async initialize(){this.ensureNotDisposed();try{await this._videoSource.load();const e=this._videoSource.videoWidth,t=this._videoSource.videoHeight;e>0&&t>0&&this._pipelineRunner.setOutputSize(e,t),m.info("Video debugger initialized")}catch(e){throw m.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Debugger is already running");return}try{this._videoSource.videoWidth===0&&await this.initialize(),await this._videoSource.play(),this._videoSource.onFrame(e=>{this._pipelineRunner.processFrame(e).catch(t=>{m.error("Error processing frame:",t)})}),this._isRunning=!0,m.info("Video debugger started")}catch(e){throw m.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,m.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),m.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),m.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),m.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ma,D.DEFAULT_AUDIO_CHANNELS=xa,D.DEFAULT_AUDIO_SAMPLE_RATE=xi,D.DEFAULT_RECONNECT_ATTEMPTS=It,D.DEFAULT_RECONNECT_DELAY=Ni,D.DEFAULT_WS_TIMEOUT=Oa,D.Disposable=G,D.EventBus=ls,D.Logger=m,D.SDKClient=wa,D.SDKError=H,D.SessionState=us,D.StandaloneVideoDebugger=np,D.createClient=tp}));