@sanseng/livekit-ws-sdk 0.1.19 → 0.1.20

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 Ri(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 wi(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 ql=Object.freeze({__proto__:null,removeExtmapAllowMixed:bn,shimAddIceCandidateNullOrEmpty:Ri,shimConnectionState:vn,shimMaxMessageSize:Si,shimParameterlessSetLocalDescription:wi,shimRTCIceCandidate:Ci,shimRTCIceCandidateRelayProtocol:gn,shimSendThrowTypeError:Ei});function Wl(){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=zr,i=Fl(n),s={browserDetails:i,commonShim:ql,extractVersion:Wt,disableLog:Ll,disableWarnings:Ul,sdp:jl};switch(i.browser){case"chrome":if(!oo||!pn||!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=oo,Ri(n,i),wi(n),Xr(n,i),Zr(n),pn(n,i),eo(n),so(n,i),to(n),io(n),ro(n,i),Ci(n),gn(n),vn(n),Si(n,i),Ei(n),bn(n,i);break;case"firefox":if(!bo||!mn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=bo,Ri(n,i),wi(n),ao(n,i),mn(n,i),co(n),ho(n),lo(n),uo(n),po(n),mo(n),fo(n),go(n),vo(n),Ci(n),vn(n),Si(n,i),Ei(n);break;case"safari":if(!Po||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Po,Ri(n,i),wi(n),So(n),Ro(n),To(n),_o(n),yo(n),Eo(n),ko(n),wo(n),Ci(n),gn(n),Si(n,i),Ei(n),bn(n,i);break;default:t("Unsupported browser!");break}return s}Wl({window:typeof window>"u"?void 0:window});var _n,Ao;class ue extends(Ao=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)}}_n=ue,ue.resolve=n=>Reflect.get(Ao,"resolve",_n).call(_n,n);const Kl=/version\/(\d+(\.?_?\d+)+)/i;let yn;function _e(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(yn===void 0||e){const i=Hl.find(s=>{let{test:r}=s;return r.test(t)});yn=i?.describe(t)}return yn}const Hl=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Pi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Tn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Pi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Tn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Pi(Kl,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Tn(n)}}}];function Pi(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 Tn(n){return n.includes("mac os")?Pi(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Gl="2.17.1";const zl=Gl,Jl=16;class Qe 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 kn extends Qe{}var $;(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"})($||($={}));class F extends kn{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=$[t]}static notAllowed(e,t,i){return new F(e,$.NotAllowed,t,i)}static timeout(e){return new F(e,$.Timeout)}static leaveRequest(e,t){return new F(e,$.LeaveRequest,void 0,t)}static internal(e,t){return new F(e,$.InternalError,void 0,t)}static cancelled(e){return new F(e,$.Cancelled)}static serverUnreachable(e,t){return new F(e,$.ServerUnreachable,t)}static websocket(e,t,i){return new F(e,$.WebSocket,t,i)}static serviceNotFound(e,t){return new F(e,$.ServiceNotFound,void 0,t)}}class Cn extends Qe{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class We extends Qe{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class $l extends Qe{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class re extends Qe{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class kt extends Qe{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Oo extends Qe{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class No extends kn{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:dn[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 kn{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=me[t]}}class Ct extends Qe{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Ii;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Ii||(Ii={})),(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})(Ii||(Ii={}));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 Ql(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 J{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 Yl=["vp8","h264"],Xl=["vp8","h264","vp9","av1","h265"];function Zl(n){return!!Yl.find(e=>e===n)}const eu=Zl;var xo;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(xo||(xo={}));var Sn;(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}})(Sn||(Sn={}));const Kt={h90:new J(160,90,9e4,20),h180:new J(320,180,16e4,20),h216:new J(384,216,18e4,20),h360:new J(640,360,45e4,20),h540:new J(960,540,8e5,25),h720:new J(1280,720,17e5,30),h1080:new J(1920,1080,3e6,30),h1440:new J(2560,1440,5e6,30),h2160:new J(3840,2160,8e6,30)},En={h120:new J(160,120,7e4,20),h180:new J(240,180,125e3,20),h240:new J(320,240,14e4,20),h360:new J(480,360,33e4,20),h480:new J(640,480,5e5,20),h540:new J(720,540,6e5,25),h720:new J(960,720,13e5,30),h1080:new J(1440,1080,23e5,30),h1440:new J(1920,1440,38e5,30)},Rn={h360fps3:new J(640,360,2e5,3,"medium"),h360fps15:new J(640,360,4e5,15,"medium"),h720fps5:new J(1280,720,8e5,5,"medium"),h720fps15:new J(1280,720,15e5,15,"medium"),h720fps30:new J(1280,720,2e6,30,"medium"),h1080fps15:new J(1920,1080,25e5,15,"medium"),h1080fps30:new J(1920,1080,5e6,30,"medium"),original:new J(0,0,7e6,30,"medium")};function Mo(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Fo(n??{}),l=e?.processor,u=t?.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(wn(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&&(wn(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 wn(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Pn(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"?wn(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 Lo(n){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Uo();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 Uo(){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=()=>m(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 tu(n){return n==="audioinput"?C.Source.Microphone:n==="videoinput"?C.Source.Camera:C.Source.Unknown}function In(n){return n===C.Source.Microphone?"audioinput":n===C.Source.Camera?"videoinput":void 0}function iu(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,ut()?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 Ht(n){return n.split("/")[1].toLowerCase()}function nu(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new sn({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 su(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function ru(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 Fo(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:Ql(e)}}function ou(n){switch(n){case oe.CAMERA:return C.Source.Camera;case oe.MICROPHONE:return C.Source.Microphone;case oe.SCREEN_SHARE:return C.Source.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return C.Source.ScreenShareAudio;default:return C.Source.Unknown}}function Bo(n,e){return n.width*n.height<e.width*e.height}function au(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const cu=5e3,Gt=[];var Te;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Te||(Te={}));class C extends Me.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=C.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(),cu):this.handleAppVisibilityChanged()},this.log=je((s=i.loggerName)!==null&&s!==void 0?s:Ie.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.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===C.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Gt.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Gt.splice(Gt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),St(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){Et(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=>{Et(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=je(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Gt.forEach(i=>{i.parentElement||(t=!1)}),t&&Gt.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===C.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 St(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)),(!ut()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(ut()||lt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Et(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 we.AUDIO;case e.Video:return we.VIDEO;default:return we.DATA}}n.kindToProto=s;function r(d){switch(d){case we.AUDIO:return e.Audio;case we.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 tn.ACTIVE:return i.Active;case tn.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(C||(C={}));const du="|",Vo="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function lu(n){const e=n.split(du);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 Dn(){return"addTransceiver"in RTCPeerConnection.prototype}function An(){return"addTrack"in RTCPeerConnection.prototype}function uu(){if(!("getCapabilities"in RTCRtpSender)||ut()||lt())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 hu(){if(!("getCapabilities"in RTCRtpSender)||lt())return!1;if(ut()){const t=_e();if(t?.version&&Ue(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&Ue(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 De(n){return n==="av1"||n==="vp9"}function On(n){return!document||zt()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function pu(){return typeof RTCPeerConnection>"u"?!1:Dn()||An()}function lt(){var n;return((n=_e())===null||n===void 0?void 0:n.name)==="Firefox"}function jo(){const n=_e();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function ut(){var n;return((n=_e())===null||n===void 0?void 0:n.name)==="Safari"}function zt(){const n=_e();return n?.name==="Safari"||n?.os==="iOS"}function mu(){const n=_e();return n?.name==="Safari"&&n.version.startsWith("17.")||n?.os==="iOS"&&!!n?.osVersion&&Ue(n.osVersion,"17")>=0}function fu(n){return n||(n=_e()),n?.name==="Safari"&&Ue(n.version,"18.3")>0||n?.os==="iOS"&&!!n?.osVersion&&Ue(n.osVersion,"18.3")>0}function qo(){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 gu(){const n=_e(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Ue(n.osVersion,e)>=0?!0:n.name==="Safari"&&Ue(n.version,e)>=0}function ye(){return typeof document<"u"}function Le(){return navigator.product=="ReactNative"}function Rt(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Nn(n){return Rt(n)?n.hostname.split(".")[0]:null}function Wo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ko(){if(!Le())return;let n=Wo();if(n)return n.platform}function Ho(){if(ye())return window.devicePixelRatio;if(Le()){let n=Wo();if(n)return n.devicePixelRatio}return 1}function Ue(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 vu(n){for(const e of n)e.target.handleResize(e)}function bu(n){for(const e of n)e.target.handleVisibilityChanged(e)}let xn=null;const Go=()=>(xn||(xn=new ResizeObserver(vu)),xn);let Mn=null;const zo=()=>(Mn||(Mn=new IntersectionObserver(bu,{root:null,rootMargin:"0px"})),Mn);function _u(){var n;const e=new Tr({sdk:kr.JS,protocol:Jl,version:zl});return Le()&&(e.os=(n=Ko())!==null&&n!==void 0?n:""),e}function Jo(){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 Jt;function Ln(){if(!Jt){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(),[Jt]=i.stream.getAudioTracks(),!Jt)throw Error("Could not get empty media stream audio track");Jt.enabled=!1}return Jt.clone()}class Ee{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>m(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 yu(n){return Xl.includes(n)}function Ye(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 Tu(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function $t(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function ku(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 Cu(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 $o(n){switch(n.reason){case $.LeaveRequest:return n.context;case $.Cancelled:return Ce.CLIENT_INITIATED;case $.NotAllowed:return Ce.USER_REJECTED;case $.ServerUnreachable:return Ce.JOIN_FAILURE;default:return Ce.UNKNOWN_REASON}}function Di(n){return n!==void 0?Number(n):void 0}function ht(n){return n!==void 0?BigInt(n):void 0}function wt(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Fe(n){return!!n&&n.kind==C.Kind.Audio}function Xe(n){return!!n&&n.kind==C.Kind.Video}function Ze(n){return wt(n)&&Xe(n)}function Ke(n){return wt(n)&&Fe(n)}function Un(n){return!!n&&!n.isLocal}function Su(n){return!!n&&!n.isLocal}function Fn(n){return Un(n)&&Xe(n)}function Eu(n){return n.isLocal}function Ru(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 wu(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 Pu(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=Iu(n,e);return t?i:Bn(i,"v1")}function Iu(n,e){const t=new URL(Tu(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),Bn(t,"rtc")}function Du(n){const e=new URL($t(n));return Bn(e,"validate")}function Qo(n){return n.endsWith("/")?n:"".concat(n,"/")}function Bn(n,e){return n.pathname="".concat(Qo(n.pathname)).concat(e),n}function Yo(n){if(typeof n=="string")return Pr.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return Pr.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function Au(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 Ou=10,Qt="lk_e2ee",Nu={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Ou,keyringSize:16};var et;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(et||(et={}));var Xo;(function(n){n.KeyRatcheted="keyRatcheted"})(Xo||(Xo={}));var tt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(tt||(tt={}));var Zo;(function(n){n.Error="cryptorError"})(Zo||(Zo={}));function xu(){return Mu()||Vn()}function Vn(){return typeof window.RTCRtpScriptTransform<"u"}function Mu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Lu(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 mr({value:n.value})}class Pp extends Me.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({},Nu),e),this.on(et.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(et.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(et.RatchetRequest,e,t)}}var ea;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(ea||(ea={}));class Uu extends Me.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(tt.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(tt.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(tt.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(et.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(tt.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(!xu())throw new Cn("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:Al.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===z.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)=>m(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(I.LocalTrackPublished,i=>{if(!Xe(i.track)||!zt())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:Ht(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(et.SetKey,i=>this.postKey(i)).on(et.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return m(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 Ee;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 Ee;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"?Ht(i.mimeType):void 0)}}setupE2EESender(e,t){if(!wt(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 m(this,void 0,void 0,function*(){if(this.worker){if(Vn()&&!jo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Qt 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:Qt in e}};this.worker.postMessage(o,[a,r])}e[Qt]=!0}})}handleSender(e,t,i){var s;if(!(Qt 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(Vn()&&!jo()){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[Qt]=!0}}}const Fu=500,Bu=15e3;class Pt{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Pt),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=Nn(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(Fu*Math.pow(2,r),Bu)))}getBackOffPromise(e){const t=new URL(e),i=t&&Nn(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Nn(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Pt._instance=null;const jn="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 m(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&&!(ut()&&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 m(this,void 0,void 0,function*(){if(t!==jn)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===jn);if(!r){V.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==jn&&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 Yt;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Yt||(Yt={}));class Vu{constructor(){this.pendingTasks=new Map,this.taskMutex=new he,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Yt.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Yt.RUNNING,yield e()}finally{t.status=Yt.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class ju{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=()=>m(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 qu=["syncState","trickle","offer","answer","simulate","leave"];function Wu(n){const e=qu.indexOf(n.case)>=0;return V.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Q;(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"})(Q||(Q={}));const Ku=250;class qn{get currentState(){return this.state}get isDisconnected(){return this.state===Q.DISCONNECTING||this.state===Q.DISCONNECTED}get isEstablishingConnection(){return this.state===Q.CONNECTING||this.state===Q.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=Q.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=je((i=t.loggerName)!==null&&i!==void 0?i:Ie.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Vu,this.queuedRequests=[],this.closingLock=new he,this.connectionLock=new he,this.state=Q.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 m(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=Q.CONNECTING,d.options=o,yield d.connect(r,a,o,c,l)})()})}reconnect(e,t,i,s){return m(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=Q.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 m(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=_u(),f=l?Hu(a,h,o):Gu(a,h,o),b=Pu(r,f,l).toString(),v=Du(b).toString();return new Promise((R,T)=>m(d,void 0,void 0,function*(){var A,x;try{let _=!1;const y=O=>m(this,void 0,void 0,function*(){if(_)return;_=!0;const L=O instanceof Event?O.currentTarget:O,q=Au(L,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(q)).catch(Z=>{this.log.error(Z),this.close()}):this.close(),S(),T(F.cancelled(q))});c?.addEventListener("abort",y);const S=()=>{clearTimeout(N),c?.removeEventListener("abort",y)},N=setTimeout(()=>{y(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 ju(b);try{this.ws.closed.then(ge=>{var rt;this.isEstablishingConnection&&T(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===Q.CONNECTED&&this.handleOnClose((rt=ge.reason)!==null&&rt!==void 0?rt:"Unexpected WS error"))}).catch(ge=>{this.isEstablishingConnection&&T(F.internal("Websocket error during a (re)connection attempt: ".concat(ge)))});const O=yield this.ws.opened.catch(ge=>m(this,void 0,void 0,function*(){if(this.state!==Q.CONNECTED){this.state=Q.DISCONNECTED,clearTimeout(N);const rt=yield this.handleConnectionError(ge,v);T(rt);return}this.handleWSError(ge),T(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=Yo(q.value),ke=this.validateFirstMessage(Z,(A=o.reconnect)!==null&&A!==void 0?A:!1);if(!ke.isValid){T(ke.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 pt=ke.shouldProcessFirstMessage?Z:void 0;U(O,pt),R(ke.response)}catch(O){T(O)}finally{S()}}finally{u()}}))})()})}startReadingLoop(e,t){return m(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=Yo(s);this.handleSignalResponse(r)}})}close(){return m(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([Q.DISCONNECTING||Q.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=Q.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=Q.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:It(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:It(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 gi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new vi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(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 on({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 xr({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ur({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 Vr({timestamp:X.parse(Date.now()),rtt:X.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new rn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new _i({reason:Ce.CLIENT_INITIATED,action:yt.DISCONNECT})})}sendRequest(e){return m(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&&!Wu(t)&&i.state===Q.RECONNECTING){i.queuedRequests.push(()=>m(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 Yd({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=ta(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=ta(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 m(this,void 0,void 0,function*(){if(this.state===Q.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=Q.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===Q.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 m(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 ta(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 It(n,e){return new $e({sdp:n.sdp,type:n.type,id:e})}function Hu(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",Le()?"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 Gu(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new Sl({clientInfo:e,connectionSettings:new jr({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 El({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class ia{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 zu{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 Ae={},Wn={},Kn={exports:{}},na;function Hn(){if(na)return Kn.exports;na=1;var n=Kn.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")})}),Kn.exports}var sa;function Ju(){return sa||(sa=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=Hn(),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}})})}})(Wn)),Wn}var Gn,ra;function $u(){if(ra)return Gn;ra=1;var n=Hn(),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 Gn=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
- `},Gn}var oa;function Qu(){if(oa)return Ae;oa=1;var n=Ju(),e=$u(),t=Hn();return Ae.grammar=t,Ae.write=e,Ae.parse=n.parse,Ae.parseParams=n.parseParams,Ae.parseFmtpConfig=n.parseFmtpConfig,Ae.parsePayloads=n.parsePayloads,Ae.parseRemoteCandidates=n.parseRemoteCandidates,Ae.parseImageAttributes=n.parseImageAttributes,Ae.parseSimulcastStreamList=n.parseSimulcastStreamList,Ae}var it=Qu();function zn(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 T=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(_){return(0,_.resolve)(x)}),l=[]}},u()),T){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 Yu=.7,Xu=20,Dt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class aa extends Me.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=zn(s=>m(this,void 0,void 0,function*(){this.emit(Dt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Xu),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=je((i=t.loggerName)!==null&&i!==void 0?i:Ie.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 m(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 m(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}=Zu(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=it.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Jn(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=it.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(Dt.NegotiationComplete),e.sdp&&it.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(Dt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return m(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=it.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{da(o),o.type==="audio"?ca(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||(De(c.codec)&&!ut()&&this.ensureVideoDDExtensionForSVC(o,a),!De(c.codec)))return!0;const l=Math.round(c.maxbr*Yu);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,it.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=it.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{da(s),s.type==="audio"&&ca(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,it.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 m(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 m(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 kt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Vo))){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:Vo})}}}function ca(n,e,t){const i=Jn(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 Zu(n){var e;const t=[],i=[],s=it.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Jn(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 da(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 Jn(n){return typeof n=="number"?n.toFixed(0):n}const $n="vp8",eh={audioPreset:Sn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Rn.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:$n,backupCodec:!0,preConnectBuffer:!1},la={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ua={deviceId:{ideal:"default"},resolution:Kt.h720.resolution},th={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Nl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Qn={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 ih{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=Qn.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=je((s=i.loggerName)!==null&&s!==void 0?s:Ie.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new aa(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new aa(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,Pe.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,Pe.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 m(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 m(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){var i;t===Pe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return m(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 m(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 m(this,void 0,void 0,function*(){return new ue((t,i)=>m(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new kt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new kt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(Dt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Dt.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===Pe.PUBLISHER?this.publisher.getConnectedAddress():e===Pe.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 m(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)=>m(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 ha=5e3,nh=3e4;class G{static fetchRegionSettings(e,t,i){return m(this,void 0,void 0,function*(){const s=yield G.fetchLock.lock();try{const r=yield fetch("".concat(sh(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=wu(r.headers),o=a?a*1e3:ha;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 m(this,void 0,void 0,function*(){const s=G.settingsTimeouts.get(e.hostname);clearTimeout(s),G.settingsTimeouts.set(e.hostname,setTimeout(()=>m(this,void 0,void 0,function*(){try{const r=yield G.fetchRegionSettings(e,t);G.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof F&&r.reason===$.NotAllowed){V.debug("token is not valid, cancelling auto region refresh");return}V.debug("auto refetching of region settings failed",{error:r}),G.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){G.cache.set(e.hostname,i),G.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=G.settingsTimeouts.get(e);t&&(clearTimeout(t),G.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=G.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=G.connectionTrackers.get(e);i&&i.connectionCount===0&&(V.debug("stopping region refetch after disconnect delay",{hostname:e}),G.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},nh))}static cancelCleanup(e){const t=G.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=G.connectionTrackers.get(e);t||(t={connectionCount:0},G.connectionTrackers.set(e,t)),t.connectionCount++,G.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=G.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&G.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Rt(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){return G.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=G.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),G.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){G.updateCachedRegionSettings(this.serverUrl,this.token,e)}}G.cache=new Map,G.settingsTimeouts=new Map,G.connectionTrackers=new Map,G.fetchLock=new he;function sh(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=ma(t,ie.MAX_MESSAGE_BYTES),this.data=i?ma(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new vr({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 pa=15360;function Yn(n){return new TextEncoder().encode(n).length}function ma(n,e){if(Yn(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 Xn=2e3;function Ai(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 Zn=typeof MediaRecorder<"u";class rh{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const oh=Zn?MediaRecorder:rh;class ah extends oh{constructor(e,t){if(!Zn)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=>m(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 ch(){return Zn}const dh=1e3,lh=1e4;class fa extends C{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=zn(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(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=>m(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!==C.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 m(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Et(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&&(St(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=>{St(s??e,r)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dh;return(function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=_e())===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 We("unable to get track dimensions after timeout")})()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ye(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ye(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(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===C.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new We("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 m(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=xl(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===C.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{Et(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===C.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 m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),qo()&&(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 m(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=_e();if(i?.name==="Safari"&&Ue(i.version,"12.0")<0)throw new Cn("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 m(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 m(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 m(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(St(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&&(Et(i._mediaStreamTrack,d),St(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 m(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 m(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(!ch()){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 ah(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},lh)}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 Oi extends fa{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,C.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(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=Ai(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 m(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===C.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 m(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!==Ye(this._constraints.deviceId);return this.source===C.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 m(this,void 0,void 0,function*(){let t;if(e){const i=Pn({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 m(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()},Xn)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Le()&&!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 m(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 m(this,void 0,void 0,function*(){const e=yield Lo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(w.AudioSilenceDetected)),e})}}function uh(n,e,t){switch(n.kind){case"audio":return new Oi(n,e,!1,void 0,t);case"video":return new Ni(n,e,!1,t);default:throw new We("unsupported track type: ".concat(n.kind))}}const hh=Object.values(Kt),ph=Object.values(En),mh=Object.values(Rn),fh=[Kt.h180,Kt.h360],gh=[En.h180,En.h360],vh=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new J(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)}),es=["q","h","f"];function ts(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=_h(n,e,t,d),V.debug("using video encoding",a));const l=a.maxFramerate,u=new J(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&De(d)){const b=new ba(c),v=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=_e();if(zt()||Le()||R?.name==="Chrome"&&Ue(R?.version,"113")<0){const T=b.suffix=="h"?2:3,A=fu(R);for(let x=0;x<b.spatial;x+=1)v.push({rid:es[2-x],maxBitrate:a.maxBitrate/Math.pow(T,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=va(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:ga(n,u):h=(r=va(i?.videoSimulcastLayers))!==null&&r!==void 0?r:ga(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 is(e,t,[b,f,u],l);if(v>=480)return is(e,t,[b,u],l)}return is(e,t,[u])}function bh(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===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ts(n.source===C.Source.ScreenShare,c,d,t)}function _h(n,e,t,i){const s=yh(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 yh(n,e,t){if(n)return mh;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?hh:ph}function ga(n,e){if(n)return vh(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)?fh:gh}function is(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=es.length)return;const o=Math.min(n,e),d={rid:es[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=lt()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Le()&&Ko()==="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 va(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 ba{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 Th(n){return n.source===C.Source.ScreenShare||n.constraints.height&&Ye(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const kh=5e3;class Ni extends fa{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,C.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>m(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+=Ai(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()},Xn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=qe(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 m(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=qe(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 m(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===C.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 m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.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 m(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 an({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(De(this.codec),t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Pn({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=qe(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 m(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=qe(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 m(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)},kh))}setPublishingCodecs(e){return m(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(De(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=qe(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(De(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 _a(u.sender,u.encodings,l.qualities,this.senderLock,De(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 m(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 _a(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return m(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&&De(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 m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),qo()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function _a(n,e,t,i,s,r,a){return m(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=ya(v),T=t.find(A=>A.quality===R);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,r.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),lt()&&(T.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 ya(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function Ta(n,e,t,i){if(!t)return[new Je({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new ba(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 Je({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=ya((a=s.rid)!==null&&a!==void 0?a:"");return new Je({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 ka="_lossy",Ca="_reliable",Ch=2*1e3,ns="leave-reconnect",Sh=3e4,Eh=8*1024,Rh=256*1024;var Re;(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"})(Re||(Re={}));class wh extends Me.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Qn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Re.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 ia,this.reliableReceivedState=new zu(Sh),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>m(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===Ca)r.reliableDCSub=a;else if(a.label===ka)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=>m(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=mr.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"&&Sa(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"&&Sa(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===ns&&(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===Re.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=()=>m(this,void 0,void 0,function*(){!this.url||!(yield fetch($t(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Q.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Q.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(at.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>m(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch($t(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=je((t=e.loggerName)!==null&&t!==void 0?t:Ie.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new qn(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 m(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===$.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===$.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return m(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 m(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 ia,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 m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new We("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 m(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 m(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 ih(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)=>m(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===Re.New;this.pcState=Re.Connected,u&&this.emit(P.Connected,e)}else a===te.FAILED&&(this.pcState===Re.Connected||this.pcState===Re.Reconnecting)&&(this.pcState=Re.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?at.RR_SUBSCRIBER_FAILED:at.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Q.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)},Ph((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>m(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)=>m(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",at.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:ha,regionSettings:e.regions})),e.action){case yt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close();break;case yt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ns);break;case yt.RESUME:this.handleDisconnect(ns)}}}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===Bt.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(ka,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ca,{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,Eh),Rh)}},1e3))}createSender(e,t,i){return m(this,void 0,void 0,function*(){if(Dn())return yield this.createTransceiverRTCRtpSender(e,t,i);if(An())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 m(this,void 0,void 0,function*(){if(Dn())return this.createSimulcastTransceiverSender(e,t,i,s);if(An())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 m(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Xe(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 m(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 m(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(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)===Bt.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 Ct||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",at.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 m(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 Ct;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof F&&a.reason===$.NotAllowed?new re("could not reconnect, token might be expired"):new Ct}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!==Q.CONNECTED)throw new Ct("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 m(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===$.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof F&&s.reason===$.LeaveRequest?s:new Ct(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!==Q.CONNECTED)throw new Ct("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 m(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Re.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(Ch),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Re.Connected}catch(e){throw this.pcState=Re.Disconnected,F.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return m(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Zi({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new Xi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Lu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new pr({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 m(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)=>m(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 m(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 m(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 m(this,void 0,void 0,function*(){return new ue((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new kt("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 kt("cannot negotiate on closed engine")),this.on(P.Closing,s),this.pcManager.publisher.once(Dt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();yu(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof kt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",at.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 cn({answer:this.pcManager.mode==="publisher-only"?c?It({sdp:c.sdp,type:c.type}):void 0:l?It({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?It({sdp:o.sdp,type:o.type}):void 0:d?It({sdp:d.sdp,type:d.type}):void 0,subscription:new bi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:nu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((b,v)=>new Fr({publisherSid:v,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Br({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),Pe.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),Pe.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),Pe.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),Pe.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 Ph(n){return n!==void 0&&n>13}function Sa(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 Ea{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 Ih extends Ea{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 Ee,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:()=>m(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 m(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(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=qe(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 Dh extends Ea{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Di(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 Ee,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:()=>m(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 m(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(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=qe(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 Ah{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 m(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 m(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 Ee;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:Di(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 Ih(c,d,Di(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 Ee;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 Dh(c,d,Di(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 Ra{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 m(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 Oh extends Ra{}class Nh extends Ra{}const wa=15e3;class xh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return m(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)=>m(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 m(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 pi({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:ht(a.timestamp),totalLength:ht(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Rr({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?en.UPDATE:en.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 m(this,void 0,void 0,function*(){for(const R of Ru(v,wa)){const T=new mi({content:R,streamId:r,chunkIndex:ht(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return m(this,void 0,void 0,function*(){const v=new fi({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=()=>m(this,void 0,void 0,function*(){yield b.close()});u.once(P.Closing,f);const b=new Oh(h,a,()=>this.engine.off(P.Closing,f));return b})}sendFile(e,t){return m(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return m(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 m(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 pi({totalLength:ht((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:ht(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new wr({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,T=new WritableStream({write(x){return m(this,void 0,void 0,function*(){const _=yield b.lock();let y=0;try{for(;y<x.byteLength;){const S=x.slice(y,y+wa),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new mi({content:S,streamId:c,chunkIndex:ht(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,y+=S.byteLength}}finally{_()}})},close(){return m(this,void 0,void 0,function*(){const x=new fi({streamId:c}),_=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(_,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new Nh(T,l)})}}class Pa extends C{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 m(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(),Xn)),su()&&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 Mh extends Pa{constructor(e,t,i,s,r,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>m(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=Ai(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;Le()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Le())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(On(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&On(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 m(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 ss=100;class Lh extends Pa{constructor(e,t,i,s,r){super(e,t,C.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>m(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=Ai(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=zn(()=>{this.updateDimensions()},ss),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Et(this._mediaStreamTrack,t):St(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 Uh(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 m(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 m(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<ss){de.setTimeout(()=>{this.updateVisibility()},ss);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"?Ho():t||(Ho()>2?2:1)}}class Uh{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=Xt(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=Xt(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Xt(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??rs(e),this.isPiP=ye()&&Xt(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=rs(this.element),this.isPiP=Xt(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,zo().observe(this.element),Go().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=zo())===null||e===void 0||e.unobserve(this.element),(t=Go())===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 Xt(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?rs(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function rs(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 He extends Me.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=je((r=s?.loggerName)!==null&&r!==void 0?r:Ie.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.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(Fe(this.track))return this.track}get videoTrack(){if(Xe(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.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={}))})(He||(He={}));class os extends He{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&&Xe(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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Fe(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 xi(n,e){return m(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Fo(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=Mo(r,la,ua),d=Pn(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=>m(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 T=h.getSettings().deviceId;v?.deviceId&&Ye(v.deviceId)!==T?v.deviceId=T:v||(v={deviceId:T});const A=uh(h,v,e);return A.kind===C.Kind.Video?A.source=C.Source.Camera:A.kind===C.Kind.Audio&&(A.source=C.Source.Microphone),A.mediaStream=u,Fe(A)&&i?yield A.setProcessor(i):Xe(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return xi(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function Fh(n){return m(this,void 0,void 0,function*(){return(yield xi({audio:!1,video:!0}))[0]})}function Bh(n){return m(this,void 0,void 0,function*(){return(yield xi({audio:!0,video:!1}))[0]})}var nt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(nt||(nt={}));function Vh(n){switch(n){case Ft.EXCELLENT:return nt.Excellent;case Ft.GOOD:return nt.Good;case Ft.POOR:return nt.Poor;case Ft.LOST:return nt.Lost;default:return nt.Unknown}}class Ia extends Me.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===Vt.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===bt.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]:Vt.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=nt.Unknown,this.log=V,this.log=je((c=a?.loggerName)!==null&&c!==void 0?c:Ie.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 Ee,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(C.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.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===bt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==bt.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=ru(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=Vh(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=>Fe(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 C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function jh(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 Lr({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 qh extends Ia{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 Ee)},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 Ee),(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!==dn.OK&&u.reject(new No(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=>jh(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=>m(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=qe(b),T;T=yield R.next(),c=T.done,!c;v=!0){u=T.value,v=!1;const A=u;eu(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=>m(this,void 0,void 0,function*(){if(o.source===C.Source.ScreenShare||o.source===C.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(Ke(o)||Ze(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===C.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))),Ke(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 m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>m(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 No("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(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return m(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 m(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 C.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new We(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,In(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===C.Source.Microphone&&Fe(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===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.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(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Mo(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 xi(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Fe(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(I.AudioStreamAcquired)),Xe(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cn("getDisplayMedia not supported");e.resolution===void 0&&!mu()&&(e.resolution=Rn.h1080fps30.resolution);const t=iu(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new We("no video track found");const r=new Ni(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new Oi(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(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;Ke(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),wt(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let T;switch(i.source){case C.Source.Microphone:T="audioinput";break;case C.Source.Camera:T="videoinput"}T&&r.activeDeviceMap.has(T)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(T)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Oi(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Ni(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new We("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(T=>{T.track&&T.track===i&&(h=T)}),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)),!gu()&&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((T,A)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Q.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:W(i)}));let x=!1;const _=setTimeout(()=>{x=!0,i.stop(),A(new Oo("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(_),x)return;const y=yield this.publish(i,f,v);T(y)}else try{const x=yield this.publish(i,f,v);T(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(T){throw T}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ee),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=>ou(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 m(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Oo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>wt(e)&&M.source===e.source)&&e.source!==C.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&&Fe(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&lt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!uu()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!hu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=$n),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===Ht(M.mime))||(t.videoCodec=Ht(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=[],T=!(!((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),T&&R.push(ae.TF_NO_DTX),Ke(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new jt({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:T,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 _;if(e.kind===C.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:Kt.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,Ze(e)&&(De(v)&&(e.source===C.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 nn({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:$n}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new nn({codec:t.backupCodec.codec,cid:""})))),_=ts(e.source===C.Source.ScreenShare,x.width,x.height,t),x.layers=Ta(x.width,x.height,_,De(t.videoCodec))}else e.kind===C.Kind.Audio&&(_=[{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 y=()=>m(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,_),this.emit(I.LocalSenderCreated,e.sender,e),Ze(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=Th(e)),e.setDegradationPreference(t.degradationPreference)),_)if(lt()&&e.kind===C.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=_[0])===null||O===void 0)&&O.maxBitrate?_[0].maxBitrate/1e3:0})}else e.codec&&De(e.codec)&&(!((L=_[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:_[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const N=new Promise((M,O)=>m(this,void 0,void 0,function*(){var L;try{S=yield this.engine.addTrack(x),M(S)}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)S=(yield Promise.all([N,y()]))[0];else{S=yield N;let M;if(S.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===C.Kind.Video){const O=Ht(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,_=ts(e.source===C.Source.ScreenShare,x.width,x.height,t))}yield y()}const U=new os(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(U.on(w.CpuConstrained,M=>this.onTrackCpuConstrained(M,U)),U.options=t,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:_,trackInfo:S})),Ze(e)?e.startMonitor(this.engine.client):Ke(e)&&e.startMonitor(),this.addTrackPublication(U),this.emit(I.LocalTrackPublished,U),Ke(e)&&S.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,L=>{if(L.trackSid===S.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)=>m(this,void 0,void 0,function*(){var ke,pt,ge,rt,cs,ds;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),W(e)));const ps=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),Rp=yield this.waitUntilActiveAgentPresent();clearTimeout(ps),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),W(e)));const Fa=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Rp.identity],attributes:{trackId:U.trackSid,sampleRate:String((cs=A.sampleRate)!==null&&cs!==void 0?cs:"48000"),channels:String((ds=A.channelCount)!==null&&ds!==void 0?ds:"1")}});try{for(var ls=!0,us=qe(M),hs;hs=yield us.next(),ke=hs.done,!ke;ls=!0){rt=hs.value,ls=!1;const ms=rt;yield Fa.write(ms)}}catch(ms){pt={error:ms}}finally{try{!ls&&!ke&&(ge=us.return)&&(yield ge.call(us))}finally{if(pt)throw pt.error}}yield Fa.close(),q()}catch(ps){Z(ps)}})).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 m(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 We("track is not published");if(!Ze(e))throw new We("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=bh(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 jt({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=Ta(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>m(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 m(this,void 0,void 0,function*(){var i,s;if(wt(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),Ze(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 C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.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 m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return m(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)=>m(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=>m(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(Ke(d)||Ze(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 m(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 Qi({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 m(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new gr({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return m(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 hi(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 m(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 hi(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 m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return m(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)=>m(this,void 0,void 0,function*(){var l,u,h,f;if(Yn(s)>pa){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&&Ue((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(T)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const T=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(T),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 m(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Yi({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 Ee),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(Ke(s)||Ze(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return m(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 Wh extends He{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 bi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new br({participantSid:"",trackSids:[this.trackSid]})]});this.emit(w.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?He.SubscriptionStatus.Unsubscribed:super.isSubscribed?He.SubscriptionStatus.Subscribed:He.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?He.PermissionStatus.Allowed:He.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||(Fn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Fn(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 Fn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Or({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Bo(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=au(this.trackInfo,this.requestedMaxQuality);i&&Bo(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 Mi extends Ia{static fromParticipantInfo(e,t,i){return new Mi(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]:Vt.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]:C.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]:C.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 Lh(e,t,s,r):d=new Mh(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)&&Un(d)&&Fe(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=C.kindFromProto(s.type);if(!c)return;o=new Wh(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!==C.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 C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Fe(i.track)&&Un(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 z;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(z||(z={}));const Kh=4*1e3;class At extends Me.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=z.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)=>m(this,void 0,void 0,function*(){var l;if(!pu())throw Le()?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===z.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(z.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==Qo(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rt(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new G(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)=>m(this,void 0,void 0,function*(){var T,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Pt.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(_){if(this.regionUrlProvider&&_ instanceof F&&_.reason!==$.Cancelled&&_.reason!==$.NotAllowed){let y=null;try{this.log.debug("Fetching next region"),y=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(S){if(S instanceof F&&(S.status===401||S.reason===$.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(S);return}}[$.InternalError,$.ServerUnreachable,$.Timeout].includes(_.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Pt.getInstance().addFailedConnectionAttempt(o)),y&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield h(b,v,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,$o(_)),v(_))}else{let y=Ce.UNKNOWN_REASON;_ instanceof F&&(y=$o(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),v(_)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ee((b,v)=>{h(b,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>m(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 T=R.serverInfo;if(T||(T={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(A=>{let[x,_]=A;return"".concat(x,": ").concat(_)}).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}),!T.version)throw new $l("unknown server version");return T.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)=>m(this,void 0,void 0,function*(){var u,h;this.state===z.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({},Qn),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(z.Connected),this.emit(E.Connected),Pt.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 m(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===z.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===z.Connecting||l.state===z.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,Ce.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const o=[],c=_e();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=Ln();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=()=>m(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(z.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>m(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(z.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===bt.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=C.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=ku(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=Cu(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=()=>m(this,void 0,void 0,function*(){var o;((o=_e())===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=>m(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),Ke(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=In(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=>m(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=In(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({},th),e),this.log=je((i=this.options.loggerName)!==null&&i!==void 0?i:Ie.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},la),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ua),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},eh),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Ah,this.outgoingDataStreamManager=new xh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new qh("","",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",Ye(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ye(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Ye(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}),At.cleanupRegistry&&At.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 m(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 Uu(i,t),this.e2eeManager.on(tt.ParticipantEncryptionStatusChanged,(s,r)=>{Eu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(tt.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===z.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 wh(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(z.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(z.Connected)&&this.emit(E.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(z.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 m(this,void 0,void 0,function*(){if(this.state===z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rt(new URL(e))&&t){this.regionUrlProvider=new G(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===z.Disconnected&&(this.regionUrl=i,yield fetch($t(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch($t(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 m(this,void 0,void 0,function*(){let i=()=>m(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new xe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new xe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new xe({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new xe({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=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({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 xe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new _i({reason:Ce.CLIENT_INITIATED,action:yt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new xe({scenario:{case:"subscriberBandwidth",value:ht(t)}});break;case"leave-full-reconnect":s=new xe({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 m(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 T=(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(_=>_.source===C.Source.Microphone);try{b=(yield Promise.all(A.map(_=>{var y;return(y=_.audioTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(_=>_===!0)}catch(_){throw r.options.audioCaptureDefaults.deviceId=T,_}const x=A.some(_=>{var y,S;return(S=(y=_.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});b&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const T=(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(_=>_.source===C.Source.Camera);try{b=(yield Promise.all(A.map(_=>{var y;return(y=_.videoTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(_=>_===!0)}catch(_){throw r.options.videoCaptureDefaults.deviceId=T,_}const x=A.some(_=>{var y,S;return(S=(y=_.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});b&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!On()&&!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 T=(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=T,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===z.Connecting||this.state===z.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===z.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=lu(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!==z.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(z.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 m(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});Yn(l)>pa?(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 m(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=_e();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=tu(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"&&!zt()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!zt())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return m(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=Uo())!==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=Mi.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Mi(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===C.Kind.Audio?(s.on(w.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(w.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.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===Vt.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&&Su(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,Ce.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===z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===z.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return m(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 li({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 ct({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(z.Connected),a.video){const c=new os(C.Kind.Video,new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO,name:"video-dummy"}),new Ni(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Jo(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 os(C.Kind.Audio,new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO}),new Oi(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ln(),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 ct({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:bt.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=Jo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=Ln(),h=new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:we.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=Da(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)}}At.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Da(n){return n.map(e=>{if(e)return Array.isArray(e)?Da(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Oe;(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"})(Oe||(Oe={}));class st extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Oe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new At(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Oe.IDLE)throw Error("check is running already");this.setStatus(Oe.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!==Oe.SKIPPED&&this.setStatus(this.isSuccess()?Oe.SUCCESS:Oe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Oe.SKIPPED)}switchProtocol(e){return m(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 Hh extends st{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new G(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 m(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 as=1e4;class Gh extends st{get description(){return"Connection via UDP vs TCP"}perform(){return m(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/(as/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(as/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(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(()=>m(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,as)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class zh extends st{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Bh();if(yield Lo(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 Jh extends st{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Fh();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 m(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 T=0;T<v.length;T+=4)if(v[T]!==0||v[T+1]!==0||v[T+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 $h extends st{get description(){return"Resuming connection after interruption"}perform(){return m(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!==z.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 Qh extends st{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t,i;Rt(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new G(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new qn,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 Yh extends st{get description(){return"Establishing WebRTC connection"}perform(){return m(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&&(Xh(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 Xh(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 Zh extends st{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(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 qn,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Rt(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new G(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)===yr.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 Ip extends Me.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:Oe.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!==Oe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(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 m(this,void 0,void 0,function*(){return this.createAndRunCheck(Zh)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Yh)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Qh)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck($h)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(zh)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Jh)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Gh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Hh)})}}function K(n,e,t){return(e=tp(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function ep(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 tp(n){var e=ep(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 ip 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(ip,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class np 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(np,"code","ERR_JWT_EXPIRED");class sp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}K(sp,"code","ERR_JOSE_ALG_NOT_ALLOWED");class rp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_NOT_SUPPORTED")}}K(rp,"code","ERR_JOSE_NOT_SUPPORTED");class op 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(op,"code","ERR_JWE_DECRYPTION_FAILED");class ap extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWE_INVALID")}}K(ap,"code","ERR_JWE_INVALID");class cp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWS_INVALID")}}K(cp,"code","ERR_JWS_INVALID");class dp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWT_INVALID")}}K(dp,"code","ERR_JWT_INVALID");class lp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWK_INVALID")}}K(lp,"code","ERR_JWK_INVALID");class up extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWKS_INVALID")}}K(up,"code","ERR_JWKS_INVALID");class hp 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(hp,"code","ERR_JWKS_NO_MATCHING_KEY");class pp 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(pp,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class mp 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(mp,"code","ERR_JWKS_TIMEOUT");class fp 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(fp,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Aa;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Aa||(Aa={}));var Oa;(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"})(Oa||(Oa={}));var Na;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Na||(Na={}));var Li;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Li||(Li={})),Li.UserTimestamp,Li.E2ee;var xa;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(xa||(xa={}));class gp extends ve{constructor(){super(),this._room=null,this._maxAttempts=mt,this._maxDelay=Ot*ot,this._trackRegistry=new qc,this._eventAdapter=new Wc(this._trackRegistry),p.info("LiveKit Service created")}setContext(e){super.setContext(e),this._maxAttempts=e.options.reconnect?.maxAttempts||mt,this._maxDelay=(e.options.reconnect?.delay??Ot)*ot,this._eventAdapter.setContext(e)}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._room&&this._room.isConnected()){p.warn("Already connected to LiveKit room");return}try{p.info(`Connecting to LiveKit room: ${i} at ${e}`);const r=new At({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(ot*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,()=>{p.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),r.on(E.Disconnected,a=>{a?p.info(`LiveKit room disconnected: ${a}`):p.info("LiveKit room disconnected"),a!==Ce.CLIENT_INITIATED&&this._context.eventBus.emit("inner:rtc:disconnected",{reason:a?String(a):void 0}),this._room=null}),p.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||mt}),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){p.warn("Track does not have MediaStreamTrack");return}e.kind==="audio"&&i.on(I.IsSpeakingChanged,o=>{this._context.eventBus.emit("inner:audio:speaking:changed",{participantId:i.identity,isSpeaking:o}),p.info(`Participant ${i.identity} is speaking: ${o}`)});const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){p.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){p.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){p.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){p.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"}),p.info("Disconnected from LiveKit room")}catch(e){p.error("Error disconnecting from LiveKit room:",e),this._room=null}}isConnected(){return this._room?this._room.state===z.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),p.info("LiveKit Service disposed")}}class vp extends ve{constructor(){super(),this._conversationManager=null,p.info("WebSocket Dispatcher created")}setConversationManager(e){this._conversationManager=e,p.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){p.error("Error dispatching message:",t)}}_handleWSServerMessage(e){e.code===101?(this._conversationManager?.handleServerPong(),p.debug("Received pingpong response")):e.code===102&&(p.warn("Server will disconnect"),this._conversationManager?.willDisconnect())}_handleServerTextMessage(e){if(!this._conversationManager){p.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),p.debug(`Answer received (code 200) for uid: ${t}`)):s===201?(this._conversationManager.handleAnswerChunk(t,"",!0),p.debug(`Answer completed (code 201) for uid: ${t}`)):s===300?(this._conversationManager.handleAsrTextReceived(t,i),p.debug(`ASR text chunk received (code 300) for uid: ${t}`)):s===400?(this._conversationManager.handleServerInitiatedMessage(t,i),p.debug(`Server initiated message received (code 300) for uid: ${t}`)):s===500&&(this._conversationManager.handleServerCommand(s,i),p.debug(`Server command received (code 500) for uid: ${t}`))}onDispose(){p.info("WebSocket Dispatcher disposed")}}class bp extends ve{constructor(){super(),this._ws=null,this._dispatcher=null,this._isConnecting=!1,this._activeTimers=new Set,this._retryCount=0,this._maxRetries=mt,this._pingTimer=void 0,this._pongTimer=void 0,this._isExplicitDisconnect=!1,this._maxDelay=Ot*ot}setContext(e){super.setContext(e),this._maxRetries=e.options.reconnect?.maxAttempts??mt,this._maxDelay=(e.options.reconnect?.delay??Ot)*ot,this._dispatcher&&(this._dispatcher.dispose(),this._dispatcher=null),this._dispatcher=new vp,this._dispatcher.setContext(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),p.info("Conversation transport connected"),e()},this._ws.onerror=i=>{this._isConnecting=!1,p.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"}),p.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}),p.info(`Conversation transport closed with non-retry code ${e}: ${t??""}`);return}if(!this._isExplicitDisconnect&&this._retryCount<this._maxRetries){this._retryCount++;const s=Math.min(ot*Math.pow(2,this._retryCount-1),this._maxDelay);p.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(()=>{p.error(`Pong timeout (${vs/ot}s). Reconnecting...`),this._ws?.close()},vs)}handlePongReceived(){clearTimeout(this._pongTimer),this._clearTimer(this._pingTimer),this._pingTimer=setTimeout(()=>{this.sendPing()},qa)}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),p.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);p.debug("Message received:",t.type),this._dispatcher?this._dispatcher.dispatch(t):p.warn("Dispatcher not set, message ignored")}catch(t){p.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){p.debug("WebSocket not connected, binary data dropped");return}try{this._ws.send(e),p.debug("Binary data sent via transport")}catch(t){p.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),p.info("Conversation transport disposed")}}const Ui=["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:camera:started","media:camera:stopped","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"],Ma=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class _p{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:camera:started":{public:"media:camera:started"},"inner:camera:stopped":{public:"media:camera:stopped"},"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)),Ui.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(Ui.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(!Ma.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){p.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Ui.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){p.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(Ui.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!Ma.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class yp extends Y{constructor(e,t){super(),this._requestCounter=0,this._baseURL=e||"",this._defaultHeaders=t||{},p.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,T)=>{h[T]=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};p.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};p.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(){p.info("HTTP Service disposed")}}function Tp(n,e="https"){return n.includes("://")?n:`${e.replace(/:$/,"")}://${n}`}class kp extends ve{constructor(e,t){super(),this._httpService=new yp(e||Ha,t)}getAuthToken(){if(this.ensureNotDisposed(),this._context.authToken)return this._httpService?.setAuthToken(this._context.authToken),Promise.resolve();throw this._context.emitError("Auth token not found",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||""},headers:this._context.options.sandbox?{"X-Env-Sandbox":"true"}:void 0}).then(e=>{if(e.data.code===Zt){const t=e.data.data;return this._context.setLivekitConfig(Tp(t.livekitUrl,"wss"),t.roomToken,t.roomId),this._context.setWsUrl(`${this._context.options.wsUrlPrefix||za}/${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===Zt)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===Zt)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===Zt).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}onDispose(){this._httpService.dispose()}}class La extends Y{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._cameraController=null,this._liveKitService=null,this._conversationTransport=null,this._connectionCoordinator=null,this._httpController=null,this._preConnectPromise=null,this._lastPreConnectSuccessAt=null,this._context=new $a(e),p.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new _p(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}setAuthToken(e){this.ensureNotDisposed(),this._context.setAuthToken(e),this._httpController&&this._httpController.getAuthToken()}async startCamera(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._cameraController)throw new H("Camera controller is not available",B.CAMERA_CONTROLLER_NOT_AVAILABLE);await this._cameraController.startCamera()}stopCamera(){this.ensureNotDisposed(),this._ensureConnected(),this._cameraController&&this._cameraController.stopCamera()}getCameraStream(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getStream()??null}getCameraTrack(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getTrack()??null}attachCameraTo(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._cameraController)throw new H("Camera controller is not available",B.CAMERA_CONTROLLER_NOT_AVAILABLE);this._cameraController.attachTo(e)}async preConnect(){if(this.ensureNotDisposed(),this._preConnectPromise)return this._preConnectPromise;const e=Date.now();return this._lastPreConnectSuccessAt!==null&&e-this._lastPreConnectSuccessAt<Ja?Promise.resolve(!0):(this._preConnectPromise=(async()=>{try{if(p.info("Creating HTTP controller..."),this._httpController=this._httpController??new kp(this._context.options.http?.baseURL,this._context.options.http?.headers),this._httpController.setContext(this._context),p.info("Setting auth token..."),await this._httpController.getAuthToken(),p.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){p.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(p.info("Initializing SDK..."),this._connectionCoordinator=new Ya,this._connectionCoordinator.setContext(this._context),this._context.bindConnectionState(()=>this._connectionCoordinator.getState()),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._videoController=new nc(this._context.options.video),this._videoController.setContext(this._context),this._audioController=new Cc(this._context.options.audio),this._audioController.setContext(this._context),this._cameraController=new Lc,this._cameraController.setContext(this._context),this._conversationController=new jc,this._conversationController.setContext(this._context),this._liveKitService=new gp,this._liveKitService.setContext(this._context),this._conversationTransport=new bp,this._conversationTransport.setContext(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))}if(this._conversationTransport){const e={sendBinary:t=>{this._conversationTransport.sendBinary(t)},isConnected:()=>this._conversationTransport.isConnected};this._audioController&&this._audioController.setWebSocketSender(e),this._cameraController&&this._cameraController.setWebSocketSender(e)}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(),p.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")){p.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService&&await this._liveKitService.disconnect(),this._audioController&&this._audioController.stopCapture(),this._cameraController&&this._cameraController.stopCamera(),this._httpController&&await this._httpController.disconnectConversation(),this._preConnectPromise=null,this._connectionCoordinator.completeDisconnecting(),p.info("SDK disconnected")}catch(e){throw p.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 p.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 p.error("Error during reconnect:",i),this._context.emitError(i,B.SDK_RECONNECT_FAILED)}}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():ys(_s("idle"))}async _cleanup(){if(this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){p.error("Error disconnecting LiveKit:",e)}this._audioController&&this._audioController.stopCapture(),this._cameraController&&this._cameraController.stopCamera()}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=>{p.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._cameraController&&(this._cameraController.dispose(),this._cameraController=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(),p.info("SDK Client disposed")}}function Cp(n){if(!n.avatarName)throw new H("avatarName is required",B.NO_AVATARNAME);return p.info("Creating SDK client with options:",{avatarName:n.avatarName}),new La(n)}class Ua extends Y{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)),p.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),p.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,p.info("Video playback started")}catch(e){throw p.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,p.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,p.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){p.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return p.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=>{p.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=>{p.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,p.info("Local Video Debug Source disposed")}}class Sp extends Y{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new ks;const s={...e,renderMode:"processed"};this._pipeline=new Es(this._source,s),this._outputRenderer=new Bi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),p.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),p.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){p.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){p.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){p.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,p.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,p.info("Video Pipeline Runner disposed")}}class Ep extends Y{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Ua(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new Sp(this._options,t,i),this._options.greenScreen?.enabled){const r=new Vi(this._options.greenScreen);this._pipelineRunner.setProcessor(r),p.info("Green screen processor enabled in debugger")}p.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Ua(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{p.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){p.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){p.error("Failed to switch video source:",a);try{r.dispose()}catch(o){p.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),p.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 Vi(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,p.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),p.info("Video debugger initialized")}catch(e){throw p.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){p.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=>{p.error("Error processing frame:",t)})}),this._isRunning=!0,p.info("Video debugger started")}catch(e){throw p.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,p.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),p.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),p.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),p.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ka,D.DEFAULT_AUDIO_CHANNELS=Wa,D.DEFAULT_AUDIO_SAMPLE_RATE=Fi,D.DEFAULT_RECONNECT_ATTEMPTS=mt,D.DEFAULT_RECONNECT_DELAY=Ot,D.DEFAULT_WS_TIMEOUT=ja,D.Disposable=Y,D.EventBus=fs,D.Logger=p,D.SDKClient=La,D.SDKError=H,D.SessionState=gs,D.StandaloneVideoDebugger=Ep,D.createClient=Cp}));
147
+ `},Gn}var oa;function Qu(){if(oa)return Ae;oa=1;var n=Ju(),e=$u(),t=Hn();return Ae.grammar=t,Ae.write=e,Ae.parse=n.parse,Ae.parseParams=n.parseParams,Ae.parseFmtpConfig=n.parseFmtpConfig,Ae.parsePayloads=n.parsePayloads,Ae.parseRemoteCandidates=n.parseRemoteCandidates,Ae.parseImageAttributes=n.parseImageAttributes,Ae.parseSimulcastStreamList=n.parseSimulcastStreamList,Ae}var it=Qu();function zn(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 T=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(_){return(0,_.resolve)(x)}),l=[]}},u()),T){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 Yu=.7,Xu=20,Dt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class aa extends Me.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=zn(s=>m(this,void 0,void 0,function*(){this.emit(Dt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Xu),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=je((i=t.loggerName)!==null&&i!==void 0?i:Ie.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 m(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 m(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}=Zu(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=it.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Jn(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=it.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(Dt.NegotiationComplete),e.sdp&&it.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(Dt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return m(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=it.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{da(o),o.type==="audio"?ca(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||(De(c.codec)&&!ut()&&this.ensureVideoDDExtensionForSVC(o,a),!De(c.codec)))return!0;const l=Math.round(c.maxbr*Yu);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,it.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=it.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{da(s),s.type==="audio"&&ca(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,it.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 m(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 m(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 kt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Vo))){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:Vo})}}}function ca(n,e,t){const i=Jn(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 Zu(n){var e;const t=[],i=[],s=it.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Jn(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 da(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 Jn(n){return typeof n=="number"?n.toFixed(0):n}const $n="vp8",eh={audioPreset:Sn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Rn.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:$n,backupCodec:!0,preConnectBuffer:!1},la={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ua={deviceId:{ideal:"default"},resolution:Kt.h720.resolution},th={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Nl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Qn={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 ih{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=Qn.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=je((s=i.loggerName)!==null&&s!==void 0?s:Ie.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new aa(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new aa(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,Pe.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,Pe.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 m(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 m(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){var i;t===Pe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return m(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 m(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 m(this,void 0,void 0,function*(){return new ue((t,i)=>m(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new kt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new kt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(Dt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Dt.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===Pe.PUBLISHER?this.publisher.getConnectedAddress():e===Pe.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 m(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)=>m(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 ha=5e3,nh=3e4;class G{static fetchRegionSettings(e,t,i){return m(this,void 0,void 0,function*(){const s=yield G.fetchLock.lock();try{const r=yield fetch("".concat(sh(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=wu(r.headers),o=a?a*1e3:ha;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 m(this,void 0,void 0,function*(){const s=G.settingsTimeouts.get(e.hostname);clearTimeout(s),G.settingsTimeouts.set(e.hostname,setTimeout(()=>m(this,void 0,void 0,function*(){try{const r=yield G.fetchRegionSettings(e,t);G.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof F&&r.reason===$.NotAllowed){V.debug("token is not valid, cancelling auto region refresh");return}V.debug("auto refetching of region settings failed",{error:r}),G.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){G.cache.set(e.hostname,i),G.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=G.settingsTimeouts.get(e);t&&(clearTimeout(t),G.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=G.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=G.connectionTrackers.get(e);i&&i.connectionCount===0&&(V.debug("stopping region refetch after disconnect delay",{hostname:e}),G.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},nh))}static cancelCleanup(e){const t=G.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=G.connectionTrackers.get(e);t||(t={connectionCount:0},G.connectionTrackers.set(e,t)),t.connectionCount++,G.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=G.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&G.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Rt(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){return G.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=G.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),G.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){G.updateCachedRegionSettings(this.serverUrl,this.token,e)}}G.cache=new Map,G.settingsTimeouts=new Map,G.connectionTrackers=new Map,G.fetchLock=new he;function sh(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=ma(t,ie.MAX_MESSAGE_BYTES),this.data=i?ma(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new vr({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 pa=15360;function Yn(n){return new TextEncoder().encode(n).length}function ma(n,e){if(Yn(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 Xn=2e3;function Ai(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 Zn=typeof MediaRecorder<"u";class rh{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const oh=Zn?MediaRecorder:rh;class ah extends oh{constructor(e,t){if(!Zn)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=>m(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 ch(){return Zn}const dh=1e3,lh=1e4;class fa extends C{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=zn(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(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=>m(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!==C.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 m(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Et(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&&(St(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=>{St(s??e,r)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dh;return(function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=_e())===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 We("unable to get track dimensions after timeout")})()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ye(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ye(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(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===C.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new We("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 m(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=xl(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===C.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{Et(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===C.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 m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),qo()&&(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 m(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=_e();if(i?.name==="Safari"&&Ue(i.version,"12.0")<0)throw new Cn("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 m(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 m(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 m(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(St(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&&(Et(i._mediaStreamTrack,d),St(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 m(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 m(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(!ch()){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 ah(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},lh)}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 Oi extends fa{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,C.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(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=Ai(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 m(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===C.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 m(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!==Ye(this._constraints.deviceId);return this.source===C.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 m(this,void 0,void 0,function*(){let t;if(e){const i=Pn({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 m(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()},Xn)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Le()&&!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 m(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 m(this,void 0,void 0,function*(){const e=yield Lo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(w.AudioSilenceDetected)),e})}}function uh(n,e,t){switch(n.kind){case"audio":return new Oi(n,e,!1,void 0,t);case"video":return new Ni(n,e,!1,t);default:throw new We("unsupported track type: ".concat(n.kind))}}const hh=Object.values(Kt),ph=Object.values(En),mh=Object.values(Rn),fh=[Kt.h180,Kt.h360],gh=[En.h180,En.h360],vh=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new J(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)}),es=["q","h","f"];function ts(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=_h(n,e,t,d),V.debug("using video encoding",a));const l=a.maxFramerate,u=new J(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&De(d)){const b=new ba(c),v=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=_e();if(zt()||Le()||R?.name==="Chrome"&&Ue(R?.version,"113")<0){const T=b.suffix=="h"?2:3,A=fu(R);for(let x=0;x<b.spatial;x+=1)v.push({rid:es[2-x],maxBitrate:a.maxBitrate/Math.pow(T,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=va(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:ga(n,u):h=(r=va(i?.videoSimulcastLayers))!==null&&r!==void 0?r:ga(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 is(e,t,[b,f,u],l);if(v>=480)return is(e,t,[b,u],l)}return is(e,t,[u])}function bh(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===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ts(n.source===C.Source.ScreenShare,c,d,t)}function _h(n,e,t,i){const s=yh(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 yh(n,e,t){if(n)return mh;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?hh:ph}function ga(n,e){if(n)return vh(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)?fh:gh}function is(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=es.length)return;const o=Math.min(n,e),d={rid:es[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=lt()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Le()&&Ko()==="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 va(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 ba{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 Th(n){return n.source===C.Source.ScreenShare||n.constraints.height&&Ye(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const kh=5e3;class Ni extends fa{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,C.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>m(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+=Ai(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()},Xn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=qe(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 m(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=qe(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 m(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===C.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 m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.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 m(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 an({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(De(this.codec),t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Pn({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=qe(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 m(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=qe(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 m(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)},kh))}setPublishingCodecs(e){return m(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(De(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=qe(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(De(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 _a(u.sender,u.encodings,l.qualities,this.senderLock,De(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 m(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 _a(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return m(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&&De(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 m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),qo()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function _a(n,e,t,i,s,r,a){return m(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=ya(v),T=t.find(A=>A.quality===R);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,r.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),lt()&&(T.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 ya(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function Ta(n,e,t,i){if(!t)return[new Je({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new ba(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 Je({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=ya((a=s.rid)!==null&&a!==void 0?a:"");return new Je({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 ka="_lossy",Ca="_reliable",Ch=2*1e3,ns="leave-reconnect",Sh=3e4,Eh=8*1024,Rh=256*1024;var Re;(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"})(Re||(Re={}));class wh extends Me.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Qn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Re.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 ia,this.reliableReceivedState=new zu(Sh),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>m(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===Ca)r.reliableDCSub=a;else if(a.label===ka)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=>m(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=mr.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"&&Sa(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"&&Sa(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===ns&&(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===Re.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=()=>m(this,void 0,void 0,function*(){!this.url||!(yield fetch($t(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Q.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Q.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(at.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>m(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch($t(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=je((t=e.loggerName)!==null&&t!==void 0?t:Ie.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new qn(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 m(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===$.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===$.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return m(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 m(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 ia,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 m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new We("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 m(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 m(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 ih(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)=>m(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===Re.New;this.pcState=Re.Connected,u&&this.emit(P.Connected,e)}else a===te.FAILED&&(this.pcState===Re.Connected||this.pcState===Re.Reconnecting)&&(this.pcState=Re.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?at.RR_SUBSCRIBER_FAILED:at.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Q.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)},Ph((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>m(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)=>m(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",at.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:ha,regionSettings:e.regions})),e.action){case yt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close();break;case yt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ns);break;case yt.RESUME:this.handleDisconnect(ns)}}}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===Bt.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(ka,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ca,{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,Eh),Rh)}},1e3))}createSender(e,t,i){return m(this,void 0,void 0,function*(){if(Dn())return yield this.createTransceiverRTCRtpSender(e,t,i);if(An())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 m(this,void 0,void 0,function*(){if(Dn())return this.createSimulcastTransceiverSender(e,t,i,s);if(An())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 m(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Xe(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 m(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 m(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(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)===Bt.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 Ct||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",at.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 m(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 Ct;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof F&&a.reason===$.NotAllowed?new re("could not reconnect, token might be expired"):new Ct}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!==Q.CONNECTED)throw new Ct("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 m(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===$.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof F&&s.reason===$.LeaveRequest?s:new Ct(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!==Q.CONNECTED)throw new Ct("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 m(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Re.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(Ch),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Re.Connected}catch(e){throw this.pcState=Re.Disconnected,F.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return m(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Zi({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new Xi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Lu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new pr({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 m(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)=>m(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 m(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 m(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 m(this,void 0,void 0,function*(){return new ue((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new kt("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 kt("cannot negotiate on closed engine")),this.on(P.Closing,s),this.pcManager.publisher.once(Dt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();yu(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof kt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",at.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 cn({answer:this.pcManager.mode==="publisher-only"?c?It({sdp:c.sdp,type:c.type}):void 0:l?It({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?It({sdp:o.sdp,type:o.type}):void 0:d?It({sdp:d.sdp,type:d.type}):void 0,subscription:new bi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:nu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((b,v)=>new Fr({publisherSid:v,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Br({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),Pe.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),Pe.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),Pe.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),Pe.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 Ph(n){return n!==void 0&&n>13}function Sa(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 Ea{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 Ih extends Ea{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 Ee,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:()=>m(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 m(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(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=qe(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 Dh extends Ea{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Di(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 Ee,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:()=>m(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 m(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(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=qe(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 Ah{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 m(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 m(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 Ee;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:Di(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 Ih(c,d,Di(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 Ee;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 Dh(c,d,Di(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 Ra{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 m(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 Oh extends Ra{}class Nh extends Ra{}const wa=15e3;class xh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return m(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)=>m(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 m(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 pi({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:ht(a.timestamp),totalLength:ht(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Rr({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?en.UPDATE:en.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 m(this,void 0,void 0,function*(){for(const R of Ru(v,wa)){const T=new mi({content:R,streamId:r,chunkIndex:ht(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return m(this,void 0,void 0,function*(){const v=new fi({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=()=>m(this,void 0,void 0,function*(){yield b.close()});u.once(P.Closing,f);const b=new Oh(h,a,()=>this.engine.off(P.Closing,f));return b})}sendFile(e,t){return m(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return m(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 m(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 pi({totalLength:ht((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:ht(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new wr({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,T=new WritableStream({write(x){return m(this,void 0,void 0,function*(){const _=yield b.lock();let y=0;try{for(;y<x.byteLength;){const S=x.slice(y,y+wa),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new mi({content:S,streamId:c,chunkIndex:ht(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,y+=S.byteLength}}finally{_()}})},close(){return m(this,void 0,void 0,function*(){const x=new fi({streamId:c}),_=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(_,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new Nh(T,l)})}}class Pa extends C{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 m(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(),Xn)),su()&&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 Mh extends Pa{constructor(e,t,i,s,r,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>m(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=Ai(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;Le()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Le())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(On(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&On(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 m(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 ss=100;class Lh extends Pa{constructor(e,t,i,s,r){super(e,t,C.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>m(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=Ai(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=zn(()=>{this.updateDimensions()},ss),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Et(this._mediaStreamTrack,t):St(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 Uh(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 m(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 m(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<ss){de.setTimeout(()=>{this.updateVisibility()},ss);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"?Ho():t||(Ho()>2?2:1)}}class Uh{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=Xt(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=Xt(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Xt(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??rs(e),this.isPiP=ye()&&Xt(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=rs(this.element),this.isPiP=Xt(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,zo().observe(this.element),Go().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=zo())===null||e===void 0||e.unobserve(this.element),(t=Go())===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 Xt(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?rs(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function rs(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 He extends Me.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=je((r=s?.loggerName)!==null&&r!==void 0?r:Ie.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.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(Fe(this.track))return this.track}get videoTrack(){if(Xe(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.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={}))})(He||(He={}));class os extends He{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&&Xe(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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Fe(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 xi(n,e){return m(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Fo(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=Mo(r,la,ua),d=Pn(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=>m(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 T=h.getSettings().deviceId;v?.deviceId&&Ye(v.deviceId)!==T?v.deviceId=T:v||(v={deviceId:T});const A=uh(h,v,e);return A.kind===C.Kind.Video?A.source=C.Source.Camera:A.kind===C.Kind.Audio&&(A.source=C.Source.Microphone),A.mediaStream=u,Fe(A)&&i?yield A.setProcessor(i):Xe(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return xi(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function Fh(n){return m(this,void 0,void 0,function*(){return(yield xi({audio:!1,video:!0}))[0]})}function Bh(n){return m(this,void 0,void 0,function*(){return(yield xi({audio:!0,video:!1}))[0]})}var nt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(nt||(nt={}));function Vh(n){switch(n){case Ft.EXCELLENT:return nt.Excellent;case Ft.GOOD:return nt.Good;case Ft.POOR:return nt.Poor;case Ft.LOST:return nt.Lost;default:return nt.Unknown}}class Ia extends Me.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===Vt.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===bt.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]:Vt.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=nt.Unknown,this.log=V,this.log=je((c=a?.loggerName)!==null&&c!==void 0?c:Ie.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 Ee,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(C.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.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===bt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==bt.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=ru(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=Vh(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=>Fe(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 C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function jh(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 Lr({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 qh extends Ia{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 Ee)},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 Ee),(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!==dn.OK&&u.reject(new No(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=>jh(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=>m(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=qe(b),T;T=yield R.next(),c=T.done,!c;v=!0){u=T.value,v=!1;const A=u;eu(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=>m(this,void 0,void 0,function*(){if(o.source===C.Source.ScreenShare||o.source===C.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(Ke(o)||Ze(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===C.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))),Ke(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 m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>m(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 No("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(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return m(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 m(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 C.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new We(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,In(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===C.Source.Microphone&&Fe(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===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.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(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Mo(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 xi(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Fe(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(I.AudioStreamAcquired)),Xe(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cn("getDisplayMedia not supported");e.resolution===void 0&&!mu()&&(e.resolution=Rn.h1080fps30.resolution);const t=iu(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new We("no video track found");const r=new Ni(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new Oi(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(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;Ke(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),wt(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let T;switch(i.source){case C.Source.Microphone:T="audioinput";break;case C.Source.Camera:T="videoinput"}T&&r.activeDeviceMap.has(T)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(T)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Oi(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Ni(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new We("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(T=>{T.track&&T.track===i&&(h=T)}),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)),!gu()&&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((T,A)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Q.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:W(i)}));let x=!1;const _=setTimeout(()=>{x=!0,i.stop(),A(new Oo("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(_),x)return;const y=yield this.publish(i,f,v);T(y)}else try{const x=yield this.publish(i,f,v);T(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(T){throw T}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ee),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=>ou(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 m(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Oo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>wt(e)&&M.source===e.source)&&e.source!==C.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&&Fe(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&lt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!uu()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!hu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=$n),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===Ht(M.mime))||(t.videoCodec=Ht(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=[],T=!(!((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),T&&R.push(ae.TF_NO_DTX),Ke(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new jt({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:T,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 _;if(e.kind===C.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:Kt.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,Ze(e)&&(De(v)&&(e.source===C.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 nn({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:$n}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new nn({codec:t.backupCodec.codec,cid:""})))),_=ts(e.source===C.Source.ScreenShare,x.width,x.height,t),x.layers=Ta(x.width,x.height,_,De(t.videoCodec))}else e.kind===C.Kind.Audio&&(_=[{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 y=()=>m(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,_),this.emit(I.LocalSenderCreated,e.sender,e),Ze(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=Th(e)),e.setDegradationPreference(t.degradationPreference)),_)if(lt()&&e.kind===C.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=_[0])===null||O===void 0)&&O.maxBitrate?_[0].maxBitrate/1e3:0})}else e.codec&&De(e.codec)&&(!((L=_[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:_[0].maxBitrate/1e3});yield this.engine.negotiate()});let S;const N=new Promise((M,O)=>m(this,void 0,void 0,function*(){var L;try{S=yield this.engine.addTrack(x),M(S)}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)S=(yield Promise.all([N,y()]))[0];else{S=yield N;let M;if(S.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===C.Kind.Video){const O=Ht(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,_=ts(e.source===C.Source.ScreenShare,x.width,x.height,t))}yield y()}const U=new os(e.kind,S,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(U.on(w.CpuConstrained,M=>this.onTrackCpuConstrained(M,U)),U.options=t,e.sid=S.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:_,trackInfo:S})),Ze(e)?e.startMonitor(this.engine.client):Ke(e)&&e.startMonitor(),this.addTrackPublication(U),this.emit(I.LocalTrackPublished,U),Ke(e)&&S.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,L=>{if(L.trackSid===S.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)=>m(this,void 0,void 0,function*(){var ke,pt,ge,rt,cs,ds;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),W(e)));const ps=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),Rp=yield this.waitUntilActiveAgentPresent();clearTimeout(ps),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),W(e)));const Fa=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Rp.identity],attributes:{trackId:U.trackSid,sampleRate:String((cs=A.sampleRate)!==null&&cs!==void 0?cs:"48000"),channels:String((ds=A.channelCount)!==null&&ds!==void 0?ds:"1")}});try{for(var ls=!0,us=qe(M),hs;hs=yield us.next(),ke=hs.done,!ke;ls=!0){rt=hs.value,ls=!1;const ms=rt;yield Fa.write(ms)}}catch(ms){pt={error:ms}}finally{try{!ls&&!ke&&(ge=us.return)&&(yield ge.call(us))}finally{if(pt)throw pt.error}}yield Fa.close(),q()}catch(ps){Z(ps)}})).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 m(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 We("track is not published");if(!Ze(e))throw new We("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=bh(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 jt({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=Ta(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>m(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 m(this,void 0,void 0,function*(){var i,s;if(wt(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),Ze(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 C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.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 m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return m(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)=>m(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=>m(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(Ke(d)||Ze(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 m(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 Qi({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 m(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new gr({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return m(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 hi(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 m(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 hi(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 m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return m(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)=>m(this,void 0,void 0,function*(){var l,u,h,f;if(Yn(s)>pa){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&&Ue((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(T)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const T=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(T),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 m(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Yi({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 Ee),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(Ke(s)||Ze(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return m(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 Wh extends He{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 bi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new br({participantSid:"",trackSids:[this.trackSid]})]});this.emit(w.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?He.SubscriptionStatus.Unsubscribed:super.isSubscribed?He.SubscriptionStatus.Subscribed:He.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?He.PermissionStatus.Allowed:He.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||(Fn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Fn(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 Fn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Or({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Bo(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=au(this.trackInfo,this.requestedMaxQuality);i&&Bo(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 Mi extends Ia{static fromParticipantInfo(e,t,i){return new Mi(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]:Vt.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]:C.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]:C.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 Lh(e,t,s,r):d=new Mh(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)&&Un(d)&&Fe(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=C.kindFromProto(s.type);if(!c)return;o=new Wh(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!==C.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 C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Fe(i.track)&&Un(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 z;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(z||(z={}));const Kh=4*1e3;class At extends Me.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=z.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)=>m(this,void 0,void 0,function*(){var l;if(!pu())throw Le()?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===z.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(z.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==Qo(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rt(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new G(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)=>m(this,void 0,void 0,function*(){var T,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Pt.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(_){if(this.regionUrlProvider&&_ instanceof F&&_.reason!==$.Cancelled&&_.reason!==$.NotAllowed){let y=null;try{this.log.debug("Fetching next region"),y=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(S){if(S instanceof F&&(S.status===401||S.reason===$.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(S);return}}[$.InternalError,$.ServerUnreachable,$.Timeout].includes(_.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Pt.getInstance().addFailedConnectionAttempt(o)),y&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield h(b,v,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,$o(_)),v(_))}else{let y=Ce.UNKNOWN_REASON;_ instanceof F&&(y=$o(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),v(_)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ee((b,v)=>{h(b,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>m(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 T=R.serverInfo;if(T||(T={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(A=>{let[x,_]=A;return"".concat(x,": ").concat(_)}).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}),!T.version)throw new $l("unknown server version");return T.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)=>m(this,void 0,void 0,function*(){var u,h;this.state===z.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({},Qn),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(z.Connected),this.emit(E.Connected),Pt.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 m(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===z.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===z.Connecting||l.state===z.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,Ce.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const o=[],c=_e();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=Ln();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=()=>m(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(z.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>m(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(z.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===bt.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=C.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=ku(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=Cu(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=()=>m(this,void 0,void 0,function*(){var o;((o=_e())===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=>m(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),Ke(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=In(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=>m(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=In(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({},th),e),this.log=je((i=this.options.loggerName)!==null&&i!==void 0?i:Ie.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},la),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ua),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},eh),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Ah,this.outgoingDataStreamManager=new xh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new qh("","",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",Ye(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ye(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Ye(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}),At.cleanupRegistry&&At.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 m(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 Uu(i,t),this.e2eeManager.on(tt.ParticipantEncryptionStatusChanged,(s,r)=>{Eu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(tt.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===z.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 wh(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(z.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(z.Connected)&&this.emit(E.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(z.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 m(this,void 0,void 0,function*(){if(this.state===z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rt(new URL(e))&&t){this.regionUrlProvider=new G(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===z.Disconnected&&(this.regionUrl=i,yield fetch($t(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch($t(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 m(this,void 0,void 0,function*(){let i=()=>m(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new xe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new xe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new xe({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new xe({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=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new xe({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 xe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new _i({reason:Ce.CLIENT_INITIATED,action:yt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new xe({scenario:{case:"subscriberBandwidth",value:ht(t)}});break;case"leave-full-reconnect":s=new xe({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 m(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 T=(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(_=>_.source===C.Source.Microphone);try{b=(yield Promise.all(A.map(_=>{var y;return(y=_.audioTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(_=>_===!0)}catch(_){throw r.options.audioCaptureDefaults.deviceId=T,_}const x=A.some(_=>{var y,S;return(S=(y=_.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});b&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const T=(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(_=>_.source===C.Source.Camera);try{b=(yield Promise.all(A.map(_=>{var y;return(y=_.videoTrack)===null||y===void 0?void 0:y.setDeviceId(R)}))).every(_=>_===!0)}catch(_){throw r.options.videoCaptureDefaults.deviceId=T,_}const x=A.some(_=>{var y,S;return(S=(y=_.track)===null||y===void 0?void 0:y.isMuted)!==null&&S!==void 0?S:!1});b&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!On()&&!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 T=(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=T,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===z.Connecting||this.state===z.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===z.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=lu(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!==z.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(z.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 m(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});Yn(l)>pa?(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 m(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=_e();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=tu(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"&&!zt()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!zt())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return m(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=Uo())!==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=Mi.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Mi(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===C.Kind.Audio?(s.on(w.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(w.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.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===Vt.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&&Su(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,Ce.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===z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===z.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return m(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 li({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 ct({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(z.Connected),a.video){const c=new os(C.Kind.Video,new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO,name:"video-dummy"}),new Ni(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Jo(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 os(C.Kind.Audio,new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO}),new Oi(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ln(),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 ct({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:bt.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=Jo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new _t({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:we.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=Ln(),h=new _t({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:we.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=Da(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)}}At.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Da(n){return n.map(e=>{if(e)return Array.isArray(e)?Da(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Oe;(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"})(Oe||(Oe={}));class st extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Oe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new At(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Oe.IDLE)throw Error("check is running already");this.setStatus(Oe.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!==Oe.SKIPPED&&this.setStatus(this.isSuccess()?Oe.SUCCESS:Oe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Oe.SKIPPED)}switchProtocol(e){return m(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 Hh extends st{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new G(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 m(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 as=1e4;class Gh extends st{get description(){return"Connection via UDP vs TCP"}perform(){return m(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/(as/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(as/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(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(()=>m(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,as)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class zh extends st{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Bh();if(yield Lo(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 Jh extends st{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Fh();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 m(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 T=0;T<v.length;T+=4)if(v[T]!==0||v[T+1]!==0||v[T+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 $h extends st{get description(){return"Resuming connection after interruption"}perform(){return m(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!==z.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 Qh extends st{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t,i;Rt(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new G(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new qn,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 Yh extends st{get description(){return"Establishing WebRTC connection"}perform(){return m(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&&(Xh(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 Xh(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 Zh extends st{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(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 qn,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Rt(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new G(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)===yr.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 Ip extends Me.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:Oe.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!==Oe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(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 m(this,void 0,void 0,function*(){return this.createAndRunCheck(Zh)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Yh)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Qh)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck($h)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(zh)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Jh)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Gh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Hh)})}}function K(n,e,t){return(e=tp(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function ep(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 tp(n){var e=ep(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 ip 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(ip,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class np 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(np,"code","ERR_JWT_EXPIRED");class sp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}K(sp,"code","ERR_JOSE_ALG_NOT_ALLOWED");class rp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_NOT_SUPPORTED")}}K(rp,"code","ERR_JOSE_NOT_SUPPORTED");class op 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(op,"code","ERR_JWE_DECRYPTION_FAILED");class ap extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWE_INVALID")}}K(ap,"code","ERR_JWE_INVALID");class cp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWS_INVALID")}}K(cp,"code","ERR_JWS_INVALID");class dp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWT_INVALID")}}K(dp,"code","ERR_JWT_INVALID");class lp extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWK_INVALID")}}K(lp,"code","ERR_JWK_INVALID");class up extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWKS_INVALID")}}K(up,"code","ERR_JWKS_INVALID");class hp 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(hp,"code","ERR_JWKS_NO_MATCHING_KEY");class pp 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(pp,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class mp 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(mp,"code","ERR_JWKS_TIMEOUT");class fp 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(fp,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Aa;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Aa||(Aa={}));var Oa;(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"})(Oa||(Oa={}));var Na;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Na||(Na={}));var Li;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Li||(Li={})),Li.UserTimestamp,Li.E2ee;var xa;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(xa||(xa={}));class gp extends ve{constructor(){super(),this._room=null,this._maxAttempts=mt,this._maxDelay=Ot*ot,this._trackRegistry=new qc,this._eventAdapter=new Wc(this._trackRegistry),p.info("LiveKit Service created")}setContext(e){super.setContext(e),this._maxAttempts=e.options.reconnect?.maxAttempts||mt,this._maxDelay=(e.options.reconnect?.delay??Ot)*ot,this._eventAdapter.setContext(e)}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._room&&this._room.isConnected()){p.warn("Already connected to LiveKit room");return}try{p.info(`Connecting to LiveKit room: ${i} at ${e}`);const r=new At({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(ot*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,()=>{p.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),r.on(E.Disconnected,a=>{a?p.info(`LiveKit room disconnected: ${a}`):p.info("LiveKit room disconnected"),a!==Ce.CLIENT_INITIATED&&this._context.eventBus.emit("inner:rtc:disconnected",{reason:a?String(a):void 0}),this._room=null}),p.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||mt}),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){p.warn("Track does not have MediaStreamTrack");return}e.kind==="audio"&&i.on(I.IsSpeakingChanged,o=>{this._context.eventBus.emit("inner:audio:speaking:changed",{participantId:i.identity,isSpeaking:o}),p.info(`Participant ${i.identity} is speaking: ${o}`)});const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){p.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){p.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){p.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){p.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"}),p.info("Disconnected from LiveKit room")}catch(e){p.error("Error disconnecting from LiveKit room:",e),this._room=null}}isConnected(){return this._room?this._room.state===z.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),p.info("LiveKit Service disposed")}}class vp extends ve{constructor(){super(),this._conversationManager=null,p.info("WebSocket Dispatcher created")}setConversationManager(e){this._conversationManager=e,p.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){p.error("Error dispatching message:",t)}}_handleWSServerMessage(e){e.code===101?(this._conversationManager?.handleServerPong(),p.debug("Received pingpong response")):e.code===102&&(p.warn("Server will disconnect"),this._conversationManager?.willDisconnect())}_handleServerTextMessage(e){if(!this._conversationManager){p.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),p.debug(`Answer received (code 200) for uid: ${t}`)):s===201?(this._conversationManager.handleAnswerChunk(t,"",!0),p.debug(`Answer completed (code 201) for uid: ${t}`)):s===300?(this._conversationManager.handleAsrTextReceived(t,i),p.debug(`ASR text chunk received (code 300) for uid: ${t}`)):s===400?(this._conversationManager.handleServerInitiatedMessage(t,i),p.debug(`Server initiated message received (code 300) for uid: ${t}`)):s===500&&(this._conversationManager.handleServerCommand(s,i),p.debug(`Server command received (code 500) for uid: ${t}`))}onDispose(){p.info("WebSocket Dispatcher disposed")}}class bp extends ve{constructor(){super(),this._ws=null,this._dispatcher=null,this._isConnecting=!1,this._activeTimers=new Set,this._retryCount=0,this._maxRetries=mt,this._pingTimer=void 0,this._pongTimer=void 0,this._isExplicitDisconnect=!1,this._maxDelay=Ot*ot}setContext(e){super.setContext(e),this._maxRetries=e.options.reconnect?.maxAttempts??mt,this._maxDelay=(e.options.reconnect?.delay??Ot)*ot,this._dispatcher&&(this._dispatcher.dispose(),this._dispatcher=null),this._dispatcher=new vp,this._dispatcher.setContext(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),p.info("Conversation transport connected"),e()},this._ws.onerror=i=>{this._isConnecting=!1,p.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"}),p.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}),p.info(`Conversation transport closed with non-retry code ${e}: ${t??""}`);return}if(!this._isExplicitDisconnect&&this._retryCount<this._maxRetries){this._retryCount++;const s=Math.min(ot*Math.pow(2,this._retryCount-1),this._maxDelay);p.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(()=>{p.error(`Pong timeout (${vs/ot}s). Reconnecting...`),this._ws?.close()},vs)}handlePongReceived(){clearTimeout(this._pongTimer),this._clearTimer(this._pingTimer),this._pingTimer=setTimeout(()=>{this.sendPing()},qa)}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),p.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);p.debug("Message received:",t.type),this._dispatcher?this._dispatcher.dispatch(t):p.warn("Dispatcher not set, message ignored")}catch(t){p.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){p.debug("WebSocket not connected, binary data dropped");return}try{this._ws.send(e),p.debug("Binary data sent via transport")}catch(t){p.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),p.info("Conversation transport disposed")}}const Ui=["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:camera:started","media:camera:stopped","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"],Ma=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class _p{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:camera:started":{public:"media:camera:started"},"inner:camera:stopped":{public:"media:camera:stopped"},"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)),Ui.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(Ui.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(!Ma.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){p.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Ui.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){p.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(Ui.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!Ma.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class yp extends Y{constructor(e,t){super(),this._requestCounter=0,this._baseURL=e||"",this._defaultHeaders=t||{},p.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,T)=>{h[T]=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};p.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};p.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(){p.info("HTTP Service disposed")}}function Tp(n,e="https"){return n.includes("://")?n:`${e.replace(/:$/,"")}://${n}`}class kp extends ve{constructor(e,t){super(),this._httpService=new yp(e||Ha,t)}getAuthToken(){if(this.ensureNotDisposed(),this._context.authToken)return this._httpService?.setAuthToken(this._context.authToken),Promise.resolve();throw this._context.emitError("Auth token not found",B.SDK_AUTH_TOKEN_FAILED)}getLivekitConfig(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/start",method:"POST",data:{avatarId:this._context.options.avatarName,voice:this._context.options.avatarVoice||""},headers:this._context.options.sandbox?{"X-Env-Sandbox":"true"}:void 0}).then(e=>{if(e.data.code===Zt){const t=e.data.data;return this._context.setLivekitConfig(Tp(t.livekitUrl,"wss"),t.roomToken,t.roomId),this._context.setWsUrl(`${this._context.options.wsUrlPrefix||za}/${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===Zt)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===Zt)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===Zt).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}onDispose(){this._httpService.dispose()}}class La extends Y{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._cameraController=null,this._liveKitService=null,this._conversationTransport=null,this._connectionCoordinator=null,this._httpController=null,this._preConnectPromise=null,this._lastPreConnectSuccessAt=null,this._context=new $a(e),p.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new _p(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}setAuthToken(e){this.ensureNotDisposed(),this._context.setAuthToken(e),this._httpController&&this._httpController.getAuthToken()}async startCamera(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._cameraController)throw new H("Camera controller is not available",B.CAMERA_CONTROLLER_NOT_AVAILABLE);await this._cameraController.startCamera()}stopCamera(){this.ensureNotDisposed(),this._ensureConnected(),this._cameraController&&this._cameraController.stopCamera()}getCameraStream(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getStream()??null}getCameraTrack(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getTrack()??null}attachCameraTo(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._cameraController)throw new H("Camera controller is not available",B.CAMERA_CONTROLLER_NOT_AVAILABLE);this._cameraController.attachTo(e)}async preConnect(){if(this.ensureNotDisposed(),this._preConnectPromise)return this._preConnectPromise;const e=Date.now();return this._lastPreConnectSuccessAt!==null&&e-this._lastPreConnectSuccessAt<Ja?Promise.resolve(!0):(this._preConnectPromise=(async()=>{try{if(p.info("Creating HTTP controller..."),this._httpController=this._httpController??new kp(this._context.options.http?.baseURL,this._context.options.http?.headers),this._httpController.setContext(this._context),p.info("Setting auth token..."),await this._httpController.getAuthToken(),p.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){p.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(p.info("Initializing SDK..."),this._connectionCoordinator=new Ya,this._connectionCoordinator.setContext(this._context),this._context.bindConnectionState(()=>this._connectionCoordinator.getState()),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._videoController=new nc(this._context.options.video),this._videoController.setContext(this._context),this._audioController=new Cc(this._context.options.audio),this._audioController.setContext(this._context),this._cameraController=new Lc,this._cameraController.setContext(this._context),this._conversationController=new jc,this._conversationController.setContext(this._context),this._liveKitService=new gp,this._liveKitService.setContext(this._context),this._conversationTransport=new bp,this._conversationTransport.setContext(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))}if(this._conversationTransport){const e={sendBinary:t=>{this._conversationTransport.sendBinary(t)},isConnected:()=>this._conversationTransport.isConnected};this._audioController&&this._audioController.setWebSocketSender(e),this._cameraController&&this._cameraController.setWebSocketSender(e)}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(),p.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")){p.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService&&await this._liveKitService.disconnect(),this._audioController&&this._audioController.stopCapture(),this._cameraController&&this._cameraController.stopCamera(),this._httpController&&await this._httpController.disconnectConversation(),this._preConnectPromise=null,this._connectionCoordinator.completeDisconnecting(),p.info("SDK disconnected")}catch(e){throw p.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 p.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 p.error("Error during reconnect:",i),this._context.emitError(i,B.SDK_RECONNECT_FAILED)}}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():ys(_s("idle"))}async _cleanup(){if(this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){p.error("Error disconnecting LiveKit:",e)}this._audioController&&this._audioController.stopCapture(),this._cameraController&&this._cameraController.stopCamera()}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=>{p.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._cameraController&&(this._cameraController.dispose(),this._cameraController=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(),p.info("SDK Client disposed")}}function Cp(n){if(!n.avatarName)throw new H("avatarName is required",B.NO_AVATARNAME);return p.info("Creating SDK client with options:",{avatarName:n.avatarName}),new La(n)}class Ua extends Y{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)),p.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),p.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,p.info("Video playback started")}catch(e){throw p.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,p.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,p.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){p.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return p.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=>{p.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=>{p.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,p.info("Local Video Debug Source disposed")}}class Sp extends Y{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new ks;const s={...e,renderMode:"processed"};this._pipeline=new Es(this._source,s),this._outputRenderer=new Bi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),p.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),p.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){p.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){p.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){p.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,p.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,p.info("Video Pipeline Runner disposed")}}class Ep extends Y{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Ua(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new Sp(this._options,t,i),this._options.greenScreen?.enabled){const r=new Vi(this._options.greenScreen);this._pipelineRunner.setProcessor(r),p.info("Green screen processor enabled in debugger")}p.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Ua(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{p.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){p.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){p.error("Failed to switch video source:",a);try{r.dispose()}catch(o){p.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),p.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 Vi(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,p.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),p.info("Video debugger initialized")}catch(e){throw p.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){p.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=>{p.error("Error processing frame:",t)})}),this._isRunning=!0,p.info("Video debugger started")}catch(e){throw p.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,p.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),p.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),p.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),p.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ka,D.DEFAULT_AUDIO_CHANNELS=Wa,D.DEFAULT_AUDIO_SAMPLE_RATE=Fi,D.DEFAULT_RECONNECT_ATTEMPTS=mt,D.DEFAULT_RECONNECT_DELAY=Ot,D.DEFAULT_WS_TIMEOUT=ja,D.Disposable=Y,D.EventBus=fs,D.Logger=p,D.SDKClient=La,D.SDKError=H,D.SessionState=gs,D.StandaloneVideoDebugger=Ep,D.createClient=Cp}));