@vanira/sdk 0.0.95 → 0.0.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vanira-sdk.umd.js
CHANGED
|
@@ -54,7 +54,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
|
54
54
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
55
55
|
`);n.RTCSessionDescription&&r instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function nd(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 id(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var j7=Object.freeze({__proto__:null,removeExtmapAllowMixed:Rp,shimAddIceCandidateNullOrEmpty:nd,shimConnectionState:Lp,shimMaxMessageSize:ed,shimParameterlessSetLocalDescription:id,shimRTCIceCandidate:$l,shimRTCIceCandidateRelayProtocol:Dp,shimSendThrowTypeError:td});function Y7(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=n.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=r3,r=G7(e),s={browserDetails:r,commonShim:j7,extractVersion:QA,disableLog:K7,disableWarnings:V7,sdp:W7};switch(r.browser){case"chrome":if(!sv||!Qp||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(r.version===null)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=sv,nd(e,r),id(e),a3(e,r),o3(e),Qp(e,r),A3(e,r),u3(e,r),c3(e),l3(e,r),h3(e,r),$l(e),Dp(e),Lp(e),ed(e,r),td(e,r),Rp(e,r);break;case"firefox":if(!av||!Pp||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=av,nd(e,r),id(e),p3(e,r),Pp(e,r),m3(e,r),f3(e),y3(e),g3(e),v3(e),w3(e),b3(e),C3(e),B3(e),x3(e),$l(e),Lp(e),ed(e,r),td(e,r);break;case"safari":if(!ov||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=ov,nd(e,r),id(e),M3(e),F3(e),E3(e),S3(e),k3(e),U3(e),T3(e),Q3(e),$l(e),Dp(e),ed(e,r),td(e,r),Rp(e,r);break;default:i("Unsupported browser!");break}return s}Y7({window:typeof window>"u"?void 0:window});var _p,D3;class Rn extends(D3=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)}}_p=Rn;Rn.resolve=n=>Reflect.get(D3,"resolve",_p).call(_p,n);const J7=/version\/(\d+(\.?_?\d+)+)/i;let Jh;function On(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Jh===void 0||e){const i=X7.find(r=>r.test.test(t));Jh=i==null?void 0:i.describe(t)}return Jh}const X7=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:rd(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Xh(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:rd(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Xh(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:rd(J7,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Xh(n)}}}];function rd(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 Xh(n){return n.includes("mac os")?rd(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Z7="2.20.0";const $7=Z7,e8=17,L3=0,Qd=1,t8=Qd;class us extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof(i==null?void 0:i.cause)<"u"&&(this.cause=i==null?void 0:i.cause)}}class Hi extends us{}var at;(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"})(at||(at={}));class fe extends Hi{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=at[t]}static notAllowed(e,t,i){return new fe(e,at.NotAllowed,t,i)}static timeout(e){return new fe(e,at.Timeout)}static leaveRequest(e,t){return new fe(e,at.LeaveRequest,void 0,t)}static internal(e,t){return new fe(e,at.InternalError,void 0,t)}static cancelled(e){return new fe(e,at.Cancelled)}static serverUnreachable(e,t){return new fe(e,at.ServerUnreachable,t)}static websocket(e,t,i){return new fe(e,at.WebSocket,t,i)}static serviceNotFound(e,t){return new fe(e,at.ServiceNotFound,void 0,t)}}class Sm extends us{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Xr extends us{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class n8 extends us{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Mt extends us{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class xa extends us{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class i8 extends us{constructor(e){super(14,e??"unable to publish data"),this.name="PublishDataError"}}class cv extends us{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class lv extends Hi{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:ua[t]}}var Dn;(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"})(Dn||(Dn={}));class Ei extends Hi{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Dn[t]}}class qa extends us{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Pd;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Pd||(Pd={}));(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})(Pd||(Pd={}));class Zt{}Zt.setTimeout=function(){return setTimeout(...arguments)};Zt.setInterval=function(){return setInterval(...arguments)};Zt.clearTimeout=function(){return clearTimeout(...arguments)};Zt.clearInterval=function(){return clearInterval(...arguments)};var G;(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",n.DataTrackPublished="dataTrackPublished",n.DataTrackUnpublished="dataTrackUnpublished",n.LocalDataTrackPublished="localDataTrackPublished",n.LocalDataTrackUnpublished="localDataTrackUnpublished"})(G||(G={}));var $;(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"})($||($={}));var q;(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",n.PublishDataTrackResponse="publishDataTrackResponse",n.UnPublishDataTrackResponse="unPublishDataTrackResponse",n.DataTrackSubscriberHandles="dataTrackSubscriberHandles",n.DataTrackPacketReceived="dataTrackPacketReceived",n.Joined="joined",n.TokenRefreshed="tokenRefreshed",n.ServerRegionsReported="serverRegionsReported"})(q||(q={}));var J;(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"})(J||(J={}));function r8(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 it{constructor(e,t,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const s8=["vp8","h264"],a8=["vp8","h264","vp9","av1","h265"];function R3(n){return!!s8.find(e=>e===n)}const o8=R3;var dv;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(dv||(dv={}));var Op;(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}})(Op||(Op={}));const wc={h90:new it(160,90,9e4,20),h180:new it(320,180,16e4,20),h216:new it(384,216,18e4,20),h360:new it(640,360,45e4,20),h540:new it(960,540,8e5,25),h720:new it(1280,720,17e5,30),h1080:new it(1920,1080,3e6,30),h1440:new it(2560,1440,5e6,30),h2160:new it(3840,2160,8e6,30)},Np={h120:new it(160,120,7e4,20),h180:new it(240,180,125e3,20),h240:new it(320,240,14e4,20),h360:new it(480,360,33e4,20),h480:new it(640,480,5e5,20),h540:new it(720,540,6e5,25),h720:new it(960,720,13e5,30),h1080:new it(1440,1080,23e5,30),h1440:new it(1920,1440,38e5,30)},km={h360fps3:new it(640,360,2e5,3,"medium"),h360fps15:new it(640,360,4e5,15,"medium"),h720fps5:new it(1280,720,8e5,5,"medium"),h720fps15:new it(1280,720,15e5,15,"medium"),h720fps30:new it(1280,720,2e6,30,"medium"),h1080fps15:new it(1920,1080,25e5,15,"medium"),h1080fps30:new it(1920,1080,5e6,30,"medium"),original:new it(0,0,7e6,30,"medium")};function _3(n,e,t){var i,r,s,a;const o=H3(n??{}),A=o.optionsWithoutProcessor,c=o.audioProcessor,l=o.videoProcessor,d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=A??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Hp(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(Hp(h.video,t),(r=(a=h.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function Hp(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Em(n){var e,t,i,r;const s={};if(n.video)if(typeof n.video=="object"){const a={},o=a,A=n.video;Object.keys(A).forEach(c=>{switch(c){case"resolution":Hp(o,A.resolution);break;default:o[c]=A[c]}}),s.video=a,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=n.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return n.audio?typeof n.audio=="object"?(s.audio=n.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function O3(n){return I(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=N3();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield In(t),r.getByteTimeDomainData(a);const A=a.some(c=>c!==128&&c!==0);return i.close(),!A}return!1}()})}function N3(){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=()=>I(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch{}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function A8(n){return n==="audioinput"?H.Source.Microphone:n==="videoinput"?H.Source.Camera:H.Source.Unknown}function Kp(n){return n===H.Source.Microphone?"audioinput":n===H.Source.Camera?"videoinput":void 0}function c8(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,Pa()?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 ZA(n){return n.split("/")[1].toLowerCase()}function l8(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new wm({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function De(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?De(n.track):{})}}function d8(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function u8(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],r={};for(const s of i)n[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function H3(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:r8(e)}}function h8(n){switch(n){case Yt.CAMERA:return H.Source.Camera;case Yt.MICROPHONE:return H.Source.Microphone;case Yt.SCREEN_SHARE:return H.Source.ScreenShare;case Yt.SCREEN_SHARE_AUDIO:return H.Source.ScreenShareAudio;default:return H.Source.Unknown}}function uv(n,e){return n.width*n.height<e.width*e.height}function p8(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const f8=5e3,fA=[];var mi;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(mi||(mi={}));class H extends oi.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 r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=H.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Te,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),f8):this.handleAppVisibilityChanged()},this.log=si((r=i.loggerName)!==null&&r!==void 0?r:mn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=H.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),De(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===H.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===H.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(fA.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&fA.splice(fA.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),oo(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?J.AudioPlaybackStarted:J.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?J.AudioPlaybackFailed:J.VideoPlaybackFailed,s):s.name==="AbortError"?Te.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Te.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(J.ElementAttached,e),e}detach(e){try{if(e){mo(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(J.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{mo(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(J.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=si(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),fA.forEach(i=>{i.parentElement||(t=!1)}),t&&fA.push(e)}}handleAppVisibilityChanged(){return I(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===H.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){ti()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ti()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function oo(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(r=>{t.removeTrack(r)}),t.addTrack(n)),(!Pa()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Pa()||Qa())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function mo(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(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function r(c){switch(c){case e.Audio:return Xi.AUDIO;case e.Video:return Xi.VIDEO;default:return Xi.DATA}}n.kindToProto=r;function s(c){switch(c){case Xi.AUDIO:return e.Audio;case Xi.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(c){switch(c){case t.Camera:return Yt.CAMERA;case t.Microphone:return Yt.MICROPHONE;case t.ScreenShare:return Yt.SCREEN_SHARE;case t.ScreenShareAudio:return Yt.SCREEN_SHARE_AUDIO;default:return Yt.UNKNOWN}}n.sourceToProto=a;function o(c){switch(c){case Yt.CAMERA:return t.Camera;case Yt.MICROPHONE:return t.Microphone;case Yt.SCREEN_SHARE:return t.ScreenShare;case Yt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function A(c){switch(c){case Tp.ACTIVE:return i.Active;case Tp.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=A})(H||(H={}));const m8="|",hv="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function g8(n){const e=n.split(m8);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function In(n){return new Rn(e=>Zt.setTimeout(e,n))}function Vp(){return"addTransceiver"in RTCPeerConnection.prototype}function Gp(){return"addTrack"in RTCPeerConnection.prototype}function v8(){if(!("getCapabilities"in RTCRtpSender)||Pa()||Qa())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 y8(){if(!("getCapabilities"in RTCRtpSender)||Qa())return!1;if(Pa()){const t=On();if(t!=null&&t.version&&Er(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&Er(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 er(n){return n==="av1"||n==="vp9"}function zp(n){return!document||bc()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function w8(){return typeof RTCPeerConnection>"u"?!1:Vp()||Gp()}function Qa(){var n;return((n=On())===null||n===void 0?void 0:n.name)==="Firefox"}function b8(){const n=On();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function qp(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!b8()}function Pa(){var n;return((n=On())===null||n===void 0?void 0:n.name)==="Safari"}function bc(){const n=On();return(n==null?void 0:n.name)==="Safari"||(n==null?void 0:n.os)==="iOS"}function C8(){const n=On();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&Er(n.osVersion,"17")>=0}function B8(n){return n||(n=On()),(n==null?void 0:n.name)==="Safari"&&Er(n.version,"18.3")>0||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&Er(n.osVersion,"18.3")>0}function K3(){var n,e;return ti()?(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 x8(){const n=On(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Er(n.osVersion,e)>=0?!0:n.name==="Safari"&&Er(n.version,e)>=0}function ti(){return typeof document<"u"}function ar(){return navigator.product=="ReactNative"}function Ro(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Zh(n){return Ro(n)?n.hostname.split(".")[0]:null}function V3(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function G3(){if(!ar())return;let n=V3();if(n)return n.platform}function pv(){if(ti())return window.devicePixelRatio;if(ar()){let n=V3();if(n)return n.devicePixelRatio}return 1}function Er(n,e){const t=n.split("."),i=e.split("."),r=Math.min(t.length,i.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(i[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function S8(n){for(const e of n)e.target.handleResize(e)}function k8(n){for(const e of n)e.target.handleVisibilityChanged(e)}let $h=null;const fv=()=>($h||($h=new ResizeObserver(S8)),$h);let e0=null;const mv=()=>(e0||(e0=new IntersectionObserver(k8,{root:null,rootMargin:"0px"})),e0);function E8(n){var e;const t=new _4({capabilities:n,sdk:O4.JS,protocol:e8,clientProtocol:t8,version:$7});return ar()&&(t.os=(e=G3())!==null&&e!==void 0?e:""),t}function gv(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=n,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(n/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream().getTracks(),A=pe(o,1),c=A[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}let mA;function t0(){if(!mA){const t=new AudioContext,i=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);const s=t.createMediaStreamDestination();i.connect(r),r.connect(s),i.start();var n=s.stream.getAudioTracks(),e=pe(n,1);if(mA=e[0],!mA)throw Error("Could not get empty media stream audio track");mA.enabled=!1}return mA.clone()}class fn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,r)=>I(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function T8(n){return a8.includes(n)}function Sa(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 I8(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Cc(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function M8(n,e){return n.segments.map(t=>{let i=t.id,r=t.text,s=t.language,a=t.startTime,o=t.endTime,A=t.final;var c;const l=(c=e.get(i))!==null&&c!==void 0?c:Date.now(),d=Date.now();return A?e.delete(i):e.set(i,l),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:A,language:s,firstReceivedTime:l,lastReceivedTime:d}})}function U8(n){const e=n.id,t=n.timestamp,i=n.message,r=n.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function vv(n){switch(n.reason){case at.LeaveRequest:return n.context;case at.Cancelled:return ir.CLIENT_INITIATED;case at.NotAllowed:return ir.USER_REJECTED;case at.ServerUnreachable:return ir.JOIN_FAILURE;default:return ir.UNKNOWN_REASON}}function sd(n){return n!==void 0?Number(n):void 0}function ca(n){return n!==void 0?BigInt(n):void 0}function go(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Sr(n){return!!n&&n.kind==H.Kind.Audio}function as(n){return!!n&&n.kind==H.Kind.Video}function hr(n){return go(n)&&as(n)}function Nr(n){return go(n)&&Sr(n)}function Wp(n){return!!n&&!n.isLocal}function F8(n){return!!n&&!n.isLocal}function n0(n){return Wp(n)&&as(n)}function Q8(n){return n.isLocal}function P8(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&t.push(i),t}function D8(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 z3(){return typeof CompressionStream<"u"}function L8(){return z3()&&!Qa()}function R8(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=_8(n,e);return t?i:Tm(i,"v1")}function _8(n,e){const t=new URL(I8(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),Tm(t,"rtc")}function O8(n){const e=new URL(Cc(n));return Tm(e,"validate")}function q3(n){return n.endsWith("/")?n:"".concat(n,"/")}function Tm(n,e){return n.pathname="".concat(q3(n.pathname)).concat(e),n}function yv(n){if(typeof n=="string")return Z1.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return Z1.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function N8(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 H8=10,gA="lk_e2ee",K8="LKFrameEncryptionKey",V8={sharedKey:!1,ratchetSalt:K8,ratchetWindowSize:8,failureTolerance:H8,keyringSize:16,keySize:128};var Qs;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Qs||(Qs={}));var wv;(function(n){n.KeyRatcheted="keyRatcheted"})(wv||(wv={}));var Es;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(Es||(Es={}));var bv;(function(n){n.Error="cryptorError"})(bv||(bv={}));function G8(){return Im()||z8()}function z8(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function Im(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function q8(n){var e,t,i,r,s;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"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new U4({value:n.value})}class TK extends oi.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,r)=>{Te.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},V8),e),this.on(Qs.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const r={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),r),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit(Qs.SetKey,r,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Qs.RatchetRequest,e,t)}}var Cv;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Cv||(Cv={}));function Bc(){return qp()}function xc(n){return!!(n!=null&&n.worker)&&(Im()||Bc())}function Dd(n){return!!(n!=null&&n.timestamp||n!=null&&n.frameId)}function W8(n){const e=[];return n!=null&&n.timestamp&&e.push(Do.PTF_USER_TIMESTAMP),n!=null&&n.frameId&&e.push(Do.PTF_FRAME_ID),e}function j8(n){if(!n||n.length===0)return;const e={};return n.includes(Do.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),n.includes(Do.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function Mm(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i,r;let s;const a=(i=t.isImmediate)!==null&&i!==void 0?i:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,A=t.maxWait;let c=Date.now(),l=[];function d(){if(A!==void 0){const h=Date.now()-c;if(h+e>=A)return A-h}return e}const u=function(){for(var h=arguments.length,p=new Array(h),m=0;m<h;m++)p[m]=arguments[m];const v=this;return new Promise((w,b)=>{const k=function(){if(s=void 0,c=Date.now(),!a){const B=n.apply(v,p);o&&o(B),l.forEach(E=>{let T=E.resolve;return T(B)}),l=[]}},y=a&&s===void 0;if(s!==void 0&&Zt.clearTimeout(s),s=Zt.setTimeout(k,d()),y){const B=n.apply(v,p);return o&&o(B),w(B)}l.push({resolve:w,reject:b})})};return u.cancel=function(h){s!==void 0&&Zt.clearTimeout(s),l.forEach(p=>{let m=p.reject;return m(h)}),l=[]},u}const Um=2e3;function Qu(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)}class W3 extends H{constructor(e,t,i,r,s){super(e,i,s),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?J.Muted:J.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(J.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return I(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(),Um)),d8()&&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 r=i.timestamp,s=i.rtpTimestamp;s&&this.rtpTimestamp!==s&&(this.emit(J.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}const i0=100;class Fm extends W3{constructor(e,t,i,r,s){super(e,t,H.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>I(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=Qu(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Mm(()=>{this.updateDimensions()},i0),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return(i=this.frameMetadataExtractor)===null||i===void 0?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===H.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?mo(this._mediaStreamTrack,t):oo(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 Y8(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){if(e)return this.stopObservingElement(e),super.detach(e);const 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 I(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return I(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const r=this.elementInfos.reduce((A,c)=>Math.max(A,c.visibilityChangedAt||0),0),s=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(A=>A.pictureInPicture),o=this.elementInfos.some(A=>A.visible)&&!s||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-r<i0){Zt.setTimeout(()=>{this.updateVisibility()},i0);return}this.lastVisible=o,this.emit(J.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,A=a.height()*s;o+A>i+r&&(i=o,r=A)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(J.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?pv():t||(pv()>2?2:1)}}class Y8{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const s=i.target,a=i.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=vA(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=vA(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var i;this.isPiP=vA(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??jp(e),this.isPiP=ti()&&vA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=jp(this.element),this.isPiP=vA(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,mv().observe(this.element),fv().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=mv())===null||e===void 0||e.unobserve(this.element),(t=fv())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function vA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?jp(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function jp(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,o=n,A=o.hidden,c=getComputedStyle(n),l=c.display;for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!A&&l!=="none"}class J8 extends oi.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var r,s;const a=i.data,o=a.kind,A=a.data;switch(o){case"error":if(Te.error(A.error.message),A.uuid){const d=this.decryptDataRequests.get(A.uuid);if(d!=null&&d.reject){d.reject(A.error);break}const u=this.encryptDataRequests.get(A.uuid);if(u!=null&&u.reject){u.reject(A.error);break}}this.emit(Es.EncryptionError,A.error,A.participantIdentity);break;case"initAck":A.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d,!1)});break;case"enable":if(A.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d,!1)}),this.encryptionEnabled!==A.enabled&&A.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(Es.ParticipantEncryptionStatusChanged,A.enabled,this.room.localParticipant),this.encryptionEnabled=A.enabled;else if(A.participantIdentity){const d=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(A.participantIdentity);if(!d)throw TypeError("couldn't set encryption status, participant not found".concat(A.participantIdentity));this.emit(Es.ParticipantEncryptionStatusChanged,A.enabled,d)}break;case"ratchetKey":this.keyProvider.emit(Qs.KeyRatcheted,A.ratchetResult,A.participantIdentity,A.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(A.uuid);c!=null&&c.resolve&&c.resolve(A);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(A.uuid);l!=null&&l.resolve&&l.resolve(A);break;case"packetTrailerMetadata":this.handleFrameMetadata(A.trackId,A.rtpTimestamp,A.ssrc,A.metadata);break}},this.onWorkerError=i=>{Te.error("e2ee worker encountered an error:",{error:i.error}),this.emit(Es.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(!G8())throw new Sm("tried to setup end-to-end encryption on an unsupported browser");if(Te.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:P7.getLevel()}};this.worker&&(Te.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Te.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?Te.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,i,r){if(this.room){for(const s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof Fm&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,i,r);return}}}setupEngine(e){e.on(q.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(G.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==At.NONE,r.identity)),e.on(G.ConnectionStateChanged,i=>{i===Ye.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==At.NONE,r.identity)})})}).on(G.TrackUnsubscribed,(i,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(G.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(G.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const i=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,i===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on($.LocalSenderCreated,(i,r)=>I(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on($.LocalTrackPublished,i=>{if(!as(i.track)||!bc())return;const r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:ZA(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(Qs.SetKey,(i,r)=>this.postKey(i,r??!0)).on(Qs.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return I(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}},r=new fn;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,t,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:r}},o=new fn;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,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,t){let i=e.key,r=e.participantIdentity,s=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:i,keyIndex:s,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}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)return;if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const r=e.kind==="video"&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?ZA(i.mimeType):void 0,r)}setupE2EESender(e,t){var i,r,s;if(!go(e)||!t){t||Te.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,as(e)?(r=(i=e.publishOptions)===null||i===void 0?void 0:i.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,i,r,s){return I(this,void 0,void 0,function*(){if(this.worker){if(qp()){const a={kind:"decode",participantIdentity:i,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(gA in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:i,hasPacketTrailer:s}};this.worker.postMessage(c);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,a=c.writable,e.readableStream=c.readable,o=c.readable}const A={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:i,isReuse:gA in e,hasPacketTrailer:s}};this.worker.postMessage(A,[o,a])}e[gA]=!0}})}handleSender(e,t,i,r){var s;if(!(gA 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(qp()){Te.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:Dd(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{Te.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Dd(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[gA]=!0}}}const X8=300;class Z8{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=X8;){const r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class $8{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{const i=t.data;if(i.kind==="metadata"){const r=this.extractors.get(i.data.trackId);r&&r.storeMetadata(i.data.rtpTimestamp,i.data.ssrc,i.data.metadata)}},this.onWorkerError=t=>{Te.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e==null?void 0:e.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(G.TrackSubscribed,(t,i,r)=>{t.kind==="video"&&this.setupReceiver(t,i.trackInfo)}).on(G.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(G.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,r,s;const a=e.receiver;if(!a)return;if(!(!!(t!=null&&t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0)){!((i=this.room)===null||i===void 0)&&i.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!xc(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){Te.warn("frame metadata transform not supported; skipping extraction");return}const A=new Z8,c=e.mediaStreamID;this.extractors.set(c,A),e.frameMetadataExtractor=A,!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)&&this.setupWorkerReceiver(a,c,!0)}setupPassthroughReceiver(e,t){if(Bc()){"transform"in e&&(e.transform=null);return}if(this.worker&&xc({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;const r=this.worker;if(!r)return;if(Bc()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}const s=this.workerPipelines.get(e);if(s){const A={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:i}};r.postMessage(A),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){Te.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(A){Te.warn("failed to create encoded streams",{error:A});return}const o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:i}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof Fm&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}}const eE=500,tE=15e3;class vo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new vo),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),r=Zh(i);if(!r)return;let s=(t=this.failedConnectionAttempts.get(r))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(r,s+1),this.backOffPromises.set(r,In(Math.min(eE*Math.pow(2,s),tE)))}getBackOffPromise(e){const t=new URL(e),i=t&&Zh(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Zh(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}vo._instance=null;const r0="default";class pn{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new pn),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=pn.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){Te.debug("awaiting getUserMedia promise");try{t?yield pn.userMediaPromiseMap.get(t):yield Promise.all(pn.userMediaPromiseMap.values())}catch{Te.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Pa()&&i.hasDeviceInUse(t))&&(a.filter(A=>A.kind===t).length===0||a.some(A=>{const c=A.label==="",l=t?A.kind===t:!0;return c&&l}))){const A={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(A);a=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,i){return I(this,void 0,void 0,function*(){if(t!==r0)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===r0);if(!s){Te.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==r0&&o.groupId===(i??s.groupId));if(!a){Te.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?pn.userMediaPromiseMap.has(e):pn.userMediaPromiseMap.size>0}}pn.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];pn.userMediaPromiseMap=new Map;const Qm=65535,j3=4294967295;class rr{static u16(e){return new rr(e,Qm)}static u32(e){return new rr(e,j3)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new rr(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){const e=this.value;return this.increment(),new rr(e,this.maxSize)}isBefore(e){const t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}}class yo{static fromRtpTicks(e){return new yo(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*j3);return yo.fromRtpTicks(e)}constructor(e,t){this.timestamp=rr.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new yo(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class ha{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new ha(t,new Date,e)}static startingAtTime(e,t,i){return new ha(i,e,t)}static rtpStartingNow(e){return ha.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return ha.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=ha.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(i),r.isBefore(this.previous)&&(r=this.previous),this.previous=r.clone(),r.clone()}static durationInMsToTicks(e,t){let r=(e*1e6*t+5e8)/1e9;return Math.round(r)}}function Pm(n){if(n instanceof DataView)return n;if(n instanceof ArrayBuffer)return new DataView(n);if(n instanceof Uint8Array)return new DataView(n.buffer,n.byteOffset,n.byteLength);throw new Error("Error coercing ".concat(n," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var ka;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(ka||(ka={}));class _o extends Hi{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=ka[t]}isReason(e){return this.reason===e}static tooLarge(){return new _o("Value too large to be a valid track handle",ka.TooLarge)}static reserved(e){return new _o("0x".concat(e.toString(16)," is a reserved value."),ka.Reserved)}}const nE={fromNumber(n){if(n===0)throw _o.reserved(n);if(n>Qm)throw _o.tooLarge();return n}};class iE{constructor(){this.value=0}get(){return this.value+=1,this.value>Qm?null:this.value}reset(){this.value=0}}const Ld={from(n){return{sid:n.sid,pubHandle:n.pubHandle,name:n.name,usesE2ee:n.encryption!==At.NONE}},toProtobuf(n){return new ku({sid:n.sid,pubHandle:n.pubHandle,name:n.name,encryption:n.usesE2ee?At.GCM:At.NONE})}};var $A;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})($A||($A={}));class rE{constructor(){this.pendingTasks=new Map,this.taskMutex=new bn,this.nextTaskIndex=0}run(e){return I(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:$A.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=$A.RUNNING,yield e()}finally{t.status=$A.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return I(this,void 0,void 0,function*(){return this.run(()=>I(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class sE{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;const a=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},A=o.closeCode,c=o.reason;return s.close(A,c)};this.opened=new Rn((o,A)=>{const c=()=>{A(fe.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{o({readable:new ReadableStream({start(l){s.onmessage=d=>{let u=d.data;return l.enqueue(u)},s.onerror=d=>l.error(d)},cancel:a}),writable:new WritableStream({write(l){s.send(l)},abort(){s.close()},close:a}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",c)},s.addEventListener("error",c)}),this.closed=new Rn((o,A)=>{const c=()=>I(this,void 0,void 0,function*(){const l=new Rn(u=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",h=>{u(h)},{once:!0})}),d=yield Rn.race([In(250),l]);d?o(d):A(fe.websocket("Encountered unspecified websocket error without a timely close event"))});s.onclose=l=>{let d=l.code,u=l.reason;o({closeCode:d,reason:u}),s.removeEventListener("error",c)},s.addEventListener("error",c)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=a}}const aE=["syncState","trickle","offer","answer","simulate","leave"];function oE(n){const e=aE.indexOf(n.case)>=0;return Te.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var st;(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"})(st||(st={}));const AE=250;class Dm{get currentState(){return this.state}get isDisconnected(){return this.state===st.DISCONNECTING||this.state===st.DISCONNECTED}get isEstablishingConnection(){return this.state===st.CONNECTING||this.state===st.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=st.DISCONNECTED,this.log=Te,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.loggerContextCb=t.loggerContextCb,this.log=si((i=t.loggerName)!==null&&i!==void 0?i:mn.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new rE,this.queuedRequests=[],this.closingLock=new bn,this.connectionLock=new bn,this.state=st.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,r){return I(this,arguments,void 0,function(s,a,o,A){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,d=arguments.length>5?arguments[5]:void 0;return function*(){return c.state=st.CONNECTING,c.options=o,yield c.connect(s,a,o,A,l,d)}()})}reconnect(e,t,i,r){return I(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=st.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,i,r){return I(this,arguments,void 0,function(s,a,o,A){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,d=arguments.length>5?arguments[5]:void 0;return function*(){const u=yield c.connectionLock.lock();c.connectOptions=o,c.useV0SignalPath=l;const h=E8(o.clientInfoCapabilities),p=l?cE(a,h,o):yield lE(a,h,o,d),m=R8(s,p,l).toString(),v=O8(m).toString();return new Promise((w,b)=>I(c,void 0,void 0,function*(){var k,y;try{let B=!1;const E=O=>I(this,void 0,void 0,function*(){if(B)return;B=!0;const N=O instanceof Event?O.currentTarget:O,j=N8(N,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(j)).catch(V=>{this.log.error(V),this.close()}):this.close(),T(),b(fe.cancelled(j))});A==null||A.addEventListener("abort",E);const T=()=>{clearTimeout(F),A==null||A.removeEventListener("abort",E)},F=setTimeout(()=>{E(fe.timeout("room connection has timed out (signal)"))},o.websocketTimeout),L=(O,N)=>{this.handleSignalConnected(O,F,N)},D=new URL(m);if(D.searchParams.has("access_token")&&D.searchParams.set("access_token","<redacted>"),this.ws){const O=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-O,"ms"))}this.log.info("signal connecting to ".concat(D),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new sE(m);try{this.ws.closed.then(ae=>{var Ie;this.isEstablishingConnection&&b(fe.internal("Websocket got closed during a (re)connection attempt: ".concat(ae.reason))),ae.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:ae.reason,code:ae.closeCode,wasClean:ae.closeCode===1e3,state:this.state}),this.state===st.CONNECTED&&this.handleOnClose((Ie=ae.reason)!==null&&Ie!==void 0?Ie:"Unexpected WS error"))}).catch(ae=>{this.isEstablishingConnection&&b(fe.internal("Websocket error during a (re)connection attempt: ".concat(ae)))});const O=yield this.ws.opened.catch(ae=>I(this,void 0,void 0,function*(){if(this.state!==st.CONNECTED){this.state=st.DISCONNECTED,clearTimeout(F);const Ie=yield this.handleConnectionError(ae,v);b(Ie);return}this.handleWSError(ae),b(ae)}));if(clearTimeout(F),!O)return;const N=O.readable.getReader();this.streamWriter=O.writable.getWriter();const j=yield N.read();if(N.releaseLock(),!j.value)throw fe.internal("no message received as first message");const V=yv(j.value),te=this.validateFirstMessage(V,(k=o.reconnect)!==null&&k!==void 0?k:!1);if(!te.isValid){b(te.error);return}((y=V.message)===null||y===void 0?void 0:y.case)==="join"&&(this.pingTimeoutDuration=V.message.value.pingTimeout,this.pingIntervalDuration=V.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(V.message.value));const xe=te.shouldProcessFirstMessage?V:void 0;L(O,xe),w(te.response)}catch(O){b(O)}finally{T()}}finally{u()}}))}()})}startReadingLoop(e,t){return I(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield In(this.signalLatency));const i=yield e.read(),r=i.done,s=i.value;if(r)break;const a=yv(s);this.handleSignalResponse(a)}})}close(){return I(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([st.DISCONNECTING||st.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=st.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,In(AE)])}}catch(s){e.log.debug("websocket error while closing",{error:s})}finally{t&&(e.state=st.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:pa(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:pa(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Tu({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Iu({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new Cm({requestId:o,metadata:i,name:r,attributes:a})}),o}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Y4({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Z4({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:bt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new t3({timestamp:bt.parse(Date.now()),rtt:bt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new bm({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Uu({reason:ir.CLIENT_INITIATED,action:po.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new gm({pubHandle:e,name:t,encryption:i?At.GCM:At.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new ym({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new z4({updates:[new q4({trackSid:e,subscribe:t})]})})}sendRequest(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!oE(t)&&i.state===st.RECONNECTING){i.queuedRequests.push(()=>I(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield In(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==null?void 0:t.case));return}const a=new n7({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary().buffer)}catch(o){i.log.error("error sending signal message",{error:o})}}()})}handleSignalResponse(e){var t,i;const r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){const a=Bv(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const a=Bv(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(r.value):r.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(r.value):r.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(r.value):r.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(r.value):this.log.debug("unsupported message",{msgCase:r.case}));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return I(this,void 0,void 0,function*(){if(this.state===st.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=Zt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Zt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=Zt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Zt.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=st.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,r,s,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===st.RECONNECTING&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((s=e.message)===null||s===void 0?void 0:s.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:fe.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:fe.internal("Unexpected first message")}:{isValid:!1,error:fe.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return I(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:const r=yield i.text();return r.includes("requested room does not exist")?fe.notAllowed(r,i.status):fe.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return fe.notAllowed(s,i.status);default:break}return e instanceof fe?e:fe.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof fe?i:fe.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function Bv(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 pa(n,e){return new Ns({sdp:n.sdp,type:n.type,id:e})}function cE(n,e,t){var i;const r=new URLSearchParams;return r.set("access_token",n),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",ar()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),r.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}function lE(n,e,t,i){return I(this,void 0,void 0,function*(){const r=new URLSearchParams;r.set("access_token",n);const s=new E7({clientInfo:e,connectionSettings:new n3({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:i});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const a=s.toBinary();let o,A;if(z3()){const u=new CompressionStream("gzip"),h=u.writable.getWriter();h.write(new Uint8Array(a)),h.close();const p=[],m=u.readable.getReader();for(;;){const k=yield m.read(),y=k.done,B=k.value;if(y)break;p.push(B)}const v=p.reduce((k,y)=>k+y.length,0),w=new Uint8Array(v);let b=0;for(const k of p)w.set(k,b),b+=k.length;o=w,A=Mp.GZIP}else o=a,A=Mp.NONE;const l=new T7({joinRequest:o,compression:A}).toBinary(),d=u=>{const h=Array.from(u,p=>String.fromCodePoint(p)).join("");return btoa(h)};return r.set("join_request",d(l).replace(/\+/g,"-").replace(/\//g,"_")),r})}class xv{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 dE{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 r=i+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),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 i of this._map.entries()){var t=pe(i,2);const r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const i of this._map.entries()){var t=pe(i,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const s of i.entries()){var r=pe(s,2);const a=r[0],o=r[1];t.push(e(o,a,i))}return t}asValueMap(){const e=new Map;for(const i of this._map.entries()){var t=pe(i,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}}var Gi={},s0={},a0={exports:{}},Sv;function Lm(){if(Sv)return a0.exports;Sv=1;var n=a0.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")})}),a0.exports}var kv;function uE(){return kv||(kv=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,A,c,l){if(l&&!c)A[l]=e(o[1]);else for(var d=0;d<c.length;d+=1)o[d+1]!=null&&(A[c[d]]=e(o[d+1]))},i=function(o,A,c){var l=o.name&&o.names;o.push&&!A[o.push]?A[o.push]=[]:l&&!A[o.name]&&(A[o.name]={});var d=o.push?{}:l?A[o.name]:A;t(c.match(o.reg),d,o.names,o.name),o.push&&A[o.push].push(d)},r=Lm(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var A={},c=[],l=A;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var u=d[0],h=d.slice(2);u==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var p=0;p<(r[u]||[]).length;p+=1){var m=r[u][p];if(m.reg.test(h))return i(m,l,h)}}),A.media=c,A};var a=function(o,A){var c=A.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&A.length>1&&(o[c[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 A=[],c=o.split(" ").map(e),l=0;l<c.length;l+=3)A.push({component:c[l],ip:c[l+1],port:c[l+2]});return A},n.parseImageAttributes=function(o){return o.split(" ").map(function(A){return A.substring(1,A.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(A){return A.split(",").map(function(c){var l,d=!1;return c[0]!=="~"?l=e(c):(l=e(c.substring(1,c.length)),d=!0),{scid:l,paused:d}})})}}(s0)),s0}var o0,Ev;function hE(){if(Ev)return o0;Ev=1;var n=Lm(),e=/%[sdv%]/g,t=function(a){var o=1,A=arguments,c=A.length;return a.replace(e,function(l){if(o>=c)return l;var d=A[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(a,o,A){var c=o.format instanceof Function?o.format(o.push?A:A[o.name]):o.format,l=[a+"="+c];if(o.names)for(var d=0;d<o.names.length;d+=1){var u=o.names[d];o.name?l.push(A[o.name][u]):l.push(A[o.names[d]])}else l.push(A[o.name]);return t.apply(null,l)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return o0=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var A=o.outerOrder||r,c=o.innerOrder||s,l=[];return A.forEach(function(d){n[d].forEach(function(u){u.name in a&&a[u.name]!=null?l.push(i(d,u,a)):u.push in a&&a[u.push]!=null&&a[u.push].forEach(function(h){l.push(i(d,u,h))})})}),a.media.forEach(function(d){l.push(i("m",n.m[0],d)),c.forEach(function(u){n[u].forEach(function(h){h.name in d&&d[h.name]!=null?l.push(i(u,h,d)):h.push in d&&d[h.push]!=null&&d[h.push].forEach(function(p){l.push(i(u,h,p))})})})}),l.join(`\r
|
|
56
56
|
`)+`\r
|
|
57
|
-
`},o0}var Tv;function pE(){if(Tv)return Gi;Tv=1;var n=uE(),e=hE(),t=Lm();return Gi.grammar=t,Gi.write=e,Gi.parse=n.parse,Gi.parseParams=n.parseParams,Gi.parseFmtpConfig=n.parseFmtpConfig,Gi.parsePayloads=n.parsePayloads,Gi.parseRemoteCandidates=n.parseRemoteCandidates,Gi.parseImageAttributes=n.parseImageAttributes,Gi.parseSimulcastStreamList=n.parseSimulcastStreamList,Gi}var Si=pE();const fE=.7,mE=20,Ts={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Iv extends oi.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=Te,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Mm(r=>I(this,void 0,void 0,function*(){this.emit(Ts.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),mE),this.close=()=>{this._pc&&(this.pendingInitialOffer=void 0,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=si((i=t.loggerName)!==null&&i!==void 0?i:mn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new bn}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 I(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 I(this,void 0,void 0,function*(){var i,r;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 a=gE(e),o=a.stereoMids,A=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=A}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const o=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const A=Si.parse((i=o.sdp)!==null&&i!==void 0?i:"");A.media.forEach(c=>{rl(c)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(o,Si.write(A))}const a=Si.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(o=>{const A=Rm(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||A!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0)return!0;let d=!1;for(const u of o.fmtp)if(u.payload===l){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),d=!0;break}return d||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Si.write(a)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(Ts.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Ts.NegotiationComplete),e.sdp&&Si.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Ts.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return I(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);return}const i=this.latestOfferId+1;this.latestOfferId=i;const r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};const s=Si.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{rl(a)}),r.sdp=Si.write(s),{offer:r,offerId:i}}finally{t()}})}createAndSendOffer(e){return I(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const a=Si.parse((t=s.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{rl(o),o.type==="audio"?Mv(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(A=>{if(!o.msid||!A.cid||!o.msid.includes(A.cid))return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===A.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(er(A.codec)&&!Pa()&&this.ensureVideoDDExtensionForSVC(o,a),!er(A.codec)))return!0;const l=Math.round(A.maxbr*fE);for(const d of o.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,Si.write(a)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return I(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Si.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{rl(r),r.type==="audio"&&Mv(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Si.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 Mt("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 Mt("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()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return I(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return I(this,void 0,void 0,function*(){var r,s;const a=e.sdp;if(t){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(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:o,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{i?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(o){let A="unknown error";o instanceof Error?A=o.message:typeof o=="string"&&(A=o);const c={error:A,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!i&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:c})),new xa(A)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===hv))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var A;(A=o.ext)===null||A===void 0||A.forEach(c=>{c.value>a&&(a=c.value)})}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:hv})}}}function Mv(n,e,t){const i=Rm(n.mid);let r=0;n.rtp.some(s=>s.codec==="opus"?(r=s.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(s=>s.payload===r?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function gE(n){var e;const t=[],i=[],r=Si.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;const A=Rm(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(A),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(A),!0):!1))}),{stereoMids:t,nackMids:i}}function rl(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 Rm(n){return typeof n=="number"?n.toFixed(0):n}const Yp="vp8",vE={audioPreset:Op.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:km.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Yp,backupCodec:!0,preConnectBuffer:!1},Y3={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},J3={deviceId:{ideal:"default"},resolution:wc.h720.resolution},yE={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new L7,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},_m={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ut;(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"})(Ut||(Ut={}));class Uv{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 r;this.peerConnectionTimeout=_m.peerConnectionTimeout,this.log=Te,this.updateState=()=>{var s,a;const o=this.state,A=this.requiredTransports.map(c=>c.getConnectionState());A.every(c=>c==="connected")?this.state=Ut.CONNECTED:A.some(c=>c==="failed")?this.state=Ut.FAILED:A.some(c=>c==="connecting")?this.state=Ut.CONNECTING:A.every(c=>c==="closed")?this.state=Ut.CLOSED:A.some(c=>c==="closed")?this.state=Ut.CLOSING:A.every(c=>c==="new")&&(this.state=Ut.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Ut[o]," to ").concat(Ut[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=si((r=t.loggerName)!==null&&r!==void 0?r:mn.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Iv(i,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Iv(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Zi.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Zi.PUBLISHER)},this.publisher.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=(s,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,s,a)},this.state=Ut.NEW,this.connectionLock=new bn,this.remoteOfferLock=new bn}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 I(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(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return I(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return I(this,void 0,void 0,function*(){var i;t===Zi.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return I(this,void 0,void 0,function*(){var i,r,s;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(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.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 I(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return I(this,void 0,void 0,function*(){return new Rn((t,i)=>{const r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1;const a=()=>{s||(s=!0,clearTimeout(c),this.publisher.off(Ts.OfferAnswered,o),e.signal.removeEventListener("abort",A))},o=l=>{l>r&&(a(),t())},A=()=>{a(),i(new xa("negotiation aborted"))},c=setTimeout(()=>{a(),i(new xa("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",A),this.publisher.on(Ts.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?i(l):i(new Error(String(l)))})})})}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(r=>r.receiver===e);return i==null?void 0:i.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Zi.PUBLISHER?this.publisher.getConnectedAddress():e===Zi.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 I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((A,c)=>I(s,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),Zt.clearTimeout(d),c(fe.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&l(),r==null||r.signal.addEventListener("abort",l);const d=Zt.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",l),c(fe.internal("could not establish pc connection"))},a);for(;this.state!==Ut.CONNECTED;)if(yield In(50),r!=null&&r.signal.aborted){c(fe.cancelled("room connection has been cancelled"));return}Zt.clearTimeout(d),r==null||r.signal.removeEventListener("abort",l),A()}))}()})}}const Om=typeof MediaRecorder<"u";class wE{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const bE=Om?MediaRecorder:wE;class CE extends bE{constructor(e,t){if(!Om)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,r;const s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r==null||r.close(),r=void 0},o=A=>{r==null||r.error(A),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:A=>{r=A,i=c=>I(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){const d=yield c.data.arrayBuffer();l=new Uint8Array(d)}else if(c.data.byteArray)l=c.data.byteArray;else throw new Error("no data available!");s()||A.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function BE(){return Om}const xE=1e3,SE=1e4;class X3 extends H{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),this.manuallyStopped=!1,this.pendingDeviceChange=!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=Mm(()=>I(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>I(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(J.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new bn,this.pauseUpstreamLock=new bn,this.trackChangeLock=new bn,this.trackChangeLock.lock().then(a=>I(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!==H.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;if(t&&i)return{width:t,height:i}}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,i){return I(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{mo(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let 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&&(oo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),s=this.processor.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{oo(s??e,a)}))})}waitForDimensions(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xE;return function*(){var i;if(e.kind===H.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=On())===null||i===void 0?void 0:i.os)==="iOS"&&(yield In(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield In(50)}throw new Xr("unable to get track dimensions after timeout")}()})}setDeviceId(e){return I(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Sa(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Sa(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return I(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===H.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),r=i.deviceId,s=i.groupId,a=e.kind===H.Kind.Audio?"audioinput":"videoinput";return t?pn.getInstance().normalizeDeviceId(a,r,s):r}()})}mute(){return I(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return I(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return I(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Xr("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return I(this,void 0,void 0,function*(){})}restart(e,t){return I(this,void 0,void 0,function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const r=e,s=r.deviceId,a=r.facingMode,o=R7(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===H.Kind.Video?A.video=s||a?{deviceId:s,facingMode:a}:!0:A.audio=s?Object.assign({deviceId:s},o):!0,this.attachedElements.forEach(d=>{mo(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(A)).getTracks()[0];return this.kind===H.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(J.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}})}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?J.Muted:J.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 I(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),K3()&&(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 I(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(J.UpstreamPaused,this);const i=On();if((i==null?void 0:i.name)==="Safari"&&Er(i.version,"12.0")<0)throw new Sm("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 I(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(J.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 I(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 I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),A={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext,localTrack:i};if(yield t.init(A),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(oo(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{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:c}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(mo(i._mediaStreamTrack,c),oo(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(J.TrackProcessorUpdate,i.processor)}finally{a()}yield i.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return I(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()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(J.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!BE()){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 CE(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},SE)}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 Rd extends X3{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,H.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>I(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=Qu(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(J.AudioTrackFeatureUpdate,this,hn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(J.AudioTrackFeatureUpdate,this,hn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return I(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===H.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return I(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===H.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return I(this,void 0,void 0,function*(){let t;if(e){const i=Em({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return I(this,void 0,void 0,function*(){const r=yield i.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){ti()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Um)))}setProcessor(e){return I(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!ar()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(J.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return I(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return I(this,void 0,void 0,function*(){const e=yield O3(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(J.AudioSilenceDetected)),e})}}function kE(n,e,t){switch(n.kind){case"audio":return new Rd(n,e,!1,void 0,t);case"video":return new Od(n,e,!1,t);default:throw new Xr("unsupported track type: ".concat(n.kind))}}const EE=Object.values(wc),TE=Object.values(Np),IE=Object.values(km),ME=[wc.h180,wc.h360],UE=[Np.h180,Np.h360],FE=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new it(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),Jp=["q","h","f"];function _d(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,A=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!a&&!o&&!A||!e||!t)return[{}];a||(a=QE(n,e,t,c),Te.debug("using video encoding",a));const l=a.maxFramerate,d=new it(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(A&&er(c)){const v=new $3(A),w=[];if(v.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(A));const b=On();if(bc()||ar()||(b==null?void 0:b.name)==="Chrome"&&Er(b==null?void 0:b.version,"113")<0){const k=v.suffix=="h"?2:3,y=B8(b);for(let B=0;B<v.spatial;B+=1)w.push({rid:Jp[2-B],maxBitrate:a.maxBitrate/Math.pow(k,B),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,B):void 0});w[0].scalabilityMode=A}else w.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:A});return d.encoding.priority&&(w[0].priority=d.encoding.priority,w[0].networkPriority=d.encoding.priority),Te.debug("using svc encoding",{encodings:w}),w}if(!o)return[a];let u;n?u=(r=Qv(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Fv(n,d):u=(s=Qv(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Fv(n,d);let h;if(u.length>0){const v=u[0];if(u.length>1){var p=u,m=pe(p,2);h=m[1]}const w=Math.max(e,t);if(w>=960&&h)return A0(e,t,[v,h,d],l);if(w>=480)return A0(e,t,[v,d],l)}return A0(e,t,[d])}function Z3(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&Te.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(),A=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===H.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),_d(n.source===H.Source.ScreenShare,A,c,t)}function QE(n,e,t,i){const r=PE(n,e,t);let s=r[0].encoding;const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const A=r[o];if(s=A.encoding,A.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function PE(n,e,t){if(n)return IE;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?EE:TE}function Fv(n,e){if(n)return FE(e);const t=e.width,i=e.height,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?ME:UE}function A0(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=Jp.length)return;const o=Math.min(n,e),c={rid:Jp[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(c.maxFramerate=l);const d=On(),u=(d==null?void 0:d.name)==="Firefox"&&d.os!=="iOS"||a===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),ar()&&G3()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var A;o.maxFramerate!=s&&(a&&(a=!1,Te.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Te.info('Setting framerate of encoding "'.concat((A=o.rid)!==null&&A!==void 0?A:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Qv(n){if(n)return n.slice().sort((e,t)=>{const i=e.encoding,r=t.encoding;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class $3{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 DE(n){return n.source===H.Source.ScreenShare||n.constraints.height&&Sa(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const LE=5e3;class Od extends X3{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,H.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>I(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(A){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:A}));return}const a=new Map(s.map(A=>[A.rid,A])),o=s.some(A=>A.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(J.CpuConstrained)),this.prevStats){let A=0;a.forEach((c,l)=>{var d;const u=(d=this.prevStats)===null||d===void 0?void 0:d.get(l);A+=Qu(c,u)}),this._currentBitrate=A}this.prevStats=a}),this.senderLock=new bn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ti())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()},Um))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return I(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,A=$i(this.simulcastCodecs.values()),c;c=yield A.next(),t=c.done,!t;o=!0)s=c.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(r=A.return)&&(yield r.call(A))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return I(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,A=$i(this.simulcastCodecs.values()),c;c=yield A.next(),t=c.done,!t;o=!0){s=c.value,o=!1;const l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(r=A.return)&&(yield r.call(A))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return I(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===H.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 I(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===H.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),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 I(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=mi.LOW;i<=mi.HIGH;i+=1)t.push(new Bm({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(er(this.codec),t)}restartTrack(e){return I(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const d=Em({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var A=!0,c=$i(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;A=!0){s=l.value,A=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!A&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return I(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return I(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;const s=this.source===H.Source.ScreenShare,a=_d(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(const o of this.simulcastCodecs){var i=pe(o,2);const A=i[0],c=i[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!R3(A))continue;const l=Object.assign({},this.publishOptions),d=Z3(this,A,l);d&&(yield this.applyEncodingsToSender(c.sender,d),c.encodings=d)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return I(this,void 0,void 0,function*(){const i=e.getParameters();!i.encodings||i.encodings.length!==t.length||(i.encodings.forEach((r,s)=>{if(r.active===!1)return;const a=t[s];a.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(r.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(r.maxFramerate=a.maxFramerate),a.priority!==void 0&&(r.priority=a.priority,r.networkPriority=a.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return I(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,A,c,l,d;if(yield t.setProcessor.call(r,i,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var u=!0,h=$i(r.simulcastCodecs.values()),p;p=yield h.next(),a=p.done,!a;u=!0)c=p.value,u=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){o={error:m}}finally{try{!u&&!a&&(A=h.return)&&(yield A.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return I(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)},LE))}setPublishingCodecs(e){return I(this,void 0,void 0,function*(){var t,i,r,s,a,o,A;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(er(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=$i(e);r=yield i.next(),s=r.done,!s;t=!0){A=r.value,t=!1;const l=A;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(er(l.codec),l.qualities);else{const d=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const u of l.qualities)if(u.enabled){c.push(l.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Pv(d.sender,d.encodings,l.qualities,this.senderLock,er(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return I(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 Pv(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return I(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,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&er(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings: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 I(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),K3()&&this.isInBackground&&this.source===H.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Pv(n,e,t,i,r,s,a){return I(this,void 0,void 0,function*(){const o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const A=n.getParameters(),c=A.encodings;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:c,senderEncodings:e}));return}let l=!1;!1&&c[0].scalabilityMode||(r&&t.some(h=>h.enabled)&&t.forEach(h=>h.enabled=!0),c.forEach((u,h)=>{var p;let m=(p=u.rid)!==null&&p!==void 0?p:"";m===""&&(m="q");const v=eC(m),w=t.find(b=>b.quality===v);w&&u.active!==w.enabled&&(l=!0,u.active=w.enabled,s.debug("setting layer ".concat(w.quality," to ").concat(u.active?"enabled":"disabled"),a),Qa()&&(w.enabled?(u.scaleResolutionDownBy=e[h].scaleResolutionDownBy,u.maxBitrate=e[h].maxBitrate,u.maxFrameRate=e[h].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))})),l&&(A.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:A.encodings})),yield n.setParameters(A))}finally{o()}})}function eC(n){switch(n){case"f":return mi.HIGH;case"h":return mi.MEDIUM;case"q":return mi.LOW;default:return mi.HIGH}}function Dv(n,e,t,i){if(!t)return[new Us({quality:mi.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new $3(r),a=[],o=s.suffix=="h"?1.5:2,A=s.suffix=="h"?2:3;for(let c=0;c<s.spatial;c+=1)a.push(new Us({quality:Math.min(mi.HIGH,s.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(A,c)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const A=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let c=eC((a=r.rid)!==null&&a!==void 0?a:"");return new Us({quality:c,width:Math.ceil(n/A),height:Math.ceil(e/A),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Lv="_lossy",Rv="_reliable",_v="_data_track",RE=2*1e3,c0="leave-reconnect",_E=3e4,OE=8*1024,NE=256*1024,HE=3,KE=3;var ki;(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"})(ki||(ki={}));var Me;(function(n){n[n.RELIABLE=0]="RELIABLE",n[n.LOSSY=1]="LOSSY",n[n.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(Me||(Me={}));const Ov=64e3;class VE extends oi.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=_m.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ki.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=Te,this.reliableDataSequence=1,this.reliableMessageBuffer=new xv,this.reliableReceivedState=new dE(_E),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new fn,this.handleDataChannel=i=>I(this,[i],void 0,function(r){var s=this;let a=r.channel;return function*(){if(!a)return;let o;if(a.label===Rv)s.reliableDCSub=a,o=s.handleDataMessage;else if(a.label===Lv)s.lossyDCSub=a,o=s.handleDataMessage;else if(a.label===_v)s.dataTrackDCSub=a,o=s.handleDataTrackMessage;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label)),a.onmessage=o}()}),this.handleDataMessage=i=>I(this,void 0,void 0,function*(){var r,s,a,o,A;const c=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",{data:i.data});return}const d=En.fromBinary(new Uint8Array(l));if(d.sequence>0&&d.participantSid!==""){const u=this.reliableReceivedState.get(d.participantSid);if(u&&d.sequence<=u)return;this.reliableReceivedState.set(d.participantSid,d.sequence)}if(((r=d.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(q.ActiveSpeakersUpdate,d.value.value.speakers);else if(((s=d.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const u=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(d.value.value.encryptedValue,d.value.value.iv,d.participantIdentity,d.value.value.keyIndex),h=U4.fromBinary(u.payload),p=new En({value:h.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((o=p.value)===null||o===void 0?void 0:o.case)==="user"&&Nv(p,p.value.value),this.emit(q.DataPacketReceived,p,d.value.value.encryptionType)}else((A=d.value)===null||A===void 0?void 0:A.case)==="user"&&Nv(d,d.value.value),this.emit(q.DataPacketReceived,d,At.NONE)}finally{c()}}),this.handleDataTrackMessage=i=>I(this,void 0,void 0,function*(){let r;if(i.data instanceof ArrayBuffer)r=i.data;else if(i.data instanceof Blob)r=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",{data:i.data});return}this.emit("dataTrackPacketReceived",new Uint8Array(r))}),this.handleDataError=i=>{if(this._isClosed)return;const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&i instanceof RTCErrorEvent&&i.error){const a=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(a.message),{error:a,errorDetail:a.errorDetail,sctpCauseCode:a.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(s),{event:i})},this.handleDataChannelClose=i=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(Me[i],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=i=>{this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=A=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(A,"ms. giving up")),this.emit(q.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===c0&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(q.TokenRefreshed,this.token),this.reconnectTimeout=Zt.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ki.Connected&&i();const s=()=>{this.off(q.Disconnected,a),i()},a=()=>{this.off(q.Restarted,s),r()};this.once(q.Restarted,s),this.once(q.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Me.RELIABLE){const s=this.dataChannelForKind(i);s&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(q.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.onRtpMapAvailable=i=>{const r=new Map;i.forEach(s=>{const a=s.codec.toLowerCase();T8(a)&&r.set(s.payload,a)}),this.emit(q.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>I(this,void 0,void 0,function*(){!this.url||!(yield fetch(Cc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===st.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===st.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Aa.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>I(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Cc(this.url),{method:"HEAD"}),In(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=si((t=e.loggerName)!==null&&t!==void 0?t:mn.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Dm(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new bn,this.dataProcessLock=new bn,this.dcBufferStatus=new Map([[Me.RELIABLE,!0],[Me.LOSSY,!0],[Me.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=i=>this.emit(q.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(q.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(q.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(q.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(q.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(q.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(q.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(q.SignalRequestResponse,i),this.client.onParticipantUpdate=i=>this.emit(q.ParticipantUpdate,i),this.client.onJoined=i=>this.emit(q.Joined,i),this.on(q.Closing,()=>{var i,r;(r=(i=this.bufferStatusLowClosingFuture).reject)===null||r===void 0||r.call(i,new Mt("engine closed"))}),this.bufferStatusLowClosingFuture.promise.catch(()=>{})}get logContext(){var e,t,i,r,s,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,r){return I(this,arguments,void 0,function(s,a,o,A){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var d,u,h;c._isNewlyCreated=!1,c.url=s,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();const p=!l&&L8();let m;if(p){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());const b=yield(d=c.pcManager)===null||d===void 0?void 0:d.publisher.createInitialOffer();b&&(m=pa(b.offer,b.offerId))}if(A!=null&&A.aborted)throw fe.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,fe.serviceNotFound("Simulated v1 path failure","v0-rtc");const v=yield c.client.join(s,a,o,A,l,m);c._isClosed=!1,c.latestJoinResponse=v,c.participantSid=(u=v.participant)===null||u===void 0?void 0:u.sid,c.subscriberPrimary=v.subscriberPrimary,p?(h=c.pcManager)===null||h===void 0||h.updateConfiguration(c.makeRTCConfiguration(v)):(c.pcManager||(yield c.configure(v,!l),l||c.applyInitialPublisherLayout()),(!c.subscriberPrimary||v.fastPublish)&&c.negotiate().catch(b=>{c.log.error(b)})),c.registerOnLineListener(),c.clientConfiguration=v.clientConfiguration,c.emit(q.SignalConnected,v);let w=v.serverInfo;return w||(w={version:v.serverVersion,region:v.serverRegion}),c.log.info("connected to Livekit Server ".concat(Object.entries(w).map(b=>{let k=pe(b,2),y=k[0],B=k[1];return"".concat(y,": ").concat(B)}).join(", "))),{joinResponse:v,serverInfo:w}}catch(p){if(p instanceof fe){if(p.reason===at.ServerUnreachable){if(c.log.warn("Couldn't connect to server, attempt ".concat(c.joinAttempts," of ").concat(c.maxJoinAttempts)),c.joinAttempts<c.maxJoinAttempts)return c.join(s,a,o,A,l)}else if(p.reason===at.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(p.message," – Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(s,a,o,A,!0)}throw p}}()})}close(){return I(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(q.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return I(this,void 0,void 0,function*(){var e;const t=i=>{i&&(i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null,i.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new xv,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 I(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Xr("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(fe.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{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 I(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return I(this,void 0,void 0,function*(){var i;if(!(this.pcManager&&this.pcManager.currentState!==Ut.NEW)){if(e){this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new Uv(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{const r=this.makeRTCConfiguration();this.pcManager=new Uv("publisher-only",this.loggerOptions,r)}this.emit(q.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>I(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===Ut.CONNECTED){const c=this.pcState===ki.New;this.pcState=ki.Connected,c&&this.emit(q.Connected,this.latestJoinResponse)}else r===Ut.FAILED&&(this.pcState===ki.Connected||this.pcState===ki.Reconnecting)&&(this.pcState=ki.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Aa.RR_SUBSCRIBER_FAILED:Aa.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===st.RECONNECTING,A=[Ut.FAILED,Ut.CLOSING,Ut.CLOSED].includes(r);o&&A&&!this._isClosed&&this.emit(q.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(q.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>I(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{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",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>I(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{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),{cid:e.cid});return}const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(q.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(q.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(q.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(q.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(q.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(q.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(q.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(q.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(q.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Aa.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e==null?void 0:e.action,")"),{reason:e==null?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(q.ServerRegionsReported,e.regions)),e.action){case po.DISCONNECT:this.emit(q.Disconnected,e==null?void 0:e.reason),this.close();break;case po.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(c0);break;case po.RESUME:this.handleDisconnect(c0)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Bc())&&Im()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===gc.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),ar()||this.addMediaSections(HE,KE)}addMediaSections(e,t){var i,r;const s={direction:"recvonly"};for(let a=0;a<e;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("audio",s);for(let a=0;a<t;a++)(r=this.pcManager)===null||r===void 0||r.addPublisherTransceiverOfKind("video",s)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Lv,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Rv,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(_v,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.onclose=this.handleDataChannelClose(Me.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(Me.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(Me.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Me.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Me.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Me.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Me.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,OE),NE)}},1e3))}createSender(e,t,i){return I(this,void 0,void 0,function*(){let r;if(Vp())r=yield this.createTransceiverRTCRtpSender(e,t,i);else if(Gp())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Mt("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,i,r){return I(this,void 0,void 0,function*(){let s;if(Vp())s=yield this.createSimulcastTransceiverSender(e,t,i,r);else if(Gp())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Mt("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,i),s})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r,s;const a=this.frameMetadataWorker;if(!a||!((i=this.signalOpts)===null||i===void 0)&&i.e2eeEnabled)return;const o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,A=Dd(o);if(Bc()){A&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!xc((s=this.options.frameMetadata)!==null&&s!==void 0?s:this.options.packetTrailer)||!("createEncodedStreams"in e)){A&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const c=e.createEncodedStreams(),l=c.readable,d=c.writable;A?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:d,packetTrailer:o}},[l,d]):l.pipeTo(d)}createTransceiverRTCRtpSender(e,t,i){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),as(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return I(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===gc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Ut.NEW)===Ut.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Mt?(this.log.debug("received unrecoverable error",{error:s}),a=!1):s instanceof qa||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Aa.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(q.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",{error:t})}return null}restartConnection(e){return I(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new Mt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(q.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new qa;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof fe&&a.reason===at.NotAllowed?new Mt("could not reconnect, token might be expired"):new qa}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(q.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==st.CONNECTED)throw new qa("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(q.Restarted)}catch(s){const a=yield(i=this.regionStrategy)===null||i===void 0?void 0:i.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return I(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Mt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Mt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(q.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof fe&&r.reason===at.NotAllowed?new Mt("could not reconnect, token might be expired"):r instanceof fe&&r.reason===at.LeaveRequest?r:new qa(s)}if(this.emit(q.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==st.CONNECTED)throw new qa("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!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(q.Resumed)})}waitForPCInitialConnection(e,t){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return I(this,void 0,void 0,function*(){this.pcState=ki.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield In(RE),!this.pcManager)throw new Mt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ki.Connected}catch(e){throw this.pcState=ki.Disconnected,fe.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return I(this,void 0,void 0,function*(){const i=new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcAck",value:new Eu({requestId:t})}});yield this.sendDataPacket(i,Me.RELIABLE)})}sendDataPacket(e,t){return I(this,void 0,void 0,function*(){var i,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=q8(e);if(o){const A=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new M4({encryptedValue:A.payload,iv:A.iv,keyIndex:A.keyIndex})}}}t===Me.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const s=e.toBinary(),a=Math.min((r=(i=this.pcManager)===null||i===void 0?void 0:i.getMaxPublisherMessageSize())!==null&&r!==void 0?r:Ov,Ov);if(typeof a<"u"&&a!==0&&s.byteLength>a)throw new i8("cannot publish data packet larger than ".concat(a," bytes (got ").concat(s.byteLength,")"));switch(t){case Me.LOSSY:case Me.DATA_TRACK_LOSSY:return this.sendLossyBytes(s,t);case Me.RELIABLE:const o=this.dataChannelForKind(t);if(o){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:s,sequence:e.sequence}),this.attemptingReconnect)return;o.send(s)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"drop";return function*(){yield s.ensurePublisherConnected(r);const o=s.dataChannelForKind(r);if(o){if(!s.isBufferStatusLow(r))switch(a){case"wait":yield s.waitForBufferStatusLow(r);break;case"drop":s.lossyDataDropCount+=1,s.lossyDataDropCount%100===0&&s.log.warn("dropping lossy data channel messages, total dropped: ".concat(s.lossyDataDropCount));return}if(s.lossyDataStatCurrentBytes+=i.byteLength,s.attemptingReconnect)return;o.send(i)}s.updateAndEmitDCBufferStatus(r)}()})}resendReliableMessagesForResume(e){return I(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Me.RELIABLE);const t=this.dataChannelForKind(Me.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(Me.RELIABLE)})}waitForBufferStatusLow(e){return I(this,void 0,void 0,function*(){return new Rn((t,i)=>I(this,void 0,void 0,function*(){if(this.isClosed&&i(new Mt("engine closed")),this.isBufferStatusLow(e))t();else{const r=this.dataChannelForKind(e);if(!r){i(new Mt("DataChannel not found, kind: ".concat(e)));return}this.bufferStatusLowClosingFuture.promise.catch(s=>i(s)),r.addEventListener("bufferedamountlow",()=>t(),{once:!0})}}))})}ensureDataTransportConnected(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new Mt("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw fe.internal("".concat(o," connection not set"));let A=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),A=!0),!A&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(A=!0),A&&i.negotiate().catch(d=>{i.log.error(d)});const c=i.dataChannelForKind(t,r);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield In(50)}throw fe.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))}()})}ensurePublisherConnected(e){return I(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![Ut.CONNECTING,Ut.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return I(this,void 0,void 0,function*(){return new Rn((e,t)=>I(this,void 0,void 0,function*(){if(!this.pcManager){t(new xa("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new xa("cannot negotiate on closed engine")),this.on(q.Closing,r),this.on(q.Restarting,r),this.pcManager.publisher.off(Ts.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(Ts.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(s){if(i.signal.aborted){e();return}s instanceof xa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Aa.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(q.Closing,r),this.off(q.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case Me.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case Me.LOSSY:return t?this.lossyDCSub:this.lossyDC;case Me.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,i){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const A=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),d=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,p=new Array;e.forEach(m=>{m.isDesired!==u&&h.push(m.trackSid),m.isEnabled||p.push(m.trackSid)}),this.client.sendSyncState(new xm({answer:this.pcManager.mode==="publisher-only"?c?pa({sdp:c.sdp,type:c.type}):void 0:d?pa({sdp:d.sdp,type:d.type}):void 0,offer:this.pcManager.mode==="publisher-only"?A?pa({sdp:A.sdp,type:A.type}):void 0:l?pa({sdp:l.sdp,type:l.type}):void 0,subscription:new Mu({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:l8(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((m,v)=>new $4({publisherSid:v,lastSeq:m})),publishDataTracks:i.map(m=>new vm({info:Ld.toProtobuf(m)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new e3({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(Me.LOSSY),Zi.PUBLISHER),t(this.dataChannelForKind(Me.RELIABLE),Zi.PUBLISHER),t(this.dataChannelForKind(Me.LOSSY,!0),Zi.SUBSCRIBER),t(this.dataChannelForKind(Me.RELIABLE,!0),Zi.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Zt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ti()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ti()&&(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 r=Object.entries(this.midToTrackId).find(s=>pe(s,1)[0]===i);if(r)return r[1]}}}function Nv(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}const Xp=5e3,GE=3e4;class Ve{static fetchRegionSettings(e,t,i){return I(this,void 0,void 0,function*(){const r=yield Ve.fetchLock.lock();try{const s=yield fetch("".concat(zE(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(s.ok){const a=D8(s.headers),o=a?a*1e3:Xp;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?fe.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):fe.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof fe?s:i!=null&&i.aborted?fe.cancelled("Region fetching was aborted"):fe.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,i){return I(this,void 0,void 0,function*(){const r=Ve.settingsTimeouts.get(e.hostname);clearTimeout(r),Ve.settingsTimeouts.set(e.hostname,setTimeout(()=>I(this,void 0,void 0,function*(){try{const s=yield Ve.fetchRegionSettings(e,t);Ve.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof fe&&s.reason===at.NotAllowed){Te.debug("token is not valid, cancelling auto region refresh");return}Te.debug("auto refetching of region settings failed",{error:s}),Ve.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){Ve.cache.set(e.hostname,i),Ve.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=Ve.settingsTimeouts.get(e);t&&(clearTimeout(t),Ve.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Ve.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=Ve.connectionTrackers.get(e);i&&i.connectionCount===0&&(Te.debug("stopping region refetch after disconnect delay",{hostname:e}),Ve.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},GE))}static cancelCleanup(e){const t=Ve.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Ve.connectionTrackers.get(e);t||(t={connectionCount:0},Ve.connectionTrackers.set(e,t)),t.connectionCount++,Ve.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Ve.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&Ve.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),r=Ve.cache.get(i.hostname);Ve.scheduleRefetch(this.serverUrl,this.token,(t=r==null?void 0:r.maxAgeInMs)!==null&&t!==void 0?t:Xp)}isCloud(){return Ro(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return I(this,void 0,void 0,function*(){return Ve.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return I(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Ve.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Ve.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),Te.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ve.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ve.cache=new Map;Ve.settingsTimeouts=new Map;Ve.connectionTrackers=new Map;Ve.fetchLock=new bn;function zE(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class tC{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 Ei("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Dn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ei("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Dn.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class qE extends tC{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();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>I(this,void 0,void 0,function*(){try{const i=this.signal;if(i!=null&&i.aborted)throw i.reason;const r=yield new Promise((s,a)=>{if(i){const o=()=>a(i.reason);i.addEventListener("abort",o,{once:!0}),e.read().then(s,a).finally(()=>{i.removeEventListener("abort",o)})}else e.read().then(s,a)});return r.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(i){throw t(),i}}),return(){return I(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,s,a;let o=new Set;const A=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=$i(A),d;d=yield l.next(),i=d.done,!i;c=!0){a=d.value,c=!1;const u=a;o.add(u)}}catch(u){r={error:u}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}}class WE extends tC{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=sd(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>I(this,void 0,void 0,function*(){try{if(i!=null&&i.aborted)throw i.reason;const s=yield new Promise((a,o)=>{if(i){const A=()=>o(i.reason);i.addEventListener("abort",A,{once:!0}),e.read().then(a,o).finally(()=>{i.removeEventListener("abort",A)})}else e.read().then(a,o)});if(s.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(s.value);let a;try{a=t.decode(s.value.content)}catch(o){throw new Ei("Cannot decode datastream chunk ".concat(s.value.chunkIndex," as text: ").concat(o),Dn.DecodeFailed)}return{done:!1,value:a}}}catch(s){throw r(),s}}),return(){return I(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,s,a;let o="";const A=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=$i(A),d;d=yield l.next(),i=d.done,!i;c=!0)a=d.value,c=!1,o+=a}catch(u){r={error:u}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o}()})}}class jE{constructor(){this.log=Te,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const i=t.packet,r=t.encryptionType;this.handleDataStreamPacket(i,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Ei('A text stream handler for topic "'.concat(e,'" has already been set.'),Dn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ei('A byte stream handler for topic "'.concat(e,'" has already been set.'),Dn.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){const a=new Ei("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Dn.AbnormalEnd);for(const o of i){var r=pe(o,2);const A=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(A)}for(const o of t){var s=pe(o,2);const A=s[0];s[1].controller.error(a),this.textStreamControllers.delete(A)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}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){var r;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sd(e.timestamp),attributes:e.attributes,encryptionType:i},A=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Ei("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Dn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new qE(o,A,sd(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={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},A=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Ei("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Dn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new WE(o,A,sd(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Dn.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),Dn.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Dn.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),Dn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class nC{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 I(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 YE extends nC{}class JE extends nC{}const Hv=15e3;class XE{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return I(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),A=new Array(o?o.length+1:1).fill(0),c=(d,u)=>{var h;A[u]=d;const p=A.reduce((m,v)=>m+v,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,p)},l=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield l.write(e),c(1,0),yield l.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((d,u)=>I(this,void 0,void 0,function*(){return this._sendFile(o[u],d,{topic:t.topic,mimeType:d.type,onProgress:h=>{c(h,u+1)}})})))),l.info})}streamText(e){return I(this,void 0,void 0,function*(){var t,i,r;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?At.GCM:At.NONE,attachedStreamIds:e==null?void 0:e.attachedStreamIds},o=new Md({streamId:s,mimeType:a.mimeType,topic:a.topic,timestamp:ca(a.timestamp),totalLength:ca(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new V4({version:e==null?void 0:e.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Ep.UPDATE:Ep.CREATE})}}),A=e==null?void 0:e.destinationIdentities,c=new En({destinationIdentities:A,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Me.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(m){return I(this,void 0,void 0,function*(){for(const v of P8(m,Hv)){const w=new Ud({content:v,streamId:s,chunkIndex:ca(l)}),b=new En({destinationIdentities:A,value:{case:"streamChunk",value:w}});yield d.sendDataPacket(b,Me.RELIABLE),l+=1}})},close(){return I(this,void 0,void 0,function*(){const m=new Fd({streamId:s}),v=new En({destinationIdentities:A,value:{case:"streamTrailer",value:m}});yield d.sendDataPacket(v,Me.RELIABLE)})},abort(m){}});let h=()=>I(this,void 0,void 0,function*(){yield p.close()});d.once(q.Closing,h);const p=new YE(u,a,()=>this.engine.off(q.Closing,h));return p})}sendFile(e,t){return I(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return I(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const o=yield a.read(),A=o.done,c=o.value;if(A)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return I(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?At.GCM:At.NONE},l=new Md({totalLength:ca(c.size),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:ca(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new G4({name:c.name})}}),d=new En({destinationIdentities:A,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(d,Me.RELIABLE);let u=0;const h=new bn,p=this.engine,m=this.log,v=new WritableStream({write(b){return I(this,void 0,void 0,function*(){const k=yield h.lock();let y=0;try{for(;y<b.byteLength;){const B=b.slice(y,y+Hv),E=new En({destinationIdentities:A,value:{case:"streamChunk",value:new Ud({content:B,streamId:o,chunkIndex:ca(u)})}});yield p.sendDataPacket(E,Me.RELIABLE),u+=1,y+=B.byteLength}}finally{k()}})},close(){return I(this,void 0,void 0,function*(){const b=new Fd({streamId:o}),k=new En({destinationIdentities:A,value:{case:"streamTrailer",value:b}});yield p.sendDataPacket(k,Me.RELIABLE)})},abort(b){m.error("Sink error:",b)}});return new JE(v,c)})}}function iC(n){if(n.length===0)return new AbortController().signal;if(n.length===1)return n[0];for(const r of n)if(r.aborted)return r;const e=new AbortController,t=Array(n.length),i=()=>{for(const r of t)r()};return n.forEach((r,s)=>{const a=()=>{e.abort(r.reason),i()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function rC(n){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(n," ms"),"TimeoutError"))},n),e.signal}const _t=1,Lr=2,Kv=4,ZE=8,Vv=0,Gv=12,zv=5,$E=7,qv=3,eT=3,Wv=2,jv=1,Yv=0,Jv=3,sl=2,Xv=2,tT=1,nT=0;var Kr;(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"})(Kr||(Kr={}));class Ln extends Hi{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Kr[t]}static tooShort(){return new Ln("Too short to contain a valid header",Kr.TooShort)}static headerOverrun(){return new Ln("Header exceeds total packet length",Kr.HeaderOverrun)}static missingExtWords(){return new Ln("Extension word indicator is missing",Kr.MissingExtWords)}static unsupportedVersion(e){return new Ln("Unsupported version ".concat(e),Kr.UnsupportedVersion)}static invalidHandle(e){return new Ln("invalid track handle: ".concat(e.message),Kr.InvalidHandle,{cause:e})}static malformedExt(e){return new Ln("Extension with tag ".concat(e," is malformed"),Kr.MalformedExt)}}var ec;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(ec||(ec={}));class Sc extends Hi{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=ec[t]}static tooSmallForHeader(){return new Sc("Buffer cannot fit header",ec.TooSmallForHeader)}static tooSmallForPayload(){return new Sc("Buffer cannot fit payload",ec.TooSmallForPayload)}}class Pu{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),r=this.toBinaryInto(i);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var Oo;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Oo||(Oo={}));class sC extends Pu{}class tr extends sC{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return _t+_t+tr.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,tr.tag),t+=_t,e.setUint8(t,tr.lengthBytes),t+=_t,e.setBigUint64(t,this.timestamp),t+=ZE;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:tr.tag,lengthBytes:tr.lengthBytes,timestamp:this.timestamp}}}tr.tag=Oo.UserTimestamp;tr.lengthBytes=8;class nr extends sC{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return _t+_t+nr.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,nr.tag),t+=_t,e.setUint8(t,nr.lengthBytes),t+=_t,e.setUint8(t,this.keyIndex),t+=_t;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=_t;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:nr.tag,lengthBytes:nr.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}nr.tag=Oo.E2ee;nr.lengthBytes=13;class wo extends Pu{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){const r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){const r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=Pm(e);let i,r,s=0;for(;t.byteLength-s>=_t+_t;){const a=t.getUint8(s);s+=_t;const o=t.getUint8(s);if(s+=_t,a!==nT)switch(a){case Oo.UserTimestamp:if(t.byteLength-s<tr.lengthBytes)throw Ln.malformedExt(a);i=new tr(t.getBigUint64(s)),s+=o;break;case Oo.E2ee:if(t.byteLength-s<nr.lengthBytes)throw Ln.malformedExt(a);const A=t.getUint8(s),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let d=s;d+=_t,d+=l*_t,c[l]=t.getUint8(d)}r=new nr(A,c),s+=o;break;default:if(t.byteLength-s<o)throw Ln.malformedExt(a);s+=o;break}}return[new wo({userTimestamp:i,e2ee:r}),t.byteLength]}toJSON(){var e,t,i,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(i=this.e2ee)===null||i===void 0?void 0:i.toJSON())!==null&&r!==void 0?r:null}}}const aC={from(n){return{payload:n.payload,extensions:new wo({userTimestamp:n.userTimestamp?new tr(n.userTimestamp):void 0})}},lossyIntoFrame(n){var e;return{payload:n.payload,userTimestamp:(e=n.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},oC=Symbol.for("lk.track"),AC=Symbol.for("lk.data-track");class cC{constructor(e,t,i){this.trackSymbol=oC,this.isLocal=!1,this.typeSymbol=AC,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e==null?void 0:e.signal,e==null?void 0:e.bufferSize),i=pe(t,2),r=i[0];return i[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class kc extends Pu{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=(t=e.extensions)!==null&&t!==void 0?t:new wo}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((sl+e)/4),i=t*4-sl-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:i}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let r=Gv;return t>0&&(r+=sl+t+i),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Sc.tooSmallForHeader();let t=Vv<<zv,i;switch(this.marker){case yt.Inter:i=Yv;break;case yt.Final:i=jv;break;case yt.Start:i=Wv;break;case yt.Single:i=Jv;break}t|=i<<qv;const r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<Xv);let A=0;if(e.setUint8(A,t),A+=_t,e.setUint8(A,0),A+=_t,e.setUint16(A,this.trackHandle),A+=Lr,e.setUint16(A,this.sequence.value),A+=Lr,e.setUint16(A,this.frameNumber.value),A+=Lr,e.setUint32(A,this.timestamp.asTicks()),A+=Kv,s>0){const l=a-1;e.setUint16(A,l),A+=Lr;const d=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+A));A+=d;for(let u=0;u<o;u+=1)e.setUint8(A,0),A+=_t}const c=this.toBinaryLengthBytes();if(A!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(A," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=Pm(e);if(t.byteLength<Gv)throw Ln.tooShort();let i=0;const r=t.getUint8(i);i+=_t;const s=r>>zv&$E;if(s>Vv)throw Ln.unsupportedVersion(s);let a;switch(r>>qv&eT){case Wv:a=yt.Start;break;case jv:a=yt.Final;break;case Jv:a=yt.Single;break;case Yv:default:a=yt.Inter;break}const o=(r>>Xv&tT)>0;i+=_t;let A;try{A=nE.fromNumber(t.getUint16(i))}catch(h){throw h instanceof _o&&(h.isReason(ka.Reserved)||h.isReason(ka.TooLarge))?Ln.invalidHandle(h):h}i+=Lr;const c=rr.u16(t.getUint16(i));i+=Lr;const l=rr.u16(t.getUint16(i));i+=Lr;const d=yo.fromRtpTicks(t.getUint32(i));i+=Kv;let u=new wo;if(o){if(t.byteLength-i<Lr)throw Ln.missingExtWords();let h=t.getUint16(i);i+=Lr;let m=4*(h+1)-sl;if(i+m>t.byteLength)throw Ln.headerOverrun();let v=new DataView(t.buffer,t.byteOffset+i,m);const w=wo.fromBinary(v),b=pe(w,2),k=b[0],y=b[1];u=k,i+=y}return[new kc({marker:a,trackHandle:A,sequence:c,frameNumber:l,timestamp:d,extensions:u}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var yt;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(yt||(yt={}));class Du extends Pu{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const i=this.header.toBinaryInto(e);if(t+=i,e.byteLength-t<this.payload.byteLength)throw Sc.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=_t;const r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){const t=Pm(e),i=kc.fromBinary(t),r=pe(i,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new Du(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const l0=si(mn.DataTracks);class Cr extends Hi{constructor(e,t,i,r){super(19,"Frame ".concat(i," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=fa[t],this.frameNumber=i}static interrupted(e,t){return new Cr("Interrupted by the start of a new frame ".concat(t),fa.Interrupted,e)}static unknownFrame(e){return new Cr("Initial packet was never received.",fa.UnknownFrame,e)}static bufferFull(e){return new Cr("Reorder buffer is full.",fa.BufferFull,e)}static incomplete(e,t,i){return new Cr("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),fa.Incomplete,e)}}var fa;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(fa||(fa={}));class Lu{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case yt.Single:return this.frameFromSingle(e,t);case yt.Start:return this.beginPartial(e,t);case yt.Inter:case yt.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==yt.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const r=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=r){const s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t!=null&&t.throwOnInterruption)throw Cr.interrupted(s,e.header.frameNumber.value);l0.warn("Data track frame ".concat(s," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==yt.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){const A=this.peekOldestPartialFrameNumber();if(typeof A!="number")break;if(this.partials.delete(A),t!=null&&t.throwOnInterruption)throw Cr.interrupted(A,s);l0.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(A," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==yt.Inter&&e.header.marker!==yt.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),Cr.unknownFrame(t);if(i.payloads.size>=Lu.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Cr.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&l0.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===yt.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const r=t.payloads.size;let s=0;for(const c of t.payloads.values())s+=c.length;const a=new Uint8Array(s);let o=t.startSequence.clone(),A=0;for(;;){const c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);const l=a.length-A;if(c.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(c.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(c,A),A+=c.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),Cr.incomplete(e,r,i-t.startSequence.value+1)}}Lu.MAX_BUFFER_PACKETS=128;var ma;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(ma||(ma={}));class Zn extends Hi{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=ma[t]}static unpublished(){return new Zn("The track has been unpublished and is no longer available",ma.Unpublished)}static timeout(){return new Zn("Request to subscribe to data track timed-out",ma.Timeout)}static disconnected(){return new Zn("Cannot subscribe to data track when disconnected",ma.Disconnected)}static cancelled(){return new Zn("Subscription to data track cancelled by caller",ma.Cancelled)}}const d0=si(mn.DataTracks);class iT{constructor(e){var t,i;const r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const s=new Lu;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return I(this,void 0,void 0,function*(){const t=this.depacketize(e);if(!t)return null;const i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(i){return d0.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return I(this,void 0,void 0,function*(){var t,i;const r=this.e2eeManager;if(!r)return e;const s=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!s)return d0.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return d0.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const vn=si(mn.DataTracks),rT=1e4,sT=16;class aT extends oi.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);if(!i){vn.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sT,r=null;const s=new fn,a=()=>{t==null||t.removeEventListener("abort",A)},o=()=>{if(a(),!r){vn.warn("ReadableStream subscribed to ".concat(e," was not started."));return}const l=this.descriptors.get(e);if(!l){vn.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(l.subscription.type!=="active"){vn.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}l.subscription.streamControllers.delete(r),l.subscription.streamControllers.size===0&&this.unSubscribeRequest(l.info.sid)},A=()=>{var l;if(!r)return;const d=this.descriptors.get(e);(d==null?void 0:d.subscription.type)==="active"&&d.subscription.streamControllers.delete(r),r.error(Zn.cancelled()),(l=s.reject)===null||l===void 0||l.call(s,Zn.cancelled()),o()};return[new ReadableStream({start:l=>{r=l,this.subscribeRequest(e,t).then(()=>I(this,void 0,void 0,function*(){var d,u,h;const p=this.descriptors.get(e);if(!p){vn.error("Unknown track ".concat(e));const m=Zn.disconnected();l.error(m),(d=s.reject)===null||d===void 0||d.call(s,m);return}if(p.subscription.type!=="active"){vn.error("Subscription for track ".concat(e," is not active"));const m=Zn.disconnected();l.error(m),(u=s.reject)===null||u===void 0||u.call(s,m);return}if(t!=null&&t.aborted){A();return}t==null||t.addEventListener("abort",A),p.subscription.streamControllers.set(l,a),(h=s.resolve)===null||h===void 0||h.call(s)})).catch(d=>{var u;l.error(d),(u=s.reject)===null||u===void 0||u.call(s,d)})},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:i})),s.promise]}subscribeRequest(e,t){return I(this,void 0,void 0,function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const r=(s,a,o)=>I(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));const A=iC([a,o].filter(d=>typeof d<"u")),c=new fn;s.subscription.completionFuture.promise.then(()=>{var d;return(d=c.resolve)===null||d===void 0?void 0:d.call(c)}).catch(d=>{var u;return(u=c.reject)===null||u===void 0?void 0:u.call(c,d)});const l=()=>{var d;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o!=null&&o.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(d=c.reject)===null||d===void 0||d.call(c,Zn.cancelled())}};A.aborted&&l(),A.addEventListener("abort",l),yield c.promise,A.removeEventListener("abort",l)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new fn,pendingRequestCount:1,cancel:()=>{var a,o;const A=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),A.type==="pending"&&((o=(a=A.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?Zn.timeout():Zn.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const s=rC(rT);yield r(i,t,s);return}case"pending":{i.subscription.pendingRequestCount+=1,yield r(i,t);return}case"active":return}})}querySubscribed(){return I(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){vn.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);const r=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var i=pe(r,2);const s=i[0],a=i[1];a();try{s.close()}catch(o){vn.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return I(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const s of e.entries()){var i=pe(s,2);const a=i[0],o=i[1],A=new Set;for(const c of o)A.add(c.sid),!this.descriptors.has(c.sid)&&(yield this.handleTrackPublished(a,c));t.set(a,A)}for(const s of t.entries()){var r=pe(s,2);const a=r[0],o=r[1];let c=Array.from(this.descriptors.entries()).filter(l=>{let d=pe(l,2);return d[0],d[1].publisherIdentity===a}).map(l=>pe(l,1)[0]).filter(l=>!o.has(l));for(const l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return I(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return I(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){vn.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);const r=new cC(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){vn.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=pe(i,2);const r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var i,r;const s=this.descriptors.get(t);if(!s){vn.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{vn.warn("No subscription for ".concat(t));return}case"active":{s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{const a=new iT({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}}}packetReceived(e){return I(this,void 0,void 0,function*(){let t;try{var i=Du.fromBinary(e),r=pe(i,1);t=r[0]}catch(A){vn.error("Failed to deserialize packet: ".concat(A));return}const s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){vn.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(s);if(!a){vn.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){vn.warn("Received packet for track ".concat(s," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const A of a.subscription.streamControllers.keys()){if(A.desiredSize!==null&&A.desiredSize<=0){vn.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(A.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const c=aC.lossyIntoFrame(o);A.enqueue(c)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=pe(t,2);const i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(i=(t=r.subscription.completionFuture).reject)===null||i===void 0||i.call(t,Zn.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,Zn.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Ru extends Hi{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Nd[t]}static mtuTooShort(){return new Ru("MTU is too short to send frame",Nd.MtuTooShort)}}var Nd;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(Nd||(Nd={}));class Nm{constructor(e,t){this.sequence=rr.u16(0),this.frameNumber=rr.u16(0),this.clock=ha.rtpStartingNow(yo.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?yt.Single:e===0?yt.Start:e===t-1?yt.Final:yt.Inter}*packetize(e,t){var i;const r=this.frameNumber.getThenIncrement(),s={marker:yt.Inter,trackHandle:this.handle,sequence:rr.u16(0),frameNumber:r,timestamp:(i=t==null?void 0:t.now)!==null&&i!==void 0?i:this.clock.now(),extensions:e.extensions},a=new kc(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Ru.mtuTooShort();const o=this.mtuSizeBytes-a,A=Math.ceil(e.payload.byteLength/o);for(let l=0,d=0;d<e.payload.byteLength;c=[l+1,d+o],l=c[0],d=c[1],c){var c;const u=this.sequence.getThenIncrement(),h=new kc(Object.assign(Object.assign({},s),{marker:Nm.computeFrameMarker(l,A),sequence:u})),p=Math.min(o,e.payload.byteLength-d),m=new Uint8Array(e.payload.buffer,e.payload.byteOffset+d,p);yield new Du(h,m)}}}var ji;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled",n[n.InvalidName=6]="InvalidName",n[n.Unknown=7]="Unknown"})(ji||(ji={}));class on extends Hi{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=ji[t],this.rawMessage=i==null?void 0:i.rawMessage}static notAllowed(e){return new on("Data track publishing unauthorized",ji.NotAllowed,{rawMessage:e})}static duplicateName(e){return new on("Track name already taken",ji.DuplicateName,{rawMessage:e})}static invalidName(e){return new on("Track name is invalid",ji.InvalidName,{rawMessage:e})}static timeout(){return new on("Publish data track timed-out. Does the LiveKit server support data tracks?",ji.Timeout)}static limitReached(e){return new on("Data track publication limit reached",ji.LimitReached,{rawMessage:e})}static unknown(e,t){return new on("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),ji.Unknown)}static disconnected(){return new on("Room disconnected",ji.Disconnected)}static cancelled(){return new on("Publish data track cancelled by caller",ji.Cancelled)}}var tc;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(tc||(tc={}));class Is extends Hi{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=tc[t]}static trackUnpublished(){return new Is("Track is no longer published",tc.TrackUnpublished)}static dropped(e){return new Is("Frame was dropped",tc.Dropped,{cause:e})}}var nc;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(nc||(nc={}));class Ec extends Hi{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=nc[t]}static packetizer(e){return new Ec("Error packetizing frame",nc.Packetizer,{cause:e})}static encryption(e){return new Ec("Error encrypting frame",nc.Encryption,{cause:e})}}class _u{constructor(e,t){this.trackSymbol=oC,this.isLocal=!0,this.typeSymbol=AC,this.handle=null,this.log=Te,this.flushedFuture=new fn,this.isFlushed=!0,this.handleManagerReset=()=>{var i,r;(r=(i=this.flushedFuture).resolve)===null||r===void 0||r.call(i),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=i=>{var r,s;this.isFlushed=i.isFlushed,i.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new fn)},this.options=e,this.manager=t,this.log=si(mn.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const r=new _u(e,t);return r.handle=i,r}get info(){const e=this.descriptor;if((e==null?void 0:e.type)==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return I(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw Is.trackUnpublished();const t=aC.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(i){throw i}}flush(){return I(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return I(this,void 0,void 0,function*(){if(!this.handle){Te.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class Ou{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Nm(e.info.pubHandle,Ou.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return _7(this,arguments,function*(){const i=yield Lo(this.encryptIfNeeded(e));try{yield Lo(yield*O7($i(this.packetizer.packetize(i))))}catch(r){throw r instanceof Ru?Ec.packetizer(r):r}})}encryptIfNeeded(e){return I(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Ec.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new nr(t.keyIndex,t.iv),e})}}Ou.TRANSPORT_MTU_BYTES=16e3;const pr=si(mn.DataTracks),Zv={pending(){return{type:"pending",completionFuture:new fn}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new Ou({info:n,e2eeManager:e}),unpublishingFuture:new fn}}},oT=1e4;class Hm extends oi.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new iE,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new Hm;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return I(this,void 0,void 0,function*(){var i,r,s,a,o;const A=this.getDescriptor(e);if((A==null?void 0:A.type)!=="active"||A.publishState==="unpublished")throw Is.trackUnpublished();if(A.publishState==="republishing")throw Is.dropped("Data track republishing");try{try{for(var c=!0,l=$i(A.pipeline.processFrame(t)),d;d=yield l.next(),i=d.done,!i;c=!0){a=d.value,c=!1;const u=a,h=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,h+1),h===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:u.toBinary()})}}catch(u){r={error:u}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(u){throw Is.dropped(u)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(pr.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return I(this,void 0,void 0,function*(){const i=this.handleAllocator.get();if(!i)throw on.limitReached();const r=rC(oT),s=t?iC([t,r]):r;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const a=Zv.pending();this.descriptors.set(i,a);const o=()=>{var A,c;const l=this.descriptors.get(i);if(!l){pr.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),l.type==="pending"&&((c=(A=l.completionFuture).reject)===null||c===void 0||c.call(A,r.aborted?on.timeout():on.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>i)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:_u.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return I(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){pr.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){pr.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,r,s,a;const o=this.descriptors.get(e);if(!o){pr.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const A=t.data,c=A.usesE2ee?this.e2eeManager:null;this.descriptors.set(A.pubHandle,Zv.active(A,c)),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}else(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){pr.warn("Track ".concat(e," already active"));return}if(t.type==="error"){pr.warn("Republish failed for track ".concat(e));return}pr.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;const r=this.descriptors.get(e);if(!r){pr.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){pr.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(i=(t=r.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(const r of this.descriptors.entries()){var i=pe(r,2);const s=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,on.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return I(this,void 0,void 0,function*(){var e,t,i,r;this.handleAllocator.reset();for(const s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,on.disconnected());break;case"active":(r=(i=s.unpublishingFuture).resolve)===null||r===void 0||r.call(i),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class tt extends Error{constructor(e,t,i,r){super(t),this.code=e,this.message=$v(t,tt.MAX_MESSAGE_BYTES),this.data=i?$v(i,tt.MAX_DATA_BYTES):void 0,typeof(r==null?void 0:r.cause)<"u"&&(this.cause=r==null?void 0:r.cause)}static fromProto(e){return new tt(e.code,e.message,e.data)}toProto(){return new P4({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new tt(tt.ErrorCode[e],tt.ErrorMessage[e],t,i)}}tt.MAX_MESSAGE_BYTES=256;tt.MAX_DATA_BYTES=15360;tt.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};tt.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 lC=15360,dC="lk.rpc_request",uC="lk.rpc_response";var yn;(function(n){n.RPC_REQUEST_ID="lk.rpc_request_id",n.RPC_REQUEST_METHOD="lk.rpc_request_method",n.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",n.RPC_REQUEST_VERSION="lk.rpc_request_version"})(yn||(yn={}));const AT=1,hC=2;function Km(n){return new TextEncoder().encode(n).length}function $v(n,e){if(Km(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}class cT extends oi.EventEmitter{constructor(e,t,i,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=r}performRpc(e){return I(this,arguments,void 0,function(t){var i=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,A=o===void 0?15e3:o;return function*(){const d=i.getRemoteParticipantClientProtocol(r);if(Km(a)>lC&&d<Qd)throw tt.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const h=i.getServerVersion();if(h&&Er(h,"1.8.0")<0)throw tt.builtIn("UNSUPPORTED_SERVER");const p=Math.max(A,8e3),m=crypto.randomUUID(),v=new fn;let w=null;const b=setTimeout(()=>{var y;i.pendingAcks.delete(m),(y=v.reject)===null||y===void 0||y.call(v,tt.builtIn("CONNECTION_TIMEOUT")),i.pendingResponses.delete(m),w!==null&&clearTimeout(w)},7e3);i.pendingAcks.set(m,{resolve:()=>{clearTimeout(b)},participantIdentity:r}),i.pendingResponses.set(m,{completionFuture:v,participantIdentity:r}),yield i.publishRpcRequest(r,m,s,a,p,d),w=setTimeout(()=>{var y;i.pendingResponses.delete(m),(y=v.reject)===null||y===void 0||y.call(v,tt.builtIn("RESPONSE_TIMEOUT"))},A);const k=v.promise.finally(()=>{clearTimeout(w),i.pendingAcks.has(m)&&(i.log.warn("RPC response received before ack",m),i.pendingAcks.delete(m),clearTimeout(b))});return[m,k]}()})}publishRpcRequest(e,t,i,r,s,a){return I(this,void 0,void 0,function*(){if(a>=Qd){const o=yield this.outgoingDataStreamManager.streamText({topic:dC,destinationIdentities:[e],attributes:{[yn.RPC_REQUEST_ID]:t,[yn.RPC_REQUEST_METHOD]:i,[yn.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[yn.RPC_REQUEST_VERSION]:"".concat(hC)}});yield o.write(r),yield o.close();return}this.emit("sendDataPacket",{packet:new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcRequest",value:new fm({id:t,method:i,payload:r,responseTimeoutMs:s,version:AT})}})})})}handleIncomingDataStream(e,t,i){return I(this,void 0,void 0,function*(){const r=i[yn.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(yn.RPC_REQUEST_ID," not set."));return}const s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(r,tt.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).resolve)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).reject)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var i=pe(a,2);const o=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var r=pe(a,2);const o=r[0];var s=r[1];const A=s.participantIdentity,c=s.completionFuture;A===e&&((t=c.reject)===null||t===void 0||t.call(c,tt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class lT extends oi.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return I(this,void 0,void 0,function*(){var i;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,tt.builtIn("UNSUPPORTED_VERSION"));return}const r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,tt.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof tt?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=tt.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((i=a==null?void 0:a.message)!==null&&i!==void 0?i:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,i){return I(this,void 0,void 0,function*(){const r=i[yn.RPC_REQUEST_ID],s=i[yn.RPC_REQUEST_METHOD],a=parseInt(i[yn.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[yn.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(yn.RPC_REQUEST_ID," / ").concat(yn.RPC_REQUEST_METHOD," / ").concat(yn.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(yn.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,tt.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),o!==hC){this.publishRpcResponsePacket(t,r,null,tt.builtIn("UNSUPPORTED_VERSION"));return}let A;try{A=yield e.readAll()}catch(d){this.log.warn("Error reading RPC request payload: ".concat(d)),this.publishRpcResponsePacket(t,r,null,tt.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:d}));return}const c=this.rpcHandlers.get(s);if(!c){this.publishRpcResponsePacket(t,r,null,tt.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:A,responseTimeout:a})}catch(d){let u;d instanceof tt?u=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),d),u=tt.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,u);return}yield this.publishRpcResponse(t,r,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcAck",value:new Eu({requestId:t})}})})}publishRpcResponsePacket(e,t,i,r){this.emit("sendDataPacket",{packet:new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcResponse",value:new mm({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}})})}publishRpcResponse(e,t,i){return I(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Qd){const a=yield this.outgoingDataStreamManager.streamText({topic:uC,destinationIdentities:[e],attributes:{[yn.RPC_REQUEST_ID]:t}});yield a.write(i),yield a.close();return}if(Km(i)>lC){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,tt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class dT extends W3{constructor(e,t,i,r,s,a){super(e,t,H.Kind.Audio,i,a),this.monitorReceiver=()=>I(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=Qu(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;ar()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ar())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return I(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(zp(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&zp(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(J.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(J.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return I(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})}}class qr extends oi.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=At.NONE,this.log=Te,this.handleMuted=()=>{this.emit(J.Muted)},this.handleUnmuted=()=>{this.emit(J.Unmuted)},this.log=si((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:mn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=H.Source.Unknown}setTrack(e){this.track&&(this.track.off(J.Muted,this.handleMuted),this.track.off(J.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(J.Muted,this.handleMuted),e.on(J.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),De(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==At.NONE}get audioTrack(){if(Sr(this.track))return this.track}get videoTrack(){if(as(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=H.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===H.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(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={}))})(qr||(qr={}));class Zp extends qr{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(J.Ended)},this.handleCpuConstrained=()=>{this.track&&as(this.track)&&this.emit(J.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(J.Ended,this.handleTrackEnded),this.track.off(J.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(J.Ended,this.handleTrackEnded),e.on(J.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 I(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return I(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return I(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return I(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Sr(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(hn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(hn.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(hn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(hn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(hn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(hn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Nu(n,e){return I(this,void 0,void 0,function*(){n??(n={});let t=!1;const i=H3(n),r=i.audioProcessor,s=i.videoProcessor,a=i.optionsWithoutProcessor;let o=a.audio,A=a.video;if(r&&typeof a.audio=="object"&&(a.audio.processor=r),s&&typeof a.video=="object"&&(a.video.processor=s),n.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const u=a.audio.deviceId;a.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:u}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const u=a.video.deviceId;a.video.deviceId={exact:u},t=!0,A=Object.assign(Object.assign({},a.video),{deviceId:{ideal:u}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const c=_3(a,Y3,J3),l=Em(c),d=navigator.mediaDevices.getUserMedia(l);a.audio&&(pn.userMediaPromiseMap.set("audioinput",d),d.catch(()=>pn.userMediaPromiseMap.delete("audioinput"))),a.video&&(pn.userMediaPromiseMap.set("videoinput",d),d.catch(()=>pn.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>I(this,void 0,void 0,function*(){const p=h.kind==="audio";let m;const v=p?l.audio:l.video;typeof v!="boolean"&&(m=v);const w=h.getSettings().deviceId;m!=null&&m.deviceId&&Sa(m.deviceId)!==w?m.deviceId=w:m||(m={deviceId:w});const b=kE(h,m,e);return b.kind===H.Kind.Video?b.source=H.Source.Camera:b.kind===H.Kind.Audio&&(b.source=H.Source.Microphone),b.mediaStream=u,Sr(b)&&r?yield b.setProcessor(r):as(b)&&s&&(yield b.setProcessor(s)),b})))}catch(u){if(!t)throw u;return Nu(Object.assign(Object.assign({},n),{audio:o,video:A}),e)}})}function uT(n){return I(this,void 0,void 0,function*(){return(yield Nu({audio:!1,video:!0}))[0]})}function hT(n){return I(this,void 0,void 0,function*(){return(yield Nu({audio:!0,video:!1}))[0]})}var xs;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(xs||(xs={}));function pT(n){switch(n){case FA.EXCELLENT:return xs.Excellent;case FA.GOOD:return xs.Good;case FA.POOR:return xs.Poor;case FA.LOST:return xs.Lost;default:return xs.Unknown}}class pC extends oi.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===vc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===ho.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:vc.STANDARD;var A;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=xs.Unknown,this.log=Te,this.loggerOptions=a,this.log=si((A=a==null?void 0:a.loggerName)!==null&&A!==void 0?A:mn.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const i of this.trackPublications){var t=pe(i,2);const r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(const i of this.trackPublications){var t=pe(i,2);const r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new fn,this.once($.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(H.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(H.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(H.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var 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===ho.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==ho.ACTIVE&&this.emit($.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($.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit($.ParticipantNameChanged,e)}_setAttributes(e){const t=u8(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit($.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const A=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,d)=>{var u;return l!==((u=this.permissions)===null||u===void 0?void 0:u.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit($.ParticipantPermissionsChanged,A),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit($.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=pT(e),t!==this._connectionQuality&&this.emit($.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=>Sr(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(J.Muted,()=>{this.emit($.TrackMuted,e)}),e.on(J.Unmuted,()=>{this.emit($.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case H.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case H.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function fT(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 X4({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 mT extends pC{constructor(e,t,i,r,s,a,o,A){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=At.NONE,this.e2eeStateMutex=new bn,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new fn)},this.handleReconnected=()=>{var c,l;(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.resolve)===null||l===void 0||l.call(c),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var c,l,d,u,h,p;this.reconnectFuture&&(this.reconnectFuture.promise.catch(m=>this.log.warn(m.message)),(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.reject)===null||l===void 0||l.call(c,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(d=this.signalConnectedFuture).reject)===null||u===void 0||u.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(p=(h=this.activeAgentFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=c=>{var l,d;c.participant&&this.updateInfo(c.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new fn),(d=(l=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(l)},this.handleSignalRequestResponse=c=>{const l=c.requestId,d=c.reason,u=c.message,h=this.pendingSignalRequests.get(l);switch(h&&(d!==ua.OK&&h.reject(new lv(u,d)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let p;switch(c.reason){case ua.NOT_ALLOWED:p=on.notAllowed(c.message);break;case ua.DUPLICATE_NAME:p=on.duplicateName(c.message);break;case ua.INVALID_NAME:p=on.invalidName(c.message);break;case ua.LIMIT_EXCEEDED:p=on.limitReached(c.message);break;default:p=on.unknown(c.reason,c.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(c.request.value.pubHandle,{type:"error",error:p});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(c=>fT(c)))},this.onTrackUnmuted=c=>{this.onTrackMuted(c,c.isUpstreamPaused)},this.onTrackMuted=(c,l)=>{if(l===void 0&&(l=!0),!c.sid){this.log.error("could not update mute status for unpublished track",De(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",De(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",De(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{const l=this.audioTrackPublications.get(c.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(c.sid));return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(c,l)=>{this.log.debug("track cpu constrained",De(l)),this.emit($.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>I(this,void 0,void 0,function*(){var l,d,u,h,p;if(!(!((p=this.roomOptions)===null||p===void 0)&&p.dynacast))return;const m=this.videoTrackPublications.get(c.trackSid);if(!m){this.log.warn("received subscribed quality update for unknown track",{trackSid:c.trackSid});return}if(!m.videoTrack)return;const v=yield m.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var w=!0,b=$i(v),k;k=yield b.next(),l=k.done,!l;w=!0){h=k.value,w=!1;const y=h;o8(y)&&(this.log.debug("publish ".concat(y," for ").concat(m.videoTrack.sid),De(m)),yield this.publishAdditionalCodecForTrack(m.videoTrack,y,m.options))}}catch(y){d={error:y}}finally{try{!w&&!l&&(u=b.return)&&(yield u.call(b))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=c=>{const l=this.trackPublications.get(c.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",{trackSid:c.trackSid});return}this.unpublishTrack(l.track)},this.handleTrackEnded=c=>I(this,void 0,void 0,function*(){if(c.source===H.Source.ScreenShare||c.source===H.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",De(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(Nr(c)||hr(c))try{if(ti())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:c.source===H.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),De(c)),l.onchange=()=>{l.state!=="denied"&&(c.isMuted||c.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}c.isMuted||(this.log.debug("track ended, attempting to use a different device",De(c)),Nr(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",De(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==At.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(q.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(q.Connected,this.handleReconnected).on(q.SignalConnected,this.handleSignalConnected).on(q.SignalRestarted,this.handleReconnected).on(q.SignalResumed,this.handleReconnected).on(q.Restarting,this.handleReconnecting).on(q.Resuming,this.handleReconnecting).on(q.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(q.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(q.Closing,this.handleClosing).on(q.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return I(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return I(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return I(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return I(this,arguments,void 0,function(t){var i=this;let r=t.metadata,s=t.name,a=t.attributes;return function*(){return new Rn((o,A)=>I(i,void 0,void 0,function*(){var c,l;try{let d=!1;const u=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(l=s??this.name)!==null&&l!==void 0?l:"",a),h=performance.now();for(this.pendingSignalRequests.set(u,{resolve:o,reject:p=>{A(p),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-h<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(p=>{let m=pe(p,2),v=m[0],w=m[1];return this.attributes[v]===w||w===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(u),o();return}yield In(50)}A(new lv("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error?A(d):A(new Error(String(d)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(H.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(H.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(H.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return I(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?At.GCM:At.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(i=>i.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,r){return I(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let d;if(this.pendingPublishing.has(e)){const u=yield this.waitForPendingPublicationOfSource(e);return u||this.log.info("waiting for pending publication promise timed out",{source:e}),yield u==null?void 0:u.unmute(),u}this.pendingPublishing.add(e);try{switch(e){case H.Source.Camera:d=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case H.Source.Microphone:d=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case H.Source.ScreenShare:d=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Xr(e)}}catch(u){throw d==null||d.forEach(h=>{h.stop()}),u instanceof Error&&this.emit($.MediaDevicesError,u,Kp(e)),this.pendingPublishing.delete(e),u}for(const u of d){const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===H.Source.Microphone&&Sr(u)&&h.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),u.startPreConnectBuffer())}try{const u=[];for(const p of d)this.log.info("publishing track",De(p)),u.push(this.publishTrack(p,r));const h=yield Promise.all(u);var A=pe(h,1);o=A[0]}catch(u){throw d==null||d.forEach(h=>{h.stop()}),u}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",{source:e})),o&&o.track)if(e===H.Source.ScreenShare){const d=[this.unpublishTrack(o.track)],u=this.getTrackPublication(H.Source.ScreenShareAudio);u&&u.track&&d.push(this.unpublishTrack(u.track));var c=yield Promise.all(d),l=pe(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return I(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(H.Source.Camera)||this.pendingPublishing.has(H.Source.Microphone))){this.pendingPublishing.add(H.Source.Camera),this.pendingPublishing.add(H.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(H.Source.Camera),this.pendingPublishing.delete(H.Source.Microphone)}}})}createTracks(e){return I(this,void 0,void 0,function*(){var t,i;e??(e={});const r=_3(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 Nu(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Sr(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=H.Source.Microphone,this.emit($.AudioStreamAcquired)),as(o)&&(this.cameraError=void 0,o.source=H.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return I(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Sm("getDisplayMedia not supported");e.resolution===void 0&&!C8()&&(e.resolution=km.h1080fps30.resolution);const t=c8(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new Xr("no video track found");const s=new Od(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=H.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit($.AudioStreamAcquired);const o=new Rd(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=H.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return I(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,i)=>{const r=()=>{clearTimeout(o),this.engine.off(q.Restarted,s),this.engine.off(q.Closing,a)},s=()=>{r(),t()},a=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),i(new Error("timed out waiting for engine restart"))},e);this.engine.once(q.Restarted,s),this.engine.once(q.Closing,a)})}publishOrRepublishTrack(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return function*(){var A,c,l,d;Nr(i)&&i.setAudioContext(s.audioContext),yield(A=s.reconnectFuture)===null||A===void 0?void 0:A.promise,s.republishPromise&&!a&&(yield s.republishPromise),go(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case H.Source.Microphone:b="audioinput";break;case H.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Rd(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Od(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Xr("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",De(h)),h;const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),m="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=p.forceStereo)!==null&&c!==void 0?c:m;v&&(p.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",De(i)),p.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=p.dtx)!==null&&l!==void 0||(p.dtx=!1),(d=p.red)!==null&&d!==void 0||(p.red=!1)),!x8()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),p.simulcast=!1),p.source&&(i.source=p.source);const w=new Promise((b,k)=>I(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==st.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:De(i)});let y=!1;const B=setTimeout(()=>{y=!0,i.stop(),k(new cv("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(B),y)return;const E=yield this.publish(i,p,v);b(E)}else try{const y=yield this.publish(i,p,v);b(y)}catch(y){k(y)}}catch(y){k(y)}}));s.pendingPublishPromises.set(i,w);try{return yield w}catch(b){if(!o&&b instanceof xa)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:b}),s.pendingPublishPromises.delete(i),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(i,r,a,!0);throw b}finally{s.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new fn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",De(e)),!1;const t=this.permissions,i=t.canPublish,r=t.canPublishSources;return i&&(r.length===0||r.map(s=>h8(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",De(e)),!1)}publish(e,t,i){return I(this,void 0,void 0,function*(){var r,s,a,o,A,c,l,d,u,h;if(!this.hasPermissionsToPublish(e))throw new cv("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(D=>go(e)&&D.source===e.source)&&e.source!==H.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),De(e)),t.stopMicTrackOnMute&&Sr(e)&&(e.stopOnMute=!0),e.source===H.Source.ScreenShare&&Qa()&&(t.simulcast=!1),t.videoCodec==="av1"&&!v8()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!y8()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Yp),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(D=>t.videoCodec===ZA(D.mime))||(t.videoCodec=ZA(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(J.Muted,this.onTrackMuted),e.on(J.Unmuted,this.onTrackUnmuted),e.on(J.Ended,this.handleTrackEnded),e.on(J.UpstreamPaused,this.onTrackUpstreamPaused),e.on(J.UpstreamResumed,this.onTrackUpstreamResumed),e.on(J.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],w=!(!((r=t.dtx)!==null&&r!==void 0)||r),b=e.getSourceTrackSettings();b.autoGainControl&&v.push(hn.TF_AUTO_GAIN_CONTROL),b.echoCancellation&&v.push(hn.TF_ECHO_CANCELLATION),b.noiseSuppression&&v.push(hn.TF_NOISE_SUPPRESSION),b.channelCount&&b.channelCount>1&&v.push(hn.TF_STEREO),w&&v.push(hn.TF_NO_DTX),Nr(e)&&e.hasPreConnectBuffer&&v.push(hn.TF_PRECONNECT_BUFFER);const k=this.normalizeRequestedFrameMetadataOptions(e,t),y=new yc({cid:e.mediaStreamTrack.id,name:t.name,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),disableDtx:w,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:v,packetTrailerFeatures:k});let B;if(e.kind===H.Kind.Video){let D;try{D=yield e.waitForDimensions()}catch{const N=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:wc.h720.resolution;D={width:N.width,height:N.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},De(e)),{dims:D}))}y.width=D.width,y.height=D.height,hr(e)&&(er(m)&&(e.source===H.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",De(e)))),t.scalabilityMode=(A=t.scalabilityMode)!==null&&A!==void 0?A:"L3T3_KEY"),y.simulcastCodecs=[new Ip({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Yp}),t.backupCodec&&m!==t.backupCodec.codec&&y.encryption===At.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new Ip({codec:t.backupCodec.codec,cid:""})))),B=_d(e.source===H.Source.ScreenShare,y.width,y.height,t),y.layers=Dv(y.width,y.height,B,er(t.videoCodec))}else e.kind===H.Kind.Audio&&(B=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&d!==void 0?d:"high",networkPriority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Mt("cannot publish track when not connected");const E=()=>I(this,void 0,void 0,function*(){var D,O,N;if(!this.engine.pcManager)throw new Mt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,B),hr(e)&&(e.publishOptions=t),this.emit($.LocalSenderCreated,e.sender,e),hr(e)&&((D=t.degradationPreference)!==null&&D!==void 0||(t.degradationPreference=DE(e)),e.setDegradationPreference(t.degradationPreference)),B)if(Qa()&&e.kind===H.Kind.Audio){let j;for(const V of this.engine.pcManager.publisher.getTransceivers())if(V.sender===e.sender){j=V;break}j&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:j,codec:"opus",maxbr:!((O=B[0])===null||O===void 0)&&O.maxBitrate?B[0].maxBitrate/1e3:0})}else e.codec&&er(e.codec)&&(!((N=B[0])===null||N===void 0)&&N.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:B[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const F=new Promise((D,O)=>I(this,void 0,void 0,function*(){var N;try{T=yield this.engine.addTrack(y),D(T)}catch(j){if(e.sender&&(!((N=this.engine.pcManager)===null||N===void 0)&&N.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(V){this.log.error(V)}yield this.engine.negotiate().catch(V=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},De(e)),{error:V}))})}O(j)}}));if(this.enabledPublishVideoCodecs.length>0&&k.length===0)T=(yield Promise.all([F,E()]))[0];else{T=yield F;let D;if(T.codecs.forEach(O=>{D===void 0&&(D=O.mimeType)}),D&&e.kind===H.Kind.Video){const O=ZA(D);O!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},De(e)),{codec:O})),t.videoCodec=O,B=_d(e.source===H.Source.ScreenShare,y.width,y.height,t))}yield E()}const L=new Zp(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(L.on(J.CpuConstrained,D=>this.onTrackCpuConstrained(D,L)),L.options=t,e.sid=T.sid,hr(e)&&(e.publishOptions=t,y.width&&y.height&&(e.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:B,trackInfo:T}),hr(e)?e.startMonitor(this.engine.client):Nr(e)&&e.startMonitor(),this.addTrackPublication(L),this.emit($.LocalTrackPublished,L),Nr(e)&&T.audioFeatures.includes(hn.TF_PRECONNECT_BUFFER)){const D=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on($.LocalTrackSubscribed,N=>{if(N.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",De(e)),e.stopPreConnectBuffer()}}),D&&new Promise((j,V)=>I(this,void 0,void 0,function*(){var te,xe,ae,Ie,Ee,Pe;try{this.log.debug("waiting for agent",De(e));const ke=setTimeout(()=>{V(new Error("agent not active within 10 seconds"))},1e4),ze=yield this.waitUntilActiveAgentPresent();clearTimeout(ke),this.log.debug("sending preconnect buffer",De(e));const ht=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ze.identity],attributes:{trackId:L.trackSid,sampleRate:String((Ee=b.sampleRate)!==null&&Ee!==void 0?Ee:"48000"),channels:String((Pe=b.channelCount)!==null&&Pe!==void 0?Pe:"1")}});try{for(var ne=!0,we=$i(D),Le;Le=yield we.next(),te=Le.done,!te;ne=!0){Ie=Le.value,ne=!1;const Wt=Ie;yield ht.write(Wt)}}catch(Wt){xe={error:Wt}}finally{try{!ne&&!te&&(ae=we.return)&&(yield ae.call(we))}finally{if(xe)throw xe.error}}yield ht.close(),j()}catch(ke){V(ke)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",De(e))}).catch(j=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},De(e)),{error:j}))})}return L})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||xc((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const r=(i=t.frameMetadata)!==null&&i!==void 0?i:t.packetTrailer;if(e.kind!==H.Kind.Video||!Dd(r))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),De(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const s=W8(r),a=j8(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return I(this,void 0,void 0,function*(){var r;if(this.encryptionType!==At.NONE)return;let s;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(s=p)}),!s)throw new Xr("track is not published");if(!hr(e))throw new Xr("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=Z3(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",De(e));return}const A=e.addSimulcastTrack(t,o);if(!A)return;const c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new yc({cid:A.mediaStreamTrack.id,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:A.mediaStreamTrack.id}]});if(l.layers=Dv(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Mt("cannot publish track when not connected");const d=()=>I(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,A,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:h})})}unpublishTrack(e,t){return I(this,void 0,void 0,function*(){var i,r;if(go(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",De(e)),yield l)}const s=this.getPublicationForTrack(e),a=s?De(s):void 0;if(this.log.info("unpublishing track",a),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=s.track,e.off(J.Muted,this.onTrackMuted),e.off(J.Unmuted,this.onTrackUnmuted),e.off(J.Ended,this.handleTrackEnded),e.off(J.UpstreamPaused,this.onTrackUpstreamPaused),e.off(J.UpstreamResumed,this.onTrackUpstreamResumed),e.off(J.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const A=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ut.FAILED&&A)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===A&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(A)}catch(l){this.log.warn(l),o=!0}if(hr(e)){for(const l of e.simulcastCodecs){var c=pe(l,2);const d=c[1];if(d.sender){try{o=this.engine.removeTrack(d.sender)}catch(u){this.log.warn(u),o=!0}d.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case H.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case H.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit($.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return I(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Rn((s,a)=>I(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(A=>{A.track&&(t&&(A.options=Object.assign(Object.assign({},A.options),t)),o.push(A))}),yield Promise.all(o.map(A=>I(this,void 0,void 0,function*(){const c=A.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==H.Source.ScreenShare&&c.source!==H.Source.ScreenShareAudio&&(Nr(c)||hr(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",{track:A.trackSid}),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,A.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?Me.RELIABLE:Me.LOSSY,a=r.reliable?Fs.RELIABLE:Fs.LOSSY,o=r.destinationIdentities,A=r.topic;let c=new pm({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:A});const l=new En({kind:a,value:{case:"user",value:c}});yield i.engine.sendDataPacket(l,s)}()})}publishDtmf(e,t){return I(this,void 0,void 0,function*(){const i=new En({kind:Fs.RELIABLE,value:{case:"sipDtmf",value:new Q4({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Me.RELIABLE)})}sendChatMessage(e,t){return I(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new En({value:{case:"chatMessage",value:new Id(Object.assign(Object.assign({},i),{timestamp:bt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Me.RELIABLE),this.emit($.ChatMessage,i),i})}editChatMessage(e,t){return I(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new En({value:{case:"chatMessage",value:new Id(Object.assign(Object.assign({},i),{timestamp:bt.parse(i.timestamp),editTimestamp:bt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Me.RELIABLE),this.emit($.ChatMessage,i),i})}sendText(e,t){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let i=pe(t,2);return i[0],i[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},De(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,r,s;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):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new fn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Nr(r)||hr(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return I(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>pe(s,1)[0].source===e);if(r)return r[1];yield In(20)}})}publishDataTrack(e){return I(this,void 0,void 0,function*(){const t=new _u(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class e2 extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class gT extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,r;super.set(e,t);const s=(i=this.pending)===null||i===void 0?void 0:i.get(e);if(s){for(const a of s)a.isResolved||(r=a.resolve)===null||r===void 0||r.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return I(this,void 0,void 0,function*(){const i=this.get(e);if(typeof i<"u")return i;if(t!=null&&t.aborted)throw new e2("The operation was aborted.",t.reason);const r=new fn(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){const a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new e2("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}}class vT extends qr{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(J.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Mu({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new D4({participantSid:"",trackSids:[this.trackSid]})]});this.emit(J.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?qr.SubscriptionStatus.Unsubscribed:super.isSubscribed?qr.SubscriptionStatus.Subscribed:qr.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?qr.PermissionStatus.Allowed:qr.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||(n0(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&n0(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:mi.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(J.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(J.VisibilityChanged,this.handleVisibilityChange),r.off(J.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(J.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(J.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(J.VisibilityChanged,this.handleVisibilityChange),e.on(J.Ended,this.handleEnded),this.emit(J.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(J.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?J.Muted:J.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(J.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(J.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 n0(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new W4({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===H.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)uv(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=p8(this.trackInfo,this.requestedMaxQuality);i&&uv(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:mi.HIGH})),e.quality=mi.HIGH)}this.emit(J.UpdateSettings,e)}}class Hd extends pC{static fromParticipantInfo(e,t,i,r){return new Hd(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(s=>{const a=Ld.from(s);return new cC(a,r,{publisherIdentity:t.identity})}),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let A=arguments.length>7&&arguments[7]!==void 0?arguments[7]:vc.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:L3;super(t,i||"",r,s,a,o,A),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new gT(c.map(d=>[d.info.name,d])),this.volumeMap=new Map,this.clientProtocol=l}addTrackPublication(e){super.addTrackPublication(e),e.on(J.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),De(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(J.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(J.SubscriptionPermissionChanged,t=>{this.emit($.TrackSubscriptionPermissionChanged,e,t)}),e.on(J.SubscriptionStatusChanged,t=>{this.emit($.TrackSubscriptionStatusChanged,e,t)}),e.on(J.Subscribed,t=>{this.emit($.TrackSubscribed,t,e)}),e.on(J.Unsubscribed,t=>{this.emit($.TrackUnsubscribed,t,e)}),e.on(J.SubscriptionFailed,t=>{this.emit($.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]:H.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]:H.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(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($.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),De(o))),this.emit($.TrackSubscriptionFailed,t);return}const A=e.kind==="video";let c;return A?c=new Fm(e,t,r,s):c=new dT(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Wp(c)&&Sr(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const A=H.kindFromProto(r.type);if(!A)return;o=new vT(A,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));c&&o.source!==H.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:De(c),newTrack:De(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),De(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit($.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case H.Kind.Audio:this.audioTrackPublications.delete(e);break;case H.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit($.TrackUnpublished,i)}setAudioOutput(e){return I(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Sr(i.track)&&Wp(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=pe(i,2);const r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Ye;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Ye||(Ye={}));const yT=4*1e3;class No extends oi.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,r,s,a,o,A;if(super(),t=this,this.state=Ye.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new bn,this.isVideoPlaybackBlocked=!1,this.log=Te,this.bufferedEvents=[],this.isResuming=!1,this.connect=(c,l,d)=>I(this,void 0,void 0,function*(){var u;if(!w8())throw ar()?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 h=yield this.disconnectLock.lock();if(this.state===Ye.Connected)return this.log.info("already connected to room ".concat(this.name)),h(),Promise.resolve();if(this.connectFuture)return h(),this.connectFuture.promise;this.setAndEmitConnectionState(Ye.Connecting),((u=this.regionUrlProvider)===null||u===void 0?void 0:u.getServerUrl().toString())!==q3(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ro(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ve(c,l):this.regionUrlProvider.updateToken(l),this.regionUrlProvider.fetchRegionSettings().then(v=>{var w;(w=this.regionUrlProvider)===null||w===void 0||w.setServerReportedRegions(v)}).catch(v=>{this.log.warn("could not fetch region settings",{error:v})}));const p=(v,w,b)=>I(this,void 0,void 0,function*(){var k,y;this.abortController&&this.abortController.abort();const B=new AbortController;this.abortController=B,h==null||h();try{if(yield vo.getInstance().getBackOffPromise(c),B.signal.aborted)throw fe.cancelled("Connection attempt aborted");yield this.attemptConnection(b??c,l,d,B),this.abortController=void 0,v()}catch(E){if(this.regionUrlProvider&&E instanceof fe&&E.reason!==at.Cancelled&&E.reason!==at.NotAllowed){let T=null;try{this.log.debug("Fetching next region"),T=yield this.regionUrlProvider.getNextBestRegionUrl((k=this.abortController)===null||k===void 0?void 0:k.signal)}catch(F){if(F instanceof fe&&(F.status===401||F.reason===at.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),w(F);return}}[at.InternalError,at.ServerUnreachable,at.Timeout].includes(E.reason)&&(this.log.debug("Adding failed connection attempt to back off"),vo.getInstance().addFailedConnectionAttempt(c)),T&&!(!((y=this.abortController)===null||y===void 0)&&y.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(E.message,". Retrying with another region: ").concat(T)),this.recreateEngine(!0),yield p(v,w,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,vv(E)),w(E))}else{let T=ir.UNKNOWN_REASON;E instanceof fe&&(T=vv(E)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),w(E)}}}),m=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new fn((v,w)=>{p(v,w,m)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,d,u,h,p)=>I(this,void 0,void 0,function*(){var m;const v=yield d.join(c,l,{autoSubscribe:u.autoSubscribe,adaptiveStream:typeof h.adaptiveStream=="object"?!0:h.adaptiveStream,clientInfoCapabilities:xc((m=h.frameMetadata)!==null&&m!==void 0?m:h.packetTrailer)||this.e2eeManager?[N4.CAP_PACKET_TRAILER]:void 0,maxRetries:u.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:u.websocketTimeout},p.signal,!h.singlePeerConnection),w=v.joinResponse,b=v.serverInfo;if(this.serverInfo=b,!b.version)throw new n8("unknown server version");return b.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),h.dynacast=!1),w}),this.applyJoinResponse=c=>{const l=c.participant;if(this.localParticipant.sid=l.sid,this.localParticipant.identity=l.identity,this.localParticipant.setEnabledPublishCodecs(c.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(c.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",{error:d})}this.handleParticipantUpdates([l,...c.otherParticipants]),c.room&&this.handleRoomUpdate(c.room)},this.attemptConnection=(c,l,d,u)=>I(this,void 0,void 0,function*(){var h,p;this.state===Ye.Reconnecting||this.isResuming||!((h=this.engine)===null||h===void 0)&&h.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((p=this.regionUrlProvider)===null||p===void 0)&&p.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},_m),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const m=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,u);this.applyJoinResponse(m),this.setupLocalParticipantEvents(),this.emit(G.SignalConnected)}catch(m){yield this.engine.close(),this.recreateEngine();const v=u.signal.aborted?fe.cancelled("Signal connection aborted"):fe.serverUnreachable("could not establish signal connection");throw m instanceof Error&&(v.message="".concat(v.message,": ").concat(m.message)),m instanceof fe&&(v.reason=m.reason,v.status=m.status),this.log.debug("error trying to establish signal connection",{error:m}),v}if(u.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),fe.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,u)}catch(m){throw yield this.engine.close(),this.recreateEngine(),m}ti()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ti()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Ye.Connected),this.emit(G.Connected),vo.getInstance().resetFailedConnectionAttempts(c),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var c=arguments.length,l=new Array(c),d=0;d<c;d++)l[d]=arguments[d];return I(t,[...l],void 0,function(){var u=this;let h=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var p,m,v;const w=yield u.disconnectLock.lock();try{if(u.state===Ye.Disconnected){u.log.debug("already disconnected");return}if(u.log.info("disconnect from room"),u.state===Ye.Connecting||u.state===Ye.Reconnecting||u.isResuming){const b="Abort connection attempt due to user initiated disconnect";u.log.warn(b),(p=u.abortController)===null||p===void 0||p.abort(b),(v=(m=u.connectFuture)===null||m===void 0?void 0:m.reject)===null||v===void 0||v.call(m,fe.cancelled("Client initiated disconnect")),u.connectFuture=void 0}u.engine&&(u.engine.client.isDisconnected||(yield u.engine.client.sendLeave()),yield u.engine.close()),u.handleDisconnect(h,ir.CLIENT_INITIATED),u.engine=void 0}finally{w()}}()})},this.onPageLeave=()=>I(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>I(this,void 0,void 0,function*(){const c=[],l=On();if(l&&l.os==="iOS"){const d="livekit-dummy-audio-el";let u=document.getElementById(d);if(!u){u=document.createElement("audio"),u.id=d,u.autoplay=!0,u.hidden=!0;const h=t0();h.enabled=!0;const p=new MediaStream([h]);u.srcObject=p,document.addEventListener("visibilitychange",()=>{u&&(u.srcObject=document.hidden?null:p,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(u),this.once(G.Disconnected,()=>{u==null||u.remove(),u=null})}c.push(u)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(u=>{u.track&&u.track.attachedElements.forEach(h=>{c.push(h)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>I(this,void 0,void 0,function*(){const c=[];for(const l of this.remoteParticipants.values())l.videoTrackPublications.forEach(d=>{var u;(u=d.track)===null||u===void 0||u.attachedElements.forEach(h=>{c.includes(h)||c.push(h)})});yield Promise.all(c.map(l=>l.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(l=>{l.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(Ye.Reconnecting)&&this.emit(G.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>I(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(c.serverRegion),{region:c.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(c);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(l){this.log.error("error trying to re-publish tracks after reconnection",{error:l})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:c.serverRegion})}catch{return}this.setAndEmitConnectionState(Ye.Connected),this.emit(G.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(const u of c){if(u.identity===this.localParticipant.identity){this.localParticipant.updateInfo(u);continue}u.identity===""&&(u.identity=(l=this.sidToIdentity.get(u.sid))!==null&&l!==void 0?l:"");let h=this.remoteParticipants.get(u.identity);u.state===ho.DISCONNECTED?this.handleParticipantDisconnected(u.identity,h):this.getOrCreateParticipant(u.identity,u)}const d=new Map(c.filter(u=>u.identity!==this.localParticipant.identity).map(u=>[u.identity,u.dataTracks.map(h=>Ld.from(h))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(d)},this.handleActiveSpeakersUpdate=c=>{const l=[],d={};c.forEach(u=>{if(d[u.sid]=!0,u.sid===this.localParticipant.sid)this.localParticipant.audioLevel=u.level,this.localParticipant.setIsSpeaking(!0),l.push(this.localParticipant);else{const h=this.getRemoteParticipantBySid(u.sid);h&&(h.audioLevel=u.level,h.setIsSpeaking(!0),l.push(h))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(u=>{d[u.sid]||(u.audioLevel=0,u.setIsSpeaking(!1))}),this.activeSpeakers=l,this.emitWhenConnected(G.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{const l=new Map;this.activeSpeakers.forEach(u=>{const h=this.remoteParticipants.get(u.identity);h&&h.sid!==u.sid||l.set(u.sid,u)}),c.forEach(u=>{let h=this.getRemoteParticipantBySid(u.sid);u.sid===this.localParticipant.sid&&(h=this.localParticipant),h&&(h.audioLevel=u.level,h.setIsSpeaking(u.active),u.active?l.set(u.sid,h):l.delete(u.sid))});const d=Array.from(l.values());d.sort((u,h)=>h.audioLevel-u.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(G.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{const d=this.getRemoteParticipantBySid(l.participantSid);if(!d)return;const u=d.getTrackPublicationBySid(l.trackSid);if(!u||!u.track)return;const h=H.streamStateFromProto(l.state);u.track.setStreamState(h),h!==u.track.streamState&&(d.emit($.TrackStreamStateChanged,u,u.track.streamState),this.emitWhenConnected(G.TrackStreamStateChanged,u,u.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);d&&d.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{const l=Array.from(this.remoteParticipants.values()).find(u=>u.trackPublications.has(c.trackSid));if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);d&&d.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{const d=this.remoteParticipants.get(c.participantIdentity);if(c.value.case==="user")this.handleUserPacket(d,c.value.value,c.kind,l);else if(c.value.case==="transcription")this.handleTranscription(d,c.value.value);else if(c.value.case==="sipDtmf")this.handleSipDtmf(d,c.value.value);else if(c.value.case==="chatMessage")this.handleChatMessage(d,c.value.value);else if(c.value.case==="metrics")this.handleMetrics(c.value.value,d);else if(c.value.case==="streamHeader"||c.value.case==="streamChunk"||c.value.case==="streamTrailer")this.handleDataStream(c,l);else if(c.value.case==="rpcRequest"){const u=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,u)}else if(c.value.case==="rpcResponse"){const u=c.value.value;switch(u.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(u.requestId,u.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(u.requestId,tt.fromProto(u.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(u.value.case),this.logContext);break}}else c.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(c.value.value.requestId)},this.handleUserPacket=(c,l,d,u)=>{this.emit(G.DataReceived,l.payload,c,d,l.topic,u),c==null||c.emit($.DataReceived,l.payload,d,u)},this.handleSipDtmf=(c,l)=>{this.emit(G.SipDTMFReceived,l,c),c==null||c.emit($.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{const d=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),u=d==null?void 0:d.trackPublications.get(l.trackId),h=M8(l,this.transcriptionReceivedTimes);u==null||u.emit(J.TranscriptionReceived,h),d==null||d.emit($.TranscriptionReceived,h,u),this.emit(G.TranscriptionReceived,h,d,u)},this.handleChatMessage=(c,l)=>{const d=U8(l);this.emit(G.ChatMessage,d,c)},this.handleMetrics=(c,l)=>{this.emit(G.MetricsReceived,c,l)},this.handleDataStream=(c,l)=>{this.incomingDataStreamManager.handleDataStreamPacket(c,l)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(G.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(G.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(G.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(G.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>I(this,void 0,void 0,function*(){var c;((c=On())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(G.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{const l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(G.RoomMetadataChanged,c.metadata),(l==null?void 0:l.activeRecording)!==c.activeRecording&&this.emitWhenConnected(G.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}const d=this.getRemoteParticipantBySid(l.participantSid);d&&d.setConnectionQuality(l.quality)})},this.getRemoteParticipantClientProtocol=c=>{var l,d;return(d=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.clientProtocol)!==null&&d!==void 0?d:L3},this.onLocalParticipantMetadataChanged=c=>{this.emit(G.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(G.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(G.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(G.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(G.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c==null?void 0:c.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>I(this,void 0,void 0,function*(){var l,d,u,h,p,m;(l=c.track)===null||l===void 0||l.on(J.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=c.track)===null||d===void 0||d.on(J.Restarted,this.onLocalTrackRestarted),(p=(h=(u=c.track)===null||u===void 0?void 0:u.getProcessor())===null||h===void 0?void 0:h.onPublish)===null||p===void 0||p.call(h,this),this.emit(G.LocalTrackPublished,c,this.localParticipant),Nr(c.track)&&(yield c.track.checkForSilence())&&this.emit(G.LocalAudioSilenceDetected,c);const v=yield(m=c.track)===null||m===void 0?void 0:m.getDeviceId(!1),w=Kp(c.source);w&&v&&v!==this.localParticipant.activeDeviceMap.get(w)&&(this.localParticipant.activeDeviceMap.set(w,v),this.emit(G.ActiveDeviceChanged,w,v))}),this.onLocalTrackUnpublished=c=>{var l,d;(l=c.track)===null||l===void 0||l.off(J.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=c.track)===null||d===void 0||d.off(J.Restarted,this.onLocalTrackRestarted),this.emit(G.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>I(this,void 0,void 0,function*(){const l=yield c.getDeviceId(!1),d=Kp(c.source);d&&l&&l!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(l," active")),this.localParticipant.activeDeviceMap.set(d,l),this.emit(G.ActiveDeviceChanged,d,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(G.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(G.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(G.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(G.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},yE),e),this.log=si((i=this.options.loggerName)!==null&&i!==void 0?i:mn.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Y3),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},J3),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},vE),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new jE,this.outgoingDataStreamManager=new XE(this.engine,this.log),this.incomingDataTrackManager=new aT({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",c=>{this.engine.client.sendUpdateDataSubscription(c.sid,c.subscribe)}).on("trackPublished",c=>{var l;c.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(G.DataTrackPublished,c.track),(l=this.remoteParticipants.get(c.track.publisherIdentity))===null||l===void 0||l.addRemoteDataTrack(c.track))}).on("trackUnpublished",c=>{var l;c.publisherIdentity!==this.localParticipant.identity&&(this.emit(G.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new Hm({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",c=>{this.engine.client.sendPublishDataTrackRequest(c.handle,c.name,c.usesE2ee)}).on("sfuUnpublishRequest",c=>{this.engine.client.sendUnPublishDataTrackRequest(c.handle)}).on("trackPublished",c=>{this.emit(G.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(G.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,d=c.bytes;this.engine.sendLossyBytes(d,Me.DATA_TRACK_LOSSY,"wait").finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new cT(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var c,l;return(l=(c=this.engine.latestJoinResponse)===null||c===void 0?void 0:c.serverInfo)===null||l===void 0?void 0:l.version}),this.rpcClientManager.on("sendDataPacket",c=>{let l=c.packet;var d;(d=this.engine)===null||d===void 0||d.sendDataPacket(l,Me.RELIABLE)}),this.rpcServerManager=new lT(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",c=>{let l=c.packet;var d;(d=this.engine)===null||d===void 0||d.sendDataPacket(l,Me.RELIABLE)}),this.disconnectLock=new bn,this.localParticipant=new mT("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.outgoingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Sa(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Sa(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",Sa(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),ti()){const c=new AbortController;let l;if(No.cleanupRegistry){const d=new WeakRef(this);l=()=>{const u=d.deref();u&&u.handleDeviceChange()},No.cleanupRegistry.register(this,()=>{c.abort()})}else l=this.handleDeviceChange;(A=(o=navigator.mediaDevices)===null||o===void 0?void 0:o.addEventListener)===null||A===void 0||A.call(o,"devicechange",l,{signal:c.signal})}}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){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return I(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield 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")}finally{t()}})}setupE2EE(){var e,t;const i=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new J8(r,i),this.e2eeManager.on(Es.ParticipantEncryptionStatusChanged,(s,a)=>{Q8(a)&&(this.isE2EEEnabled=s),this.emit(G.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(Es.EncryptionError,(s,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(G.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new $8(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(i=this.localParticipant)===null||i===void 0?void 0:i.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===Ye.Disconnected?Rn.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Rn.resolve(this.roomInfo.sid):new Rn((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(q.RoomUpdate,i),e(r.sid))};this.engine.on(q.RoomUpdate,i),this.once(G.Disconnected,()=>{this.engine.off(q.RoomUpdate,i),t(new Mt("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.isNewlyCreated||!this.engine.isClosed)||(this.engine=new VE(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(q.ParticipantUpdate,this.handleParticipantUpdates).on(q.RoomUpdate,this.handleRoomUpdate).on(q.SpeakersChanged,this.handleSpeakersChanged).on(q.StreamStateChanged,this.handleStreamStateUpdate).on(q.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(q.SubscriptionError,this.handleSubscriptionError).on(q.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(q.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(q.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(q.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(q.DataPacketReceived,this.handleDataPacket).on(q.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(Ye.SignalReconnecting)&&this.emit(G.SignalReconnecting)}).on(q.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Ye.Connected)&&this.emit(G.Reconnected)}).on(q.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Ye.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(q.Restarting,this.handleRestarting).on(q.Restarted,this.handleRestarted).on(q.SignalRestarted,this.handleSignalRestarted).on(q.Offline,()=>{this.setAndEmitConnectionState(Ye.Reconnecting)&&this.emit(G.Reconnecting)}).on(q.DCBufferStatusChanged,(e,t)=>{this.emit(G.DCBufferStatusChanged,e,t)}).on(q.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(q.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(G.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(q.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==At.NONE}})}).on(q.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(q.DataTrackSubscriberHandles,e=>{const t=new Map(Object.entries(e.subHandles).map(i=>{let r=pe(i,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(q.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(q.Joined,e=>{const t=new Map(e.otherParticipants.map(i=>[i.identity,i.dataTracks.map(r=>Ld.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(q.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(q.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Xp})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>I(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pn.getInstance().getDevices(e,t)}prepareConnection(e,t){return I(this,void 0,void 0,function*(){if(this.state===Ye.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(Ro(new URL(e))&&t){this.regionUrlProvider=new Ve(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Ye.Disconnected&&(this.regionUrl=i,yield fetch(Cc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Cc(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",{error:i})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return I(this,void 0,void 0,function*(){let i=()=>I(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new gr({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new gr({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new gr({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new gr({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=()=>I(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new gr({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>I(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new gr({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new gr({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>I(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Uu({reason:ir.CLIENT_INITIATED,action:po.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new gr({scenario:{case:"subscriberBandwidth",value:ca(t)}});break;case"leave-full-reconnect":r=new gr({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,A,c,l,d,u,h;let p=!0,m=!1;const v=a?{exact:r}:r;if(i==="audioinput"){m=s.localParticipant.audioTrackPublications.size===0;const w=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=v;const b=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===H.Source.Microphone);try{p=(yield Promise.all(b.map(y=>{var B;return(B=y.audioTrack)===null||B===void 0?void 0:B.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=w,y}const k=b.some(y=>{var B,E;return(E=(B=y.track)===null||B===void 0?void 0:B.isMuted)!==null&&E!==void 0?E:!1});p&&k&&(m=!0)}else if(i==="videoinput"){m=s.localParticipant.videoTrackPublications.size===0;const w=(A=s.getActiveDevice(i))!==null&&A!==void 0?A:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=v;const b=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===H.Source.Camera);try{p=(yield Promise.all(b.map(y=>{var B;return(B=y.videoTrack)===null||B===void 0?void 0:B.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=w,y}const k=b.some(y=>{var B,E;return(E=(B=y.track)===null||B===void 0?void 0:B.isMuted)!==null&&E!==void 0?E:!1});p&&k&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!zp()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(c=yield pn.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(l=(h=s.options).audioOutput)!==null&&l!==void 0||(h.audioOutput={});const w=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((u=s.audioContext)===null||u===void 0||u.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(b=>b.setAudioOutput({deviceId:r})))}catch(b){throw s.options.audioOutput.deviceId=w,b}}return m&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(G.ActiveDeviceChanged,i,r)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on($.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on($.ParticipantNameChanged,this.onLocalParticipantNameChanged).on($.AttributesChanged,this.onLocalAttributesChanged).on($.TrackMuted,this.onLocalTrackMuted).on($.TrackUnmuted,this.onLocalTrackUnmuted).on($.LocalTrackPublished,this.onLocalTrackPublished).on($.LocalTrackUnpublished,this.onLocalTrackUnpublished).on($.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on($.MediaDevicesError,this.onMediaDevicesError).on($.AudioStreamAcquired,this.startAudio).on($.ChatMessage,this.onLocalChatMessageSent).on($.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t==null||t.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===Ye.Connecting||this.state===Ye.Reconnecting){const d=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(h=>h.id)}),this.onTrackAdded(e,t,i),u()},u=()=>{this.off(G.Reconnected,d),this.off(G.Connected,d),this.off(G.Disconnected,u)};this.once(G.Reconnected,d),this.once(G.Connected,d),this.once(G.Disconnected,u);return}if(this.state===Ye.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const r=g8(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const A=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!A){s.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));return}if(!o.startsWith("TR")){const d=this.engine.getTrackIdForReceiver(i);if(!d){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s));return}o=d}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(s,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:s,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const l=A.addSubscribedMediaTrack(e,o,t,i,c);l!=null&&l.isEncrypted&&!this.e2eeManager&&this.emit(G.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(A.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find(A=>A.trackSid===e),i=t();if(i){this.emitLocalTrackSubscribed(i);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});const r=1e4;let s;const a=A=>{A.trackSid===e&&(o(),this.emitLocalTrackSubscribed(A))},o=()=>{clearTimeout(s),this.localParticipant.off($.LocalTrackPublished,a),this.off(G.Disconnected,o)};this.localParticipant.on($.LocalTrackPublished,a),this.once(G.Disconnected,o),s=setTimeout(()=>{o();const A=t();A?this.emitLocalTrackSubscribed(A):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},r)}emitLocalTrackSubscribed(e){this.localParticipant.emit($.LocalTrackSubscribed,e),this.emitWhenConnected(G.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==Ye.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(a=>{s.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var a,o,A;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((a=s.track)===null||a===void 0||a.detach(),(o=s.track)===null||o===void 0||o.stop()):(A=s.track)===null||A===void 0||A.stopMonitor()}),this.localParticipant.off($.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off($.ParticipantNameChanged,this.onLocalParticipantNameChanged).off($.AttributesChanged,this.onLocalAttributesChanged).off($.TrackMuted,this.onLocalTrackMuted).off($.TrackUnmuted,this.onLocalTrackUnmuted).off($.LocalTrackPublished,this.onLocalTrackPublished).off($.LocalTrackUnpublished,this.onLocalTrackUnpublished).off($.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off($.MediaDevicesError,this.onMediaDevicesError).off($.AudioStreamAcquired,this.startAudio).off($.ChatMessage,this.onLocalChatMessageSent).off($.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),ti()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||r===void 0||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Ye.Disconnected),this.emit(G.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(G.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return I(this,void 0,void 0,function*(){var e,t,i;const r=pn.getInstance().previousDevices,s=yield pn.getInstance().getDevices(void 0,!1),a=On();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let A of s){const c=r.find(l=>l.deviceId===A.deviceId);c&&c.label!==""&&c.kind===A.kind&&c.label!==A.label&&this.getActiveDevice(A.kind)==="default"&&this.emit(G.ActiveDeviceChanged,A.kind,A.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let A of o){const c=A8(A),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const d=s.filter(h=>h.kind===A),u=this.getActiveDevice(A);if(u===((t=r.filter(h=>h.kind===A)[0])===null||t===void 0?void 0:t.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==u){yield this.switchActiveDevice(A,d[0].deviceId);continue}A==="audioinput"&&!bc()||A==="videoinput"||d.length>0&&!d.find(h=>h.deviceId===this.getActiveDevice(A))&&(A!=="audiooutput"||!bc())&&(yield this.switchActiveDevice(A,d[0].deviceId))}})}acquireAudioContext(){return I(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=N3())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),In(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(G.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=Hd.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new Hd(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(G.ParticipantConnected,i),i.on($.TrackPublished,r=>{this.emitWhenConnected(G.TrackPublished,r,i)}).on($.TrackSubscribed,(r,s)=>{r.kind===H.Kind.Audio?(r.on(J.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(J.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===H.Kind.Video&&(r.on(J.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(J.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(G.TrackSubscribed,r,s,i)}).on($.TrackUnpublished,r=>{this.emit(G.TrackUnpublished,r,i)}).on($.TrackUnsubscribed,(r,s)=>{this.emit(G.TrackUnsubscribed,r,s,i)}).on($.TrackMuted,r=>{this.emitWhenConnected(G.TrackMuted,r,i)}).on($.TrackUnmuted,r=>{this.emitWhenConnected(G.TrackUnmuted,r,i)}).on($.ParticipantMetadataChanged,r=>{this.emitWhenConnected(G.ParticipantMetadataChanged,r,i)}).on($.ParticipantNameChanged,r=>{this.emitWhenConnected(G.ParticipantNameChanged,r,i)}).on($.AttributesChanged,r=>{this.emitWhenConnected(G.ParticipantAttributesChanged,r,i)}).on($.ConnectionQualityChanged,r=>{this.emitWhenConnected(G.ConnectionQualityChanged,r,i)}).on($.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(G.ParticipantPermissionsChanged,r,i)}).on($.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(G.TrackSubscriptionStatusChanged,r,s,i)}).on($.TrackSubscriptionFailed,(r,s)=>{this.emit(G.TrackSubscriptionFailed,r,i,s)}).on($.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(G.TrackSubscriptionPermissionChanged,r,s,i)}).on($.Active,()=>{this.emitWhenConnected(G.ParticipantActive,i),i.kind===vc.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&F8(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(dC,(e,t)=>I(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return function*(){var o;const A=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(i,a,A)}()})),this.incomingDataStreamManager.registerTextStreamHandler(uC,(e,t)=>I(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return function*(){var o;const A=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(i,a,A)}()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Zt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ir.STATE_MISMATCH))):e=0},yT)}clearConnectionReconcile(){this.connectionReconcileInterval&&Zt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===Ye.Connected),this.emit(G.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=pe(e,2),i=t[0],r=t[1];this.emit(i,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===Ye.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Ye.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return I(this,void 0,void 0,function*(){var t,i,r,s;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 Su({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:bt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Fa({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(G.SignalConnected),this.emit(G.Connected),this.setAndEmitConnectionState(Ye.Connected),a.video){const A=new Zp(H.Kind.Video,new ao({source:Yt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO,name:"video-dummy"}),new Od(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:gv(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(A),this.localParticipant.emit($.LocalTrackPublished,A)}if(a.audio){const A=new Zp(H.Kind.Audio,new ao({source:Yt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO}),new Rd(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:t0(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(A),this.localParticipant.emit($.LocalTrackPublished,A)}for(let A=0;A<o.count-1;A+=1){let c=new Fa({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(A),state:ho.ACTIVE,tracks:[],joinedAt:bt.parse(Date.now())});const l=this.getOrCreateParticipant(c.identity,c);if(o.video){const d=gv(160*((s=o.aspectRatios[A%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),u=new ao({source:Yt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO});l.addSubscribedMediaTrack(d,u.sid,new MediaStream([d]),new RTCRtpReceiver),c.tracks=[...c.tracks,u]}if(o.audio){const d=t0(),u=new ao({source:Yt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO});l.addSubscribedMediaTrack(d,u.sid,new MediaStream([d]),new RTCRtpReceiver),c.tracks=[...c.tracks,u]}l.updateInfo(c)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==G.ActiveSpeakersChanged&&e!==G.TranscriptionReceived){const s=fC(i).filter(a=>a!==void 0);(e===G.TrackSubscribed||e===G.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...i)}}No.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});function fC(n){return n.map(e=>{if(e)return Array.isArray(e)?fC(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Yi;(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"})(Yi||(Yi={}));class Ws extends oi.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Yi.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new No(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return I(this,void 0,void 0,function*(){if(this.status!==Yi.IDLE)throw Error("check is running already");this.setStatus(Yi.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!==Yi.SKIPPED&&this.setStatus(this.isSuccess()?Yi.SUCCESS:Yi.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return I(this,void 0,void 0,function*(){return this.room.state===Ye.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return I(this,void 0,void 0,function*(){this.room&&this.room.state!==Ye.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Yi.SKIPPED)}switchProtocol(e){return I(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(G.Reconnecting,()=>{t=!0}),this.room.once(G.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield In(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 wT extends Ws{get description(){return"Cloud regions"}perform(){return I(this,void 0,void 0,function*(){const e=new Ve(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return I(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,A=1e6/a,c="A".repeat(a),l=Date.now();for(let p=0;p<A;p++)yield s.write(c);yield s.close();const d=Date.now(),u=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),h={region:r,rtt:1e4,duration:d-l};return u==null||u.forEach(p=>{p.type==="candidate-pair"&&p.nominated&&(h.rtt=p.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const u0=1e4;class bT extends Ws{get description(){return"Connection via UDP vs TCP"}perform(){return I(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/(u0/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(u0/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return I(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],c=(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},d=setInterval(()=>I(this,void 0,void 0,function*(){const u=yield c.getRTCStatsReport();u==null||u.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(u=>setTimeout(u,u0)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),l})}}class CT extends Ws{get description(){return"Can publish audio"}perform(){return I(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield hT();if(yield O3(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class BT extends Ws{get description(){return"Can publish video"}perform(){return I(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield uT();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return I(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(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,A;const c=document.createElement("canvas"),l=e.getSettings(),d=(a=(s=l.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,u=(A=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&A!==void 0?A:720;c.width=d,c.height=u;const h=c.getContext("2d");h.drawImage(i,0,0);const m=h.getImageData(0,0,c.width,c.height).data;let v=!0;for(let w=0;w<m.length;w+=4)if(m[w]!==0||m[w+1]!==0||m[w+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),t.getTracks().forEach(r=>r.stop()),i.remove()})}}class xT extends Ws{get description(){return"Resuming connection after interruption"}perform(){return I(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};t.on(G.SignalReconnecting,o).on(G.Reconnecting,o).on(G.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const A=t.engine.client.onClose;if(A&&A(""),yield a,i){if(!r||t.state!==Ye.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 ST extends Ws{get description(){return"Can connect via TURN"}perform(){return I(this,void 0,void 0,function*(){var e,t,i;Ro(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ve(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new Dm,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,A=!1;for(let c of s.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,A=!0):l.startsWith("turns:")&&(o=!0,A=!0,a=!0),l.startsWith("stun:")&&(A=!0);A?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(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(c=>setTimeout(c,0)))})}}class kT extends Ws{get description(){return"Establishing WebRTC connection"}perform(){return I(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(G.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){const o=new RTCIceCandidate(s);let A="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(ET(o.address)?A+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,A+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(A)}r&&r(s,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),Te.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 ET(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 TT extends Ws{get description(){return"Connecting to signal connection via WebSocket"}perform(){return I(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Dm,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Ro(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const A=yield new Ve(this.url,this.token).getNextBestRegionUrl();A&&(s=yield r.join(A,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"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===R4.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class IK extends oi.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:Yi.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!==Yi.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return I(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(TT)})}checkWebRTC(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(kT)})}checkTURN(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(ST)})}checkReconnect(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(xT)})}checkPublishAudio(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(CT)})}checkPublishVideo(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(BT)})}checkConnectionProtocol(){return I(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(bT);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(wT)})}}new TextEncoder;new TextDecoder;class Kn extends Error{constructor(e,t){var i;super(e,t),Re(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Re(Kn,"code","ERR_JOSE_GENERIC");class IT extends Kn{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),Re(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Re(this,"claim",void 0),Re(this,"reason",void 0),Re(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}Re(IT,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class MT extends Kn{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),Re(this,"code","ERR_JWT_EXPIRED"),Re(this,"claim",void 0),Re(this,"reason",void 0),Re(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}Re(MT,"code","ERR_JWT_EXPIRED");class UT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Re(UT,"code","ERR_JOSE_ALG_NOT_ALLOWED");class FT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Re(FT,"code","ERR_JOSE_NOT_SUPPORTED");class QT extends Kn{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),Re(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Re(QT,"code","ERR_JWE_DECRYPTION_FAILED");class PT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWE_INVALID")}}Re(PT,"code","ERR_JWE_INVALID");class DT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWS_INVALID")}}Re(DT,"code","ERR_JWS_INVALID");class LT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWT_INVALID")}}Re(LT,"code","ERR_JWT_INVALID");class RT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWK_INVALID")}}Re(RT,"code","ERR_JWK_INVALID");class _T extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWKS_INVALID")}}Re(_T,"code","ERR_JWKS_INVALID");class OT extends Kn{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),Re(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Re(OT,"code","ERR_JWKS_NO_MATCHING_KEY");class NT extends Kn{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),Re(this,Symbol.asyncIterator,void 0),Re(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Re(NT,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class HT extends Kn{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),Re(this,"code","ERR_JWKS_TIMEOUT")}}Re(HT,"code","ERR_JWKS_TIMEOUT");class KT extends Kn{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),Re(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Re(KT,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const VT="core-bridge-";function GT(n){return n.replace(/\/$/,"")}function zT(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`call-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}class qT{constructor(e){S(this,"serverUrl");S(this,"agentId");S(this,"callId");S(this,"authToken");S(this,"continuedCallId");S(this,"bridgePrefix");S(this,"onConnected");S(this,"onDisconnected");S(this,"onError");S(this,"room",null);S(this,"audioElements",[]);S(this,"connected",!1);S(this,"disconnecting",!1);if(!e.serverUrl)throw new Error("serverUrl is required");if(!e.agentId)throw new Error("agentId is required");this.serverUrl=GT(e.serverUrl),this.agentId=e.agentId,this.callId=e.callId??zT(),this.authToken=e.token,this.continuedCallId=e.continuedCallId,this.bridgePrefix=e.bridgeIdentityPrefix??VT,this.onConnected=e.onConnected,this.onDisconnected=e.onDisconnected,this.onError=e.onError}get isConnected(){return this.connected}reportError(e){var t;(t=this.onError)==null||t.call(this,e)}cleanupAudioElements(){for(const e of this.audioElements)try{e.pause(),e.srcObject=null,e.remove()}catch{}this.audioElements=[]}attachRemoteAudio(e){if(e.kind!==H.Kind.Audio)return;const t=e.attach();t.autoplay=!0,t.setAttribute("playsinline","true"),t.style.display="none",document.body.appendChild(t),t.play().catch(()=>{}),this.audioElements.push(t)}handleBridgeParticipant(e){e.identity.startsWith(this.bridgePrefix)&&e.trackPublications.forEach(t=>{t.track&&this.attachRemoteAudio(t.track)})}wireRoomEvents(e){e.on(G.TrackSubscribed,(t,i,r)=>{r.identity.startsWith(this.bridgePrefix)&&this.attachRemoteAudio(t)}),e.on(G.Disconnected,()=>{var t;this.connected=!1,this.cleanupAudioElements(),this.disconnecting||(t=this.onDisconnected)==null||t.call(this)})}async fetchLiveKitToken(){const e=new URLSearchParams({agent_id:this.agentId,call_id:this.callId});this.authToken&&e.set("token",this.authToken),this.continuedCallId&&e.set("continued_call_id",this.continuedCallId);const t=await fetch(`${this.serverUrl}/livekit/token?${e.toString()}`);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`GET /livekit/token failed (${t.status})${i?`: ${i}`:""}`)}return t.json()}async connect(){var e;if(this.connected||this.room)throw new Error("LiveKitVoiceClient is already connected");this.disconnecting=!1;try{const t=await this.fetchLiveKitToken();t.call_id&&(this.callId=t.call_id);const i=new No({adaptiveStream:!0,dynacast:!0});this.room=i,this.wireRoomEvents(i),await i.connect(t.url,t.token,{autoSubscribe:!0}),await i.localParticipant.setMicrophoneEnabled(!0);for(const r of i.remoteParticipants.values())this.handleBridgeParticipant(r);return this.connected=!0,(e=this.onConnected)==null||e.call(this,{roomName:t.room_name,identity:t.identity,callId:this.callId}),t}catch(t){if(this.cleanupAudioElements(),this.room)try{this.room.disconnect()}catch{}throw this.room=null,this.connected=!1,this.reportError(t),t}}disconnect(){var t;this.disconnecting=!0,this.connected=!1,this.cleanupAudioElements();const e=this.room;if(this.room=null,e)try{e.disconnect()}catch(i){this.reportError(i)}this.disconnecting=!1,(t=this.onDisconnected)==null||t.call(this)}}const lo=class lo{constructor(e){S(this,"tabId");S(this,"sessionKey");S(this,"channelName");S(this,"channel",null);S(this,"heartbeatTimer",null);S(this,"listeners",new Map);const t=e.replace(/[^a-z0-9_-]/gi,"_");this.sessionKey=`vaniraai_session_${t}`,this.channelName=`vaniraai_channel_${t}`,this.tabId=this._getOrCreateTabId(),this._setupChannel()}getTabId(){return this.tabId}claimSession(){const e=this._loadSession();if(e){const r=Date.now()-e.lastActive,s=e.tabId===this.tabId,a=r>lo.HEARTBEAT_TIMEOUT_MS;if(s)return this._startHeartbeat(),this._emit("session_restored"),!0;if(!a)return this._emit("tab_conflict"),!1}const t=e?{...e,tabId:this.tabId,lastActive:Date.now()}:{tabId:this.tabId,prospectId:"",chatId:null,conversationId:null,messages:[],lastActive:Date.now()};this._saveSession(t),this._startHeartbeat(),this._broadcast({type:"took_over",tabId:this.tabId});const i=!!(e!=null&&e.prospectId);return this._emit(i?"session_restored":"session_claimed"),!0}forceClaimSession(){const e=this._loadSession(),t=e?{...e,tabId:this.tabId,lastActive:Date.now()}:{tabId:this.tabId,prospectId:"",chatId:null,conversationId:null,messages:[],lastActive:Date.now()};this._saveSession(t),this._startHeartbeat(),this._broadcast({type:"took_over",tabId:this.tabId}),this._emit("session_claimed")}saveIds(e,t,i){const r=this._loadSession()??this._blankSession();this._saveSession({...r,prospectId:e,chatId:t,conversationId:i??r.conversationId??null,tabId:this.tabId,lastActive:Date.now()})}pushMessage(e,t){const i=this._loadSession()??this._blankSession();i.messages.push({role:e,content:t,timestamp:Date.now()}),i.messages.length>100&&(i.messages=i.messages.slice(-100)),this._saveSession({...i,tabId:this.tabId,lastActive:Date.now()})}updateLastAssistantMessage(e){const t=this._loadSession()??this._blankSession(),i=t.messages;let r=!1;for(let s=i.length-1;s>=0;s--)if(i[s].role==="assistant"&&i[s].content===""){i[s].content=e,r=!0;break}if(!r){for(let s=i.length-1;s>=0;s--)if(i[s].role==="assistant"){i[s].content=e,r=!0;break}}r||i.push({role:"assistant",content:e,timestamp:Date.now()}),this._saveSession({...t,tabId:this.tabId,lastActive:Date.now()})}getSession(){return this._loadSession()}clearSession(){localStorage.removeItem(this.sessionKey),this._broadcast({type:"session_cleared",tabId:this.tabId}),this._emit("session_cleared")}clearChatKeepProspect(){const e=this._loadSession();e&&this._saveSession({...e,chatId:null,conversationId:null,messages:[],lastActive:Date.now()})}destroy(){this._stopHeartbeat(),this.channel&&(this.channel.close(),this.channel=null)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){var i;return(i=this.listeners.get(e))==null||i.delete(t),this}_getOrCreateTabId(){let e=sessionStorage.getItem("vaniraai_tab_id");return e||(e=`tab_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionStorage.setItem("vaniraai_tab_id",e)),e}_setupChannel(){typeof BroadcastChannel>"u"||(this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=e=>{const t=e.data;t.tabId!==this.tabId&&(t.type==="took_over"&&(this._stopHeartbeat(),this._emit("tab_took_over")),t.type,t.type==="session_cleared"&&this._emit("session_cleared"))})}_broadcast(e){var t;(t=this.channel)==null||t.postMessage(e)}_startHeartbeat(){this._stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{const e=this._loadSession();e&&e.tabId===this.tabId&&(this._saveSession({...e,lastActive:Date.now()}),this._broadcast({type:"heartbeat",tabId:this.tabId}))},lo.HEARTBEAT_INTERVAL_MS)}_stopHeartbeat(){this.heartbeatTimer!==null&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}_loadSession(){try{const e=localStorage.getItem(this.sessionKey);return e?JSON.parse(e):null}catch{return null}}_saveSession(e){try{localStorage.setItem(this.sessionKey,JSON.stringify(e))}catch{}}_blankSession(){return{tabId:this.tabId,prospectId:"",chatId:null,conversationId:null,messages:[],lastActive:Date.now()}}_emit(e){var t;(t=this.listeners.get(e))==null||t.forEach(i=>i())}};S(lo,"HEARTBEAT_INTERVAL_MS",5e3),S(lo,"HEARTBEAT_TIMEOUT_MS",15e3);let Kd=lo;class mC{static async fetchWidgetConfig(e,t){var r;const i={"Content-Type":"application/json"};t&&(i["X-API-Key"]=t);try{const s=await fetch(`${Kc}/assistant/widget/${e}/config`,{method:"GET",headers:i});if(!s.ok)throw new Error(`Widget config fetch failed: HTTP ${s.status}`);const a=await s.json();return(r=a.agent)!=null&&r.client&&(a.client=a.agent.client),a}catch(s){throw s}}}let yA="https://inboxapi.vanira.io";const WT="https://coredb.travelr.club/v1/graphql";class Vr{static setChatUrl(e){yA=e}static async createChatProspect(e){var i,r;const t=`
|
|
57
|
+
`},o0}var Tv;function pE(){if(Tv)return Gi;Tv=1;var n=uE(),e=hE(),t=Lm();return Gi.grammar=t,Gi.write=e,Gi.parse=n.parse,Gi.parseParams=n.parseParams,Gi.parseFmtpConfig=n.parseFmtpConfig,Gi.parsePayloads=n.parsePayloads,Gi.parseRemoteCandidates=n.parseRemoteCandidates,Gi.parseImageAttributes=n.parseImageAttributes,Gi.parseSimulcastStreamList=n.parseSimulcastStreamList,Gi}var Si=pE();const fE=.7,mE=20,Ts={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Iv extends oi.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=Te,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Mm(r=>I(this,void 0,void 0,function*(){this.emit(Ts.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),mE),this.close=()=>{this._pc&&(this.pendingInitialOffer=void 0,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=si((i=t.loggerName)!==null&&i!==void 0?i:mn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new bn}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 I(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 I(this,void 0,void 0,function*(){var i,r;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 a=gE(e),o=a.stereoMids,A=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=A}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const o=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const A=Si.parse((i=o.sdp)!==null&&i!==void 0?i:"");A.media.forEach(c=>{rl(c)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(o,Si.write(A))}const a=Si.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(o=>{const A=Rm(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||A!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0)return!0;let d=!1;for(const u of o.fmtp)if(u.payload===l){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),d=!0;break}return d||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Si.write(a)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(Ts.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Ts.NegotiationComplete),e.sdp&&Si.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Ts.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return I(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);return}const i=this.latestOfferId+1;this.latestOfferId=i;const r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};const s=Si.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{rl(a)}),r.sdp=Si.write(s),{offer:r,offerId:i}}finally{t()}})}createAndSendOffer(e){return I(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const a=Si.parse((t=s.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{rl(o),o.type==="audio"?Mv(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(A=>{if(!o.msid||!A.cid||!o.msid.includes(A.cid))return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===A.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(er(A.codec)&&!Pa()&&this.ensureVideoDDExtensionForSVC(o,a),!er(A.codec)))return!0;const l=Math.round(A.maxbr*fE);for(const d of o.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,Si.write(a)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return I(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Si.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{rl(r),r.type==="audio"&&Mv(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Si.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 Mt("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 Mt("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()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return I(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return I(this,void 0,void 0,function*(){var r,s;const a=e.sdp;if(t){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(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:o,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{i?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(o){let A="unknown error";o instanceof Error?A=o.message:typeof o=="string"&&(A=o);const c={error:A,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!i&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:c})),new xa(A)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===hv))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var A;(A=o.ext)===null||A===void 0||A.forEach(c=>{c.value>a&&(a=c.value)})}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:hv})}}}function Mv(n,e,t){const i=Rm(n.mid);let r=0;n.rtp.some(s=>s.codec==="opus"?(r=s.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(s=>s.payload===r?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function gE(n){var e;const t=[],i=[],r=Si.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;const A=Rm(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(A),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(A),!0):!1))}),{stereoMids:t,nackMids:i}}function rl(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 Rm(n){return typeof n=="number"?n.toFixed(0):n}const Yp="vp8",vE={audioPreset:Op.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:km.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Yp,backupCodec:!0,preConnectBuffer:!1},Y3={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},J3={deviceId:{ideal:"default"},resolution:wc.h720.resolution},yE={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new L7,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},_m={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ut;(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"})(Ut||(Ut={}));class Uv{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 r;this.peerConnectionTimeout=_m.peerConnectionTimeout,this.log=Te,this.updateState=()=>{var s,a;const o=this.state,A=this.requiredTransports.map(c=>c.getConnectionState());A.every(c=>c==="connected")?this.state=Ut.CONNECTED:A.some(c=>c==="failed")?this.state=Ut.FAILED:A.some(c=>c==="connecting")?this.state=Ut.CONNECTING:A.every(c=>c==="closed")?this.state=Ut.CLOSED:A.some(c=>c==="closed")?this.state=Ut.CLOSING:A.every(c=>c==="new")&&(this.state=Ut.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Ut[o]," to ").concat(Ut[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=si((r=t.loggerName)!==null&&r!==void 0?r:mn.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Iv(i,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Iv(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Zi.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Zi.PUBLISHER)},this.publisher.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=(s,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,s,a)},this.state=Ut.NEW,this.connectionLock=new bn,this.remoteOfferLock=new bn}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 I(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(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return I(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return I(this,void 0,void 0,function*(){var i;t===Zi.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return I(this,void 0,void 0,function*(){var i,r,s;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(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.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 I(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return I(this,void 0,void 0,function*(){return new Rn((t,i)=>{const r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1;const a=()=>{s||(s=!0,clearTimeout(c),this.publisher.off(Ts.OfferAnswered,o),e.signal.removeEventListener("abort",A))},o=l=>{l>r&&(a(),t())},A=()=>{a(),i(new xa("negotiation aborted"))},c=setTimeout(()=>{a(),i(new xa("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",A),this.publisher.on(Ts.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?i(l):i(new Error(String(l)))})})})}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(r=>r.receiver===e);return i==null?void 0:i.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Zi.PUBLISHER?this.publisher.getConnectedAddress():e===Zi.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 I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((A,c)=>I(s,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),Zt.clearTimeout(d),c(fe.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&l(),r==null||r.signal.addEventListener("abort",l);const d=Zt.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",l),c(fe.internal("could not establish pc connection"))},a);for(;this.state!==Ut.CONNECTED;)if(yield In(50),r!=null&&r.signal.aborted){c(fe.cancelled("room connection has been cancelled"));return}Zt.clearTimeout(d),r==null||r.signal.removeEventListener("abort",l),A()}))}()})}}const Om=typeof MediaRecorder<"u";class wE{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const bE=Om?MediaRecorder:wE;class CE extends bE{constructor(e,t){if(!Om)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,r;const s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r==null||r.close(),r=void 0},o=A=>{r==null||r.error(A),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:A=>{r=A,i=c=>I(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){const d=yield c.data.arrayBuffer();l=new Uint8Array(d)}else if(c.data.byteArray)l=c.data.byteArray;else throw new Error("no data available!");s()||A.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function BE(){return Om}const xE=1e3,SE=1e4;class X3 extends H{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),this.manuallyStopped=!1,this.pendingDeviceChange=!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=Mm(()=>I(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>I(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(J.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new bn,this.pauseUpstreamLock=new bn,this.trackChangeLock=new bn,this.trackChangeLock.lock().then(a=>I(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!==H.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;if(t&&i)return{width:t,height:i}}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,i){return I(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{mo(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let 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&&(oo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),s=this.processor.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{oo(s??e,a)}))})}waitForDimensions(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xE;return function*(){var i;if(e.kind===H.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=On())===null||i===void 0?void 0:i.os)==="iOS"&&(yield In(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield In(50)}throw new Xr("unable to get track dimensions after timeout")}()})}setDeviceId(e){return I(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Sa(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Sa(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return I(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===H.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),r=i.deviceId,s=i.groupId,a=e.kind===H.Kind.Audio?"audioinput":"videoinput";return t?pn.getInstance().normalizeDeviceId(a,r,s):r}()})}mute(){return I(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return I(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return I(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Xr("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return I(this,void 0,void 0,function*(){})}restart(e,t){return I(this,void 0,void 0,function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const r=e,s=r.deviceId,a=r.facingMode,o=R7(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===H.Kind.Video?A.video=s||a?{deviceId:s,facingMode:a}:!0:A.audio=s?Object.assign({deviceId:s},o):!0,this.attachedElements.forEach(d=>{mo(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(A)).getTracks()[0];return this.kind===H.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(J.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}})}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?J.Muted:J.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 I(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),K3()&&(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 I(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(J.UpstreamPaused,this);const i=On();if((i==null?void 0:i.name)==="Safari"&&Er(i.version,"12.0")<0)throw new Sm("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 I(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(J.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 I(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 I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),A={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext,localTrack:i};if(yield t.init(A),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(oo(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{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:c}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(mo(i._mediaStreamTrack,c),oo(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(J.TrackProcessorUpdate,i.processor)}finally{a()}yield i.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return I(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()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(J.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!BE()){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 CE(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},SE)}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 Rd extends X3{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,H.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>I(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=Qu(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(J.AudioTrackFeatureUpdate,this,hn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(J.AudioTrackFeatureUpdate,this,hn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return I(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===H.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return I(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===H.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return I(this,void 0,void 0,function*(){let t;if(e){const i=Em({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return I(this,void 0,void 0,function*(){const r=yield i.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){ti()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Um)))}setProcessor(e){return I(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!ar()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(J.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return I(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return I(this,void 0,void 0,function*(){const e=yield O3(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(J.AudioSilenceDetected)),e})}}function kE(n,e,t){switch(n.kind){case"audio":return new Rd(n,e,!1,void 0,t);case"video":return new Od(n,e,!1,t);default:throw new Xr("unsupported track type: ".concat(n.kind))}}const EE=Object.values(wc),TE=Object.values(Np),IE=Object.values(km),ME=[wc.h180,wc.h360],UE=[Np.h180,Np.h360],FE=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new it(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),Jp=["q","h","f"];function _d(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,A=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!a&&!o&&!A||!e||!t)return[{}];a||(a=QE(n,e,t,c),Te.debug("using video encoding",a));const l=a.maxFramerate,d=new it(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(A&&er(c)){const v=new $3(A),w=[];if(v.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(A));const b=On();if(bc()||ar()||(b==null?void 0:b.name)==="Chrome"&&Er(b==null?void 0:b.version,"113")<0){const k=v.suffix=="h"?2:3,y=B8(b);for(let B=0;B<v.spatial;B+=1)w.push({rid:Jp[2-B],maxBitrate:a.maxBitrate/Math.pow(k,B),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,B):void 0});w[0].scalabilityMode=A}else w.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:A});return d.encoding.priority&&(w[0].priority=d.encoding.priority,w[0].networkPriority=d.encoding.priority),Te.debug("using svc encoding",{encodings:w}),w}if(!o)return[a];let u;n?u=(r=Qv(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Fv(n,d):u=(s=Qv(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Fv(n,d);let h;if(u.length>0){const v=u[0];if(u.length>1){var p=u,m=pe(p,2);h=m[1]}const w=Math.max(e,t);if(w>=960&&h)return A0(e,t,[v,h,d],l);if(w>=480)return A0(e,t,[v,d],l)}return A0(e,t,[d])}function Z3(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&Te.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(),A=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===H.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),_d(n.source===H.Source.ScreenShare,A,c,t)}function QE(n,e,t,i){const r=PE(n,e,t);let s=r[0].encoding;const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const A=r[o];if(s=A.encoding,A.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function PE(n,e,t){if(n)return IE;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?EE:TE}function Fv(n,e){if(n)return FE(e);const t=e.width,i=e.height,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?ME:UE}function A0(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=Jp.length)return;const o=Math.min(n,e),c={rid:Jp[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(c.maxFramerate=l);const d=On(),u=(d==null?void 0:d.name)==="Firefox"&&d.os!=="iOS"||a===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),ar()&&G3()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var A;o.maxFramerate!=s&&(a&&(a=!1,Te.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Te.info('Setting framerate of encoding "'.concat((A=o.rid)!==null&&A!==void 0?A:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Qv(n){if(n)return n.slice().sort((e,t)=>{const i=e.encoding,r=t.encoding;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class $3{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 DE(n){return n.source===H.Source.ScreenShare||n.constraints.height&&Sa(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const LE=5e3;class Od extends X3{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,H.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>I(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(A){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:A}));return}const a=new Map(s.map(A=>[A.rid,A])),o=s.some(A=>A.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(J.CpuConstrained)),this.prevStats){let A=0;a.forEach((c,l)=>{var d;const u=(d=this.prevStats)===null||d===void 0?void 0:d.get(l);A+=Qu(c,u)}),this._currentBitrate=A}this.prevStats=a}),this.senderLock=new bn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ti())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()},Um))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return I(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,A=$i(this.simulcastCodecs.values()),c;c=yield A.next(),t=c.done,!t;o=!0)s=c.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(r=A.return)&&(yield r.call(A))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return I(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,A=$i(this.simulcastCodecs.values()),c;c=yield A.next(),t=c.done,!t;o=!0){s=c.value,o=!1;const l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(r=A.return)&&(yield r.call(A))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return I(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===H.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 I(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===H.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),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 I(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=mi.LOW;i<=mi.HIGH;i+=1)t.push(new Bm({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(er(this.codec),t)}restartTrack(e){return I(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const d=Em({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var A=!0,c=$i(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;A=!0){s=l.value,A=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!A&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return I(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return I(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;const s=this.source===H.Source.ScreenShare,a=_d(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(const o of this.simulcastCodecs){var i=pe(o,2);const A=i[0],c=i[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!R3(A))continue;const l=Object.assign({},this.publishOptions),d=Z3(this,A,l);d&&(yield this.applyEncodingsToSender(c.sender,d),c.encodings=d)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return I(this,void 0,void 0,function*(){const i=e.getParameters();!i.encodings||i.encodings.length!==t.length||(i.encodings.forEach((r,s)=>{if(r.active===!1)return;const a=t[s];a.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(r.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(r.maxFramerate=a.maxFramerate),a.priority!==void 0&&(r.priority=a.priority,r.networkPriority=a.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return I(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,A,c,l,d;if(yield t.setProcessor.call(r,i,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var u=!0,h=$i(r.simulcastCodecs.values()),p;p=yield h.next(),a=p.done,!a;u=!0)c=p.value,u=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){o={error:m}}finally{try{!u&&!a&&(A=h.return)&&(yield A.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return I(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)},LE))}setPublishingCodecs(e){return I(this,void 0,void 0,function*(){var t,i,r,s,a,o,A;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(er(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=$i(e);r=yield i.next(),s=r.done,!s;t=!0){A=r.value,t=!1;const l=A;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(er(l.codec),l.qualities);else{const d=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const u of l.qualities)if(u.enabled){c.push(l.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Pv(d.sender,d.encodings,l.qualities,this.senderLock,er(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return I(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 Pv(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return I(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,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&er(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings: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 I(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),K3()&&this.isInBackground&&this.source===H.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Pv(n,e,t,i,r,s,a){return I(this,void 0,void 0,function*(){const o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const A=n.getParameters(),c=A.encodings;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:c,senderEncodings:e}));return}let l=!1;!1&&c[0].scalabilityMode||(r&&t.some(h=>h.enabled)&&t.forEach(h=>h.enabled=!0),c.forEach((u,h)=>{var p;let m=(p=u.rid)!==null&&p!==void 0?p:"";m===""&&(m="q");const v=eC(m),w=t.find(b=>b.quality===v);w&&u.active!==w.enabled&&(l=!0,u.active=w.enabled,s.debug("setting layer ".concat(w.quality," to ").concat(u.active?"enabled":"disabled"),a),Qa()&&(w.enabled?(u.scaleResolutionDownBy=e[h].scaleResolutionDownBy,u.maxBitrate=e[h].maxBitrate,u.maxFrameRate=e[h].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))})),l&&(A.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:A.encodings})),yield n.setParameters(A))}finally{o()}})}function eC(n){switch(n){case"f":return mi.HIGH;case"h":return mi.MEDIUM;case"q":return mi.LOW;default:return mi.HIGH}}function Dv(n,e,t,i){if(!t)return[new Us({quality:mi.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new $3(r),a=[],o=s.suffix=="h"?1.5:2,A=s.suffix=="h"?2:3;for(let c=0;c<s.spatial;c+=1)a.push(new Us({quality:Math.min(mi.HIGH,s.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(A,c)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const A=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let c=eC((a=r.rid)!==null&&a!==void 0?a:"");return new Us({quality:c,width:Math.ceil(n/A),height:Math.ceil(e/A),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Lv="_lossy",Rv="_reliable",_v="_data_track",RE=2*1e3,c0="leave-reconnect",_E=3e4,OE=8*1024,NE=256*1024,HE=3,KE=3;var ki;(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"})(ki||(ki={}));var Me;(function(n){n[n.RELIABLE=0]="RELIABLE",n[n.LOSSY=1]="LOSSY",n[n.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(Me||(Me={}));const Ov=64e3;class VE extends oi.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=_m.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ki.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=Te,this.reliableDataSequence=1,this.reliableMessageBuffer=new xv,this.reliableReceivedState=new dE(_E),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new fn,this.handleDataChannel=i=>I(this,[i],void 0,function(r){var s=this;let a=r.channel;return function*(){if(!a)return;let o;if(a.label===Rv)s.reliableDCSub=a,o=s.handleDataMessage;else if(a.label===Lv)s.lossyDCSub=a,o=s.handleDataMessage;else if(a.label===_v)s.dataTrackDCSub=a,o=s.handleDataTrackMessage;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label)),a.onmessage=o}()}),this.handleDataMessage=i=>I(this,void 0,void 0,function*(){var r,s,a,o,A;const c=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",{data:i.data});return}const d=En.fromBinary(new Uint8Array(l));if(d.sequence>0&&d.participantSid!==""){const u=this.reliableReceivedState.get(d.participantSid);if(u&&d.sequence<=u)return;this.reliableReceivedState.set(d.participantSid,d.sequence)}if(((r=d.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(q.ActiveSpeakersUpdate,d.value.value.speakers);else if(((s=d.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const u=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(d.value.value.encryptedValue,d.value.value.iv,d.participantIdentity,d.value.value.keyIndex),h=U4.fromBinary(u.payload),p=new En({value:h.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((o=p.value)===null||o===void 0?void 0:o.case)==="user"&&Nv(p,p.value.value),this.emit(q.DataPacketReceived,p,d.value.value.encryptionType)}else((A=d.value)===null||A===void 0?void 0:A.case)==="user"&&Nv(d,d.value.value),this.emit(q.DataPacketReceived,d,At.NONE)}finally{c()}}),this.handleDataTrackMessage=i=>I(this,void 0,void 0,function*(){let r;if(i.data instanceof ArrayBuffer)r=i.data;else if(i.data instanceof Blob)r=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",{data:i.data});return}this.emit("dataTrackPacketReceived",new Uint8Array(r))}),this.handleDataError=i=>{if(this._isClosed)return;const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&i instanceof RTCErrorEvent&&i.error){const a=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(a.message),{error:a,errorDetail:a.errorDetail,sctpCauseCode:a.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(s),{event:i})},this.handleDataChannelClose=i=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(Me[i],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=i=>{this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=A=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(A,"ms. giving up")),this.emit(q.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===c0&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(q.TokenRefreshed,this.token),this.reconnectTimeout=Zt.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===ki.Connected&&i();const s=()=>{this.off(q.Disconnected,a),i()},a=()=>{this.off(q.Restarted,s),r()};this.once(q.Restarted,s),this.once(q.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Me.RELIABLE){const s=this.dataChannelForKind(i);s&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(q.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.onRtpMapAvailable=i=>{const r=new Map;i.forEach(s=>{const a=s.codec.toLowerCase();T8(a)&&r.set(s.payload,a)}),this.emit(q.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>I(this,void 0,void 0,function*(){!this.url||!(yield fetch(Cc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===st.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===st.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Aa.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>I(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Cc(this.url),{method:"HEAD"}),In(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=si((t=e.loggerName)!==null&&t!==void 0?t:mn.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Dm(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new bn,this.dataProcessLock=new bn,this.dcBufferStatus=new Map([[Me.RELIABLE,!0],[Me.LOSSY,!0],[Me.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=i=>this.emit(q.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(q.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(q.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(q.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(q.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(q.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(q.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(q.SignalRequestResponse,i),this.client.onParticipantUpdate=i=>this.emit(q.ParticipantUpdate,i),this.client.onJoined=i=>this.emit(q.Joined,i),this.on(q.Closing,()=>{var i,r;(r=(i=this.bufferStatusLowClosingFuture).reject)===null||r===void 0||r.call(i,new Mt("engine closed"))}),this.bufferStatusLowClosingFuture.promise.catch(()=>{})}get logContext(){var e,t,i,r,s,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,r){return I(this,arguments,void 0,function(s,a,o,A){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var d,u,h;c._isNewlyCreated=!1,c.url=s,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();const p=!l&&L8();let m;if(p){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());const b=yield(d=c.pcManager)===null||d===void 0?void 0:d.publisher.createInitialOffer();b&&(m=pa(b.offer,b.offerId))}if(A!=null&&A.aborted)throw fe.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,fe.serviceNotFound("Simulated v1 path failure","v0-rtc");const v=yield c.client.join(s,a,o,A,l,m);c._isClosed=!1,c.latestJoinResponse=v,c.participantSid=(u=v.participant)===null||u===void 0?void 0:u.sid,c.subscriberPrimary=v.subscriberPrimary,p?(h=c.pcManager)===null||h===void 0||h.updateConfiguration(c.makeRTCConfiguration(v)):(c.pcManager||(yield c.configure(v,!l),l||c.applyInitialPublisherLayout()),(!c.subscriberPrimary||v.fastPublish)&&c.negotiate().catch(b=>{c.log.error(b)})),c.registerOnLineListener(),c.clientConfiguration=v.clientConfiguration,c.emit(q.SignalConnected,v);let w=v.serverInfo;return w||(w={version:v.serverVersion,region:v.serverRegion}),c.log.info("connected to Livekit Server ".concat(Object.entries(w).map(b=>{let k=pe(b,2),y=k[0],B=k[1];return"".concat(y,": ").concat(B)}).join(", "))),{joinResponse:v,serverInfo:w}}catch(p){if(p instanceof fe){if(p.reason===at.ServerUnreachable){if(c.log.warn("Couldn't connect to server, attempt ".concat(c.joinAttempts," of ").concat(c.maxJoinAttempts)),c.joinAttempts<c.maxJoinAttempts)return c.join(s,a,o,A,l)}else if(p.reason===at.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(p.message," – Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(s,a,o,A,!0)}throw p}}()})}close(){return I(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(q.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return I(this,void 0,void 0,function*(){var e;const t=i=>{i&&(i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null,i.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new xv,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 I(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Xr("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(fe.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{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 I(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return I(this,void 0,void 0,function*(){var i;if(!(this.pcManager&&this.pcManager.currentState!==Ut.NEW)){if(e){this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new Uv(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{const r=this.makeRTCConfiguration();this.pcManager=new Uv("publisher-only",this.loggerOptions,r)}this.emit(q.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>I(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===Ut.CONNECTED){const c=this.pcState===ki.New;this.pcState=ki.Connected,c&&this.emit(q.Connected,this.latestJoinResponse)}else r===Ut.FAILED&&(this.pcState===ki.Connected||this.pcState===ki.Reconnecting)&&(this.pcState=ki.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Aa.RR_SUBSCRIBER_FAILED:Aa.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===st.RECONNECTING,A=[Ut.FAILED,Ut.CLOSING,Ut.CLOSED].includes(r);o&&A&&!this._isClosed&&this.emit(q.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(q.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>I(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{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",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>I(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{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),{cid:e.cid});return}const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(q.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(q.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(q.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(q.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(q.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(q.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(q.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(q.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(q.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Aa.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e==null?void 0:e.action,")"),{reason:e==null?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(q.ServerRegionsReported,e.regions)),e.action){case po.DISCONNECT:this.emit(q.Disconnected,e==null?void 0:e.reason),this.close();break;case po.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(c0);break;case po.RESUME:this.handleDisconnect(c0)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Bc())&&Im()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===gc.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),ar()||this.addMediaSections(HE,KE)}addMediaSections(e,t){var i,r;const s={direction:"recvonly"};for(let a=0;a<e;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("audio",s);for(let a=0;a<t;a++)(r=this.pcManager)===null||r===void 0||r.addPublisherTransceiverOfKind("video",s)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Lv,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Rv,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(_v,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.onclose=this.handleDataChannelClose(Me.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(Me.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(Me.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Me.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Me.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Me.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Me.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,OE),NE)}},1e3))}createSender(e,t,i){return I(this,void 0,void 0,function*(){let r;if(Vp())r=yield this.createTransceiverRTCRtpSender(e,t,i);else if(Gp())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Mt("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,i,r){return I(this,void 0,void 0,function*(){let s;if(Vp())s=yield this.createSimulcastTransceiverSender(e,t,i,r);else if(Gp())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Mt("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,i),s})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r,s;const a=this.frameMetadataWorker;if(!a||!((i=this.signalOpts)===null||i===void 0)&&i.e2eeEnabled)return;const o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,A=Dd(o);if(Bc()){A&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!xc((s=this.options.frameMetadata)!==null&&s!==void 0?s:this.options.packetTrailer)||!("createEncodedStreams"in e)){A&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const c=e.createEncodedStreams(),l=c.readable,d=c.writable;A?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:d,packetTrailer:o}},[l,d]):l.pipeTo(d)}createTransceiverRTCRtpSender(e,t,i){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),as(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return I(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===gc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Ut.NEW)===Ut.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Mt?(this.log.debug("received unrecoverable error",{error:s}),a=!1):s instanceof qa||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Aa.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(q.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",{error:t})}return null}restartConnection(e){return I(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new Mt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(q.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new qa;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof fe&&a.reason===at.NotAllowed?new Mt("could not reconnect, token might be expired"):new qa}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(q.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==st.CONNECTED)throw new qa("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(q.Restarted)}catch(s){const a=yield(i=this.regionStrategy)===null||i===void 0?void 0:i.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return I(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Mt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Mt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(q.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof fe&&r.reason===at.NotAllowed?new Mt("could not reconnect, token might be expired"):r instanceof fe&&r.reason===at.LeaveRequest?r:new qa(s)}if(this.emit(q.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==st.CONNECTED)throw new qa("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!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(q.Resumed)})}waitForPCInitialConnection(e,t){return I(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return I(this,void 0,void 0,function*(){this.pcState=ki.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield In(RE),!this.pcManager)throw new Mt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ki.Connected}catch(e){throw this.pcState=ki.Disconnected,fe.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return I(this,void 0,void 0,function*(){const i=new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcAck",value:new Eu({requestId:t})}});yield this.sendDataPacket(i,Me.RELIABLE)})}sendDataPacket(e,t){return I(this,void 0,void 0,function*(){var i,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=q8(e);if(o){const A=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new M4({encryptedValue:A.payload,iv:A.iv,keyIndex:A.keyIndex})}}}t===Me.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const s=e.toBinary(),a=Math.min((r=(i=this.pcManager)===null||i===void 0?void 0:i.getMaxPublisherMessageSize())!==null&&r!==void 0?r:Ov,Ov);if(typeof a<"u"&&a!==0&&s.byteLength>a)throw new i8("cannot publish data packet larger than ".concat(a," bytes (got ").concat(s.byteLength,")"));switch(t){case Me.LOSSY:case Me.DATA_TRACK_LOSSY:return this.sendLossyBytes(s,t);case Me.RELIABLE:const o=this.dataChannelForKind(t);if(o){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:s,sequence:e.sequence}),this.attemptingReconnect)return;o.send(s)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"drop";return function*(){yield s.ensurePublisherConnected(r);const o=s.dataChannelForKind(r);if(o){if(!s.isBufferStatusLow(r))switch(a){case"wait":yield s.waitForBufferStatusLow(r);break;case"drop":s.lossyDataDropCount+=1,s.lossyDataDropCount%100===0&&s.log.warn("dropping lossy data channel messages, total dropped: ".concat(s.lossyDataDropCount));return}if(s.lossyDataStatCurrentBytes+=i.byteLength,s.attemptingReconnect)return;o.send(i)}s.updateAndEmitDCBufferStatus(r)}()})}resendReliableMessagesForResume(e){return I(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Me.RELIABLE);const t=this.dataChannelForKind(Me.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(Me.RELIABLE)})}waitForBufferStatusLow(e){return I(this,void 0,void 0,function*(){return new Rn((t,i)=>I(this,void 0,void 0,function*(){if(this.isClosed&&i(new Mt("engine closed")),this.isBufferStatusLow(e))t();else{const r=this.dataChannelForKind(e);if(!r){i(new Mt("DataChannel not found, kind: ".concat(e)));return}this.bufferStatusLowClosingFuture.promise.catch(s=>i(s)),r.addEventListener("bufferedamountlow",()=>t(),{once:!0})}}))})}ensureDataTransportConnected(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new Mt("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw fe.internal("".concat(o," connection not set"));let A=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),A=!0),!A&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(A=!0),A&&i.negotiate().catch(d=>{i.log.error(d)});const c=i.dataChannelForKind(t,r);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield In(50)}throw fe.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))}()})}ensurePublisherConnected(e){return I(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![Ut.CONNECTING,Ut.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return I(this,void 0,void 0,function*(){return new Rn((e,t)=>I(this,void 0,void 0,function*(){if(!this.pcManager){t(new xa("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new xa("cannot negotiate on closed engine")),this.on(q.Closing,r),this.on(q.Restarting,r),this.pcManager.publisher.off(Ts.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(Ts.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(s){if(i.signal.aborted){e();return}s instanceof xa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Aa.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(q.Closing,r),this.off(q.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case Me.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case Me.LOSSY:return t?this.lossyDCSub:this.lossyDC;case Me.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,i){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const A=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),d=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,p=new Array;e.forEach(m=>{m.isDesired!==u&&h.push(m.trackSid),m.isEnabled||p.push(m.trackSid)}),this.client.sendSyncState(new xm({answer:this.pcManager.mode==="publisher-only"?c?pa({sdp:c.sdp,type:c.type}):void 0:d?pa({sdp:d.sdp,type:d.type}):void 0,offer:this.pcManager.mode==="publisher-only"?A?pa({sdp:A.sdp,type:A.type}):void 0:l?pa({sdp:l.sdp,type:l.type}):void 0,subscription:new Mu({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:l8(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((m,v)=>new $4({publisherSid:v,lastSeq:m})),publishDataTracks:i.map(m=>new vm({info:Ld.toProtobuf(m)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new e3({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(Me.LOSSY),Zi.PUBLISHER),t(this.dataChannelForKind(Me.RELIABLE),Zi.PUBLISHER),t(this.dataChannelForKind(Me.LOSSY,!0),Zi.SUBSCRIBER),t(this.dataChannelForKind(Me.RELIABLE,!0),Zi.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Zt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ti()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ti()&&(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 r=Object.entries(this.midToTrackId).find(s=>pe(s,1)[0]===i);if(r)return r[1]}}}function Nv(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}const Xp=5e3,GE=3e4;class Ve{static fetchRegionSettings(e,t,i){return I(this,void 0,void 0,function*(){const r=yield Ve.fetchLock.lock();try{const s=yield fetch("".concat(zE(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(s.ok){const a=D8(s.headers),o=a?a*1e3:Xp;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?fe.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):fe.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof fe?s:i!=null&&i.aborted?fe.cancelled("Region fetching was aborted"):fe.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,i){return I(this,void 0,void 0,function*(){const r=Ve.settingsTimeouts.get(e.hostname);clearTimeout(r),Ve.settingsTimeouts.set(e.hostname,setTimeout(()=>I(this,void 0,void 0,function*(){try{const s=yield Ve.fetchRegionSettings(e,t);Ve.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof fe&&s.reason===at.NotAllowed){Te.debug("token is not valid, cancelling auto region refresh");return}Te.debug("auto refetching of region settings failed",{error:s}),Ve.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){Ve.cache.set(e.hostname,i),Ve.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=Ve.settingsTimeouts.get(e);t&&(clearTimeout(t),Ve.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Ve.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=Ve.connectionTrackers.get(e);i&&i.connectionCount===0&&(Te.debug("stopping region refetch after disconnect delay",{hostname:e}),Ve.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},GE))}static cancelCleanup(e){const t=Ve.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Ve.connectionTrackers.get(e);t||(t={connectionCount:0},Ve.connectionTrackers.set(e,t)),t.connectionCount++,Ve.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Ve.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&Ve.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),r=Ve.cache.get(i.hostname);Ve.scheduleRefetch(this.serverUrl,this.token,(t=r==null?void 0:r.maxAgeInMs)!==null&&t!==void 0?t:Xp)}isCloud(){return Ro(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return I(this,void 0,void 0,function*(){return Ve.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return I(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Ve.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Ve.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),Te.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ve.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ve.cache=new Map;Ve.settingsTimeouts=new Map;Ve.connectionTrackers=new Map;Ve.fetchLock=new bn;function zE(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class tC{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 Ei("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Dn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ei("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Dn.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class qE extends tC{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();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>I(this,void 0,void 0,function*(){try{const i=this.signal;if(i!=null&&i.aborted)throw i.reason;const r=yield new Promise((s,a)=>{if(i){const o=()=>a(i.reason);i.addEventListener("abort",o,{once:!0}),e.read().then(s,a).finally(()=>{i.removeEventListener("abort",o)})}else e.read().then(s,a)});return r.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(i){throw t(),i}}),return(){return I(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,s,a;let o=new Set;const A=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=$i(A),d;d=yield l.next(),i=d.done,!i;c=!0){a=d.value,c=!1;const u=a;o.add(u)}}catch(u){r={error:u}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}}class WE extends tC{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=sd(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>I(this,void 0,void 0,function*(){try{if(i!=null&&i.aborted)throw i.reason;const s=yield new Promise((a,o)=>{if(i){const A=()=>o(i.reason);i.addEventListener("abort",A,{once:!0}),e.read().then(a,o).finally(()=>{i.removeEventListener("abort",A)})}else e.read().then(a,o)});if(s.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(s.value);let a;try{a=t.decode(s.value.content)}catch(o){throw new Ei("Cannot decode datastream chunk ".concat(s.value.chunkIndex," as text: ").concat(o),Dn.DecodeFailed)}return{done:!1,value:a}}}catch(s){throw r(),s}}),return(){return I(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return I(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,s,a;let o="";const A=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=$i(A),d;d=yield l.next(),i=d.done,!i;c=!0)a=d.value,c=!1,o+=a}catch(u){r={error:u}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o}()})}}class jE{constructor(){this.log=Te,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const i=t.packet,r=t.encryptionType;this.handleDataStreamPacket(i,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Ei('A text stream handler for topic "'.concat(e,'" has already been set.'),Dn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ei('A byte stream handler for topic "'.concat(e,'" has already been set.'),Dn.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){const a=new Ei("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Dn.AbnormalEnd);for(const o of i){var r=pe(o,2);const A=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(A)}for(const o of t){var s=pe(o,2);const A=s[0];s[1].controller.error(a),this.textStreamControllers.delete(A)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}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){var r;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sd(e.timestamp),attributes:e.attributes,encryptionType:i},A=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Ei("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Dn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new qE(o,A,sd(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={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},A=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Ei("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Dn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new WE(o,A,sd(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Dn.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),Dn.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Dn.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new Ei("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),Dn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class nC{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 I(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 YE extends nC{}class JE extends nC{}const Hv=15e3;class XE{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return I(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),A=new Array(o?o.length+1:1).fill(0),c=(d,u)=>{var h;A[u]=d;const p=A.reduce((m,v)=>m+v,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,p)},l=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield l.write(e),c(1,0),yield l.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((d,u)=>I(this,void 0,void 0,function*(){return this._sendFile(o[u],d,{topic:t.topic,mimeType:d.type,onProgress:h=>{c(h,u+1)}})})))),l.info})}streamText(e){return I(this,void 0,void 0,function*(){var t,i,r;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?At.GCM:At.NONE,attachedStreamIds:e==null?void 0:e.attachedStreamIds},o=new Md({streamId:s,mimeType:a.mimeType,topic:a.topic,timestamp:ca(a.timestamp),totalLength:ca(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new V4({version:e==null?void 0:e.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Ep.UPDATE:Ep.CREATE})}}),A=e==null?void 0:e.destinationIdentities,c=new En({destinationIdentities:A,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Me.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(m){return I(this,void 0,void 0,function*(){for(const v of P8(m,Hv)){const w=new Ud({content:v,streamId:s,chunkIndex:ca(l)}),b=new En({destinationIdentities:A,value:{case:"streamChunk",value:w}});yield d.sendDataPacket(b,Me.RELIABLE),l+=1}})},close(){return I(this,void 0,void 0,function*(){const m=new Fd({streamId:s}),v=new En({destinationIdentities:A,value:{case:"streamTrailer",value:m}});yield d.sendDataPacket(v,Me.RELIABLE)})},abort(m){}});let h=()=>I(this,void 0,void 0,function*(){yield p.close()});d.once(q.Closing,h);const p=new YE(u,a,()=>this.engine.off(q.Closing,h));return p})}sendFile(e,t){return I(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return I(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const o=yield a.read(),A=o.done,c=o.value;if(A)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return I(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?At.GCM:At.NONE},l=new Md({totalLength:ca(c.size),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:ca(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new G4({name:c.name})}}),d=new En({destinationIdentities:A,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(d,Me.RELIABLE);let u=0;const h=new bn,p=this.engine,m=this.log,v=new WritableStream({write(b){return I(this,void 0,void 0,function*(){const k=yield h.lock();let y=0;try{for(;y<b.byteLength;){const B=b.slice(y,y+Hv),E=new En({destinationIdentities:A,value:{case:"streamChunk",value:new Ud({content:B,streamId:o,chunkIndex:ca(u)})}});yield p.sendDataPacket(E,Me.RELIABLE),u+=1,y+=B.byteLength}}finally{k()}})},close(){return I(this,void 0,void 0,function*(){const b=new Fd({streamId:o}),k=new En({destinationIdentities:A,value:{case:"streamTrailer",value:b}});yield p.sendDataPacket(k,Me.RELIABLE)})},abort(b){m.error("Sink error:",b)}});return new JE(v,c)})}}function iC(n){if(n.length===0)return new AbortController().signal;if(n.length===1)return n[0];for(const r of n)if(r.aborted)return r;const e=new AbortController,t=Array(n.length),i=()=>{for(const r of t)r()};return n.forEach((r,s)=>{const a=()=>{e.abort(r.reason),i()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function rC(n){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(n," ms"),"TimeoutError"))},n),e.signal}const _t=1,Lr=2,Kv=4,ZE=8,Vv=0,Gv=12,zv=5,$E=7,qv=3,eT=3,Wv=2,jv=1,Yv=0,Jv=3,sl=2,Xv=2,tT=1,nT=0;var Kr;(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"})(Kr||(Kr={}));class Ln extends Hi{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Kr[t]}static tooShort(){return new Ln("Too short to contain a valid header",Kr.TooShort)}static headerOverrun(){return new Ln("Header exceeds total packet length",Kr.HeaderOverrun)}static missingExtWords(){return new Ln("Extension word indicator is missing",Kr.MissingExtWords)}static unsupportedVersion(e){return new Ln("Unsupported version ".concat(e),Kr.UnsupportedVersion)}static invalidHandle(e){return new Ln("invalid track handle: ".concat(e.message),Kr.InvalidHandle,{cause:e})}static malformedExt(e){return new Ln("Extension with tag ".concat(e," is malformed"),Kr.MalformedExt)}}var ec;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(ec||(ec={}));class Sc extends Hi{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=ec[t]}static tooSmallForHeader(){return new Sc("Buffer cannot fit header",ec.TooSmallForHeader)}static tooSmallForPayload(){return new Sc("Buffer cannot fit payload",ec.TooSmallForPayload)}}class Pu{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),r=this.toBinaryInto(i);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var Oo;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Oo||(Oo={}));class sC extends Pu{}class tr extends sC{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return _t+_t+tr.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,tr.tag),t+=_t,e.setUint8(t,tr.lengthBytes),t+=_t,e.setBigUint64(t,this.timestamp),t+=ZE;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:tr.tag,lengthBytes:tr.lengthBytes,timestamp:this.timestamp}}}tr.tag=Oo.UserTimestamp;tr.lengthBytes=8;class nr extends sC{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return _t+_t+nr.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,nr.tag),t+=_t,e.setUint8(t,nr.lengthBytes),t+=_t,e.setUint8(t,this.keyIndex),t+=_t;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=_t;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:nr.tag,lengthBytes:nr.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}nr.tag=Oo.E2ee;nr.lengthBytes=13;class wo extends Pu{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){const r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){const r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=Pm(e);let i,r,s=0;for(;t.byteLength-s>=_t+_t;){const a=t.getUint8(s);s+=_t;const o=t.getUint8(s);if(s+=_t,a!==nT)switch(a){case Oo.UserTimestamp:if(t.byteLength-s<tr.lengthBytes)throw Ln.malformedExt(a);i=new tr(t.getBigUint64(s)),s+=o;break;case Oo.E2ee:if(t.byteLength-s<nr.lengthBytes)throw Ln.malformedExt(a);const A=t.getUint8(s),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let d=s;d+=_t,d+=l*_t,c[l]=t.getUint8(d)}r=new nr(A,c),s+=o;break;default:if(t.byteLength-s<o)throw Ln.malformedExt(a);s+=o;break}}return[new wo({userTimestamp:i,e2ee:r}),t.byteLength]}toJSON(){var e,t,i,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(i=this.e2ee)===null||i===void 0?void 0:i.toJSON())!==null&&r!==void 0?r:null}}}const aC={from(n){return{payload:n.payload,extensions:new wo({userTimestamp:n.userTimestamp?new tr(n.userTimestamp):void 0})}},lossyIntoFrame(n){var e;return{payload:n.payload,userTimestamp:(e=n.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},oC=Symbol.for("lk.track"),AC=Symbol.for("lk.data-track");class cC{constructor(e,t,i){this.trackSymbol=oC,this.isLocal=!1,this.typeSymbol=AC,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e==null?void 0:e.signal,e==null?void 0:e.bufferSize),i=pe(t,2),r=i[0];return i[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class kc extends Pu{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=(t=e.extensions)!==null&&t!==void 0?t:new wo}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((sl+e)/4),i=t*4-sl-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:i}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let r=Gv;return t>0&&(r+=sl+t+i),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Sc.tooSmallForHeader();let t=Vv<<zv,i;switch(this.marker){case yt.Inter:i=Yv;break;case yt.Final:i=jv;break;case yt.Start:i=Wv;break;case yt.Single:i=Jv;break}t|=i<<qv;const r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<Xv);let A=0;if(e.setUint8(A,t),A+=_t,e.setUint8(A,0),A+=_t,e.setUint16(A,this.trackHandle),A+=Lr,e.setUint16(A,this.sequence.value),A+=Lr,e.setUint16(A,this.frameNumber.value),A+=Lr,e.setUint32(A,this.timestamp.asTicks()),A+=Kv,s>0){const l=a-1;e.setUint16(A,l),A+=Lr;const d=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+A));A+=d;for(let u=0;u<o;u+=1)e.setUint8(A,0),A+=_t}const c=this.toBinaryLengthBytes();if(A!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(A," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=Pm(e);if(t.byteLength<Gv)throw Ln.tooShort();let i=0;const r=t.getUint8(i);i+=_t;const s=r>>zv&$E;if(s>Vv)throw Ln.unsupportedVersion(s);let a;switch(r>>qv&eT){case Wv:a=yt.Start;break;case jv:a=yt.Final;break;case Jv:a=yt.Single;break;case Yv:default:a=yt.Inter;break}const o=(r>>Xv&tT)>0;i+=_t;let A;try{A=nE.fromNumber(t.getUint16(i))}catch(h){throw h instanceof _o&&(h.isReason(ka.Reserved)||h.isReason(ka.TooLarge))?Ln.invalidHandle(h):h}i+=Lr;const c=rr.u16(t.getUint16(i));i+=Lr;const l=rr.u16(t.getUint16(i));i+=Lr;const d=yo.fromRtpTicks(t.getUint32(i));i+=Kv;let u=new wo;if(o){if(t.byteLength-i<Lr)throw Ln.missingExtWords();let h=t.getUint16(i);i+=Lr;let m=4*(h+1)-sl;if(i+m>t.byteLength)throw Ln.headerOverrun();let v=new DataView(t.buffer,t.byteOffset+i,m);const w=wo.fromBinary(v),b=pe(w,2),k=b[0],y=b[1];u=k,i+=y}return[new kc({marker:a,trackHandle:A,sequence:c,frameNumber:l,timestamp:d,extensions:u}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var yt;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(yt||(yt={}));class Du extends Pu{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const i=this.header.toBinaryInto(e);if(t+=i,e.byteLength-t<this.payload.byteLength)throw Sc.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=_t;const r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){const t=Pm(e),i=kc.fromBinary(t),r=pe(i,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new Du(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const l0=si(mn.DataTracks);class Cr extends Hi{constructor(e,t,i,r){super(19,"Frame ".concat(i," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=fa[t],this.frameNumber=i}static interrupted(e,t){return new Cr("Interrupted by the start of a new frame ".concat(t),fa.Interrupted,e)}static unknownFrame(e){return new Cr("Initial packet was never received.",fa.UnknownFrame,e)}static bufferFull(e){return new Cr("Reorder buffer is full.",fa.BufferFull,e)}static incomplete(e,t,i){return new Cr("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),fa.Incomplete,e)}}var fa;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(fa||(fa={}));class Lu{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case yt.Single:return this.frameFromSingle(e,t);case yt.Start:return this.beginPartial(e,t);case yt.Inter:case yt.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==yt.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const r=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=r){const s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t!=null&&t.throwOnInterruption)throw Cr.interrupted(s,e.header.frameNumber.value);l0.warn("Data track frame ".concat(s," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==yt.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){const A=this.peekOldestPartialFrameNumber();if(typeof A!="number")break;if(this.partials.delete(A),t!=null&&t.throwOnInterruption)throw Cr.interrupted(A,s);l0.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(A," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==yt.Inter&&e.header.marker!==yt.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),Cr.unknownFrame(t);if(i.payloads.size>=Lu.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Cr.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&l0.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===yt.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const r=t.payloads.size;let s=0;for(const c of t.payloads.values())s+=c.length;const a=new Uint8Array(s);let o=t.startSequence.clone(),A=0;for(;;){const c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);const l=a.length-A;if(c.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(c.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(c,A),A+=c.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),Cr.incomplete(e,r,i-t.startSequence.value+1)}}Lu.MAX_BUFFER_PACKETS=128;var ma;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(ma||(ma={}));class Zn extends Hi{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=ma[t]}static unpublished(){return new Zn("The track has been unpublished and is no longer available",ma.Unpublished)}static timeout(){return new Zn("Request to subscribe to data track timed-out",ma.Timeout)}static disconnected(){return new Zn("Cannot subscribe to data track when disconnected",ma.Disconnected)}static cancelled(){return new Zn("Subscription to data track cancelled by caller",ma.Cancelled)}}const d0=si(mn.DataTracks);class iT{constructor(e){var t,i;const r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const s=new Lu;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return I(this,void 0,void 0,function*(){const t=this.depacketize(e);if(!t)return null;const i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(i){return d0.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return I(this,void 0,void 0,function*(){var t,i;const r=this.e2eeManager;if(!r)return e;const s=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!s)return d0.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return d0.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const vn=si(mn.DataTracks),rT=1e4,sT=16;class aT extends oi.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);if(!i){vn.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sT,r=null;const s=new fn,a=()=>{t==null||t.removeEventListener("abort",A)},o=()=>{if(a(),!r){vn.warn("ReadableStream subscribed to ".concat(e," was not started."));return}const l=this.descriptors.get(e);if(!l){vn.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(l.subscription.type!=="active"){vn.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}l.subscription.streamControllers.delete(r),l.subscription.streamControllers.size===0&&this.unSubscribeRequest(l.info.sid)},A=()=>{var l;if(!r)return;const d=this.descriptors.get(e);(d==null?void 0:d.subscription.type)==="active"&&d.subscription.streamControllers.delete(r),r.error(Zn.cancelled()),(l=s.reject)===null||l===void 0||l.call(s,Zn.cancelled()),o()};return[new ReadableStream({start:l=>{r=l,this.subscribeRequest(e,t).then(()=>I(this,void 0,void 0,function*(){var d,u,h;const p=this.descriptors.get(e);if(!p){vn.error("Unknown track ".concat(e));const m=Zn.disconnected();l.error(m),(d=s.reject)===null||d===void 0||d.call(s,m);return}if(p.subscription.type!=="active"){vn.error("Subscription for track ".concat(e," is not active"));const m=Zn.disconnected();l.error(m),(u=s.reject)===null||u===void 0||u.call(s,m);return}if(t!=null&&t.aborted){A();return}t==null||t.addEventListener("abort",A),p.subscription.streamControllers.set(l,a),(h=s.resolve)===null||h===void 0||h.call(s)})).catch(d=>{var u;l.error(d),(u=s.reject)===null||u===void 0||u.call(s,d)})},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:i})),s.promise]}subscribeRequest(e,t){return I(this,void 0,void 0,function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const r=(s,a,o)=>I(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));const A=iC([a,o].filter(d=>typeof d<"u")),c=new fn;s.subscription.completionFuture.promise.then(()=>{var d;return(d=c.resolve)===null||d===void 0?void 0:d.call(c)}).catch(d=>{var u;return(u=c.reject)===null||u===void 0?void 0:u.call(c,d)});const l=()=>{var d;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o!=null&&o.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(d=c.reject)===null||d===void 0||d.call(c,Zn.cancelled())}};A.aborted&&l(),A.addEventListener("abort",l),yield c.promise,A.removeEventListener("abort",l)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new fn,pendingRequestCount:1,cancel:()=>{var a,o;const A=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),A.type==="pending"&&((o=(a=A.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?Zn.timeout():Zn.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const s=rC(rT);yield r(i,t,s);return}case"pending":{i.subscription.pendingRequestCount+=1,yield r(i,t);return}case"active":return}})}querySubscribed(){return I(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){vn.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);const r=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var i=pe(r,2);const s=i[0],a=i[1];a();try{s.close()}catch(o){vn.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return I(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const s of e.entries()){var i=pe(s,2);const a=i[0],o=i[1],A=new Set;for(const c of o)A.add(c.sid),!this.descriptors.has(c.sid)&&(yield this.handleTrackPublished(a,c));t.set(a,A)}for(const s of t.entries()){var r=pe(s,2);const a=r[0],o=r[1];let c=Array.from(this.descriptors.entries()).filter(l=>{let d=pe(l,2);return d[0],d[1].publisherIdentity===a}).map(l=>pe(l,1)[0]).filter(l=>!o.has(l));for(const l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return I(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return I(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){vn.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);const r=new cC(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){vn.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=pe(i,2);const r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var i,r;const s=this.descriptors.get(t);if(!s){vn.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{vn.warn("No subscription for ".concat(t));return}case"active":{s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{const a=new iT({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}}}packetReceived(e){return I(this,void 0,void 0,function*(){let t;try{var i=Du.fromBinary(e),r=pe(i,1);t=r[0]}catch(A){vn.error("Failed to deserialize packet: ".concat(A));return}const s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){vn.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(s);if(!a){vn.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){vn.warn("Received packet for track ".concat(s," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const A of a.subscription.streamControllers.keys()){if(A.desiredSize!==null&&A.desiredSize<=0){vn.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(A.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const c=aC.lossyIntoFrame(o);A.enqueue(c)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=pe(t,2);const i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(i=(t=r.subscription.completionFuture).reject)===null||i===void 0||i.call(t,Zn.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,Zn.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Ru extends Hi{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Nd[t]}static mtuTooShort(){return new Ru("MTU is too short to send frame",Nd.MtuTooShort)}}var Nd;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(Nd||(Nd={}));class Nm{constructor(e,t){this.sequence=rr.u16(0),this.frameNumber=rr.u16(0),this.clock=ha.rtpStartingNow(yo.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?yt.Single:e===0?yt.Start:e===t-1?yt.Final:yt.Inter}*packetize(e,t){var i;const r=this.frameNumber.getThenIncrement(),s={marker:yt.Inter,trackHandle:this.handle,sequence:rr.u16(0),frameNumber:r,timestamp:(i=t==null?void 0:t.now)!==null&&i!==void 0?i:this.clock.now(),extensions:e.extensions},a=new kc(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Ru.mtuTooShort();const o=this.mtuSizeBytes-a,A=Math.ceil(e.payload.byteLength/o);for(let l=0,d=0;d<e.payload.byteLength;c=[l+1,d+o],l=c[0],d=c[1],c){var c;const u=this.sequence.getThenIncrement(),h=new kc(Object.assign(Object.assign({},s),{marker:Nm.computeFrameMarker(l,A),sequence:u})),p=Math.min(o,e.payload.byteLength-d),m=new Uint8Array(e.payload.buffer,e.payload.byteOffset+d,p);yield new Du(h,m)}}}var ji;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled",n[n.InvalidName=6]="InvalidName",n[n.Unknown=7]="Unknown"})(ji||(ji={}));class on extends Hi{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=ji[t],this.rawMessage=i==null?void 0:i.rawMessage}static notAllowed(e){return new on("Data track publishing unauthorized",ji.NotAllowed,{rawMessage:e})}static duplicateName(e){return new on("Track name already taken",ji.DuplicateName,{rawMessage:e})}static invalidName(e){return new on("Track name is invalid",ji.InvalidName,{rawMessage:e})}static timeout(){return new on("Publish data track timed-out. Does the LiveKit server support data tracks?",ji.Timeout)}static limitReached(e){return new on("Data track publication limit reached",ji.LimitReached,{rawMessage:e})}static unknown(e,t){return new on("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),ji.Unknown)}static disconnected(){return new on("Room disconnected",ji.Disconnected)}static cancelled(){return new on("Publish data track cancelled by caller",ji.Cancelled)}}var tc;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(tc||(tc={}));class Is extends Hi{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=tc[t]}static trackUnpublished(){return new Is("Track is no longer published",tc.TrackUnpublished)}static dropped(e){return new Is("Frame was dropped",tc.Dropped,{cause:e})}}var nc;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(nc||(nc={}));class Ec extends Hi{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=nc[t]}static packetizer(e){return new Ec("Error packetizing frame",nc.Packetizer,{cause:e})}static encryption(e){return new Ec("Error encrypting frame",nc.Encryption,{cause:e})}}class _u{constructor(e,t){this.trackSymbol=oC,this.isLocal=!0,this.typeSymbol=AC,this.handle=null,this.log=Te,this.flushedFuture=new fn,this.isFlushed=!0,this.handleManagerReset=()=>{var i,r;(r=(i=this.flushedFuture).resolve)===null||r===void 0||r.call(i),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=i=>{var r,s;this.isFlushed=i.isFlushed,i.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new fn)},this.options=e,this.manager=t,this.log=si(mn.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const r=new _u(e,t);return r.handle=i,r}get info(){const e=this.descriptor;if((e==null?void 0:e.type)==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return I(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw Is.trackUnpublished();const t=aC.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(i){throw i}}flush(){return I(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return I(this,void 0,void 0,function*(){if(!this.handle){Te.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class Ou{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Nm(e.info.pubHandle,Ou.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return _7(this,arguments,function*(){const i=yield Lo(this.encryptIfNeeded(e));try{yield Lo(yield*O7($i(this.packetizer.packetize(i))))}catch(r){throw r instanceof Ru?Ec.packetizer(r):r}})}encryptIfNeeded(e){return I(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Ec.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new nr(t.keyIndex,t.iv),e})}}Ou.TRANSPORT_MTU_BYTES=16e3;const pr=si(mn.DataTracks),Zv={pending(){return{type:"pending",completionFuture:new fn}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new Ou({info:n,e2eeManager:e}),unpublishingFuture:new fn}}},oT=1e4;class Hm extends oi.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new iE,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new Hm;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return I(this,void 0,void 0,function*(){var i,r,s,a,o;const A=this.getDescriptor(e);if((A==null?void 0:A.type)!=="active"||A.publishState==="unpublished")throw Is.trackUnpublished();if(A.publishState==="republishing")throw Is.dropped("Data track republishing");try{try{for(var c=!0,l=$i(A.pipeline.processFrame(t)),d;d=yield l.next(),i=d.done,!i;c=!0){a=d.value,c=!1;const u=a,h=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,h+1),h===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:u.toBinary()})}}catch(u){r={error:u}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(u){throw Is.dropped(u)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(pr.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return I(this,void 0,void 0,function*(){const i=this.handleAllocator.get();if(!i)throw on.limitReached();const r=rC(oT),s=t?iC([t,r]):r;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const a=Zv.pending();this.descriptors.set(i,a);const o=()=>{var A,c;const l=this.descriptors.get(i);if(!l){pr.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),l.type==="pending"&&((c=(A=l.completionFuture).reject)===null||c===void 0||c.call(A,r.aborted?on.timeout():on.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>i)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:_u.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return I(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){pr.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){pr.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,r,s,a;const o=this.descriptors.get(e);if(!o){pr.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const A=t.data,c=A.usesE2ee?this.e2eeManager:null;this.descriptors.set(A.pubHandle,Zv.active(A,c)),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}else(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){pr.warn("Track ".concat(e," already active"));return}if(t.type==="error"){pr.warn("Republish failed for track ".concat(e));return}pr.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;const r=this.descriptors.get(e);if(!r){pr.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){pr.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(i=(t=r.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(const r of this.descriptors.entries()){var i=pe(r,2);const s=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,on.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return I(this,void 0,void 0,function*(){var e,t,i,r;this.handleAllocator.reset();for(const s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,on.disconnected());break;case"active":(r=(i=s.unpublishingFuture).resolve)===null||r===void 0||r.call(i),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class tt extends Error{constructor(e,t,i,r){super(t),this.code=e,this.message=$v(t,tt.MAX_MESSAGE_BYTES),this.data=i?$v(i,tt.MAX_DATA_BYTES):void 0,typeof(r==null?void 0:r.cause)<"u"&&(this.cause=r==null?void 0:r.cause)}static fromProto(e){return new tt(e.code,e.message,e.data)}toProto(){return new P4({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new tt(tt.ErrorCode[e],tt.ErrorMessage[e],t,i)}}tt.MAX_MESSAGE_BYTES=256;tt.MAX_DATA_BYTES=15360;tt.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};tt.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 lC=15360,dC="lk.rpc_request",uC="lk.rpc_response";var yn;(function(n){n.RPC_REQUEST_ID="lk.rpc_request_id",n.RPC_REQUEST_METHOD="lk.rpc_request_method",n.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",n.RPC_REQUEST_VERSION="lk.rpc_request_version"})(yn||(yn={}));const AT=1,hC=2;function Km(n){return new TextEncoder().encode(n).length}function $v(n,e){if(Km(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}class cT extends oi.EventEmitter{constructor(e,t,i,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=r}performRpc(e){return I(this,arguments,void 0,function(t){var i=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,A=o===void 0?15e3:o;return function*(){const d=i.getRemoteParticipantClientProtocol(r);if(Km(a)>lC&&d<Qd)throw tt.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const h=i.getServerVersion();if(h&&Er(h,"1.8.0")<0)throw tt.builtIn("UNSUPPORTED_SERVER");const p=Math.max(A,8e3),m=crypto.randomUUID(),v=new fn;let w=null;const b=setTimeout(()=>{var y;i.pendingAcks.delete(m),(y=v.reject)===null||y===void 0||y.call(v,tt.builtIn("CONNECTION_TIMEOUT")),i.pendingResponses.delete(m),w!==null&&clearTimeout(w)},7e3);i.pendingAcks.set(m,{resolve:()=>{clearTimeout(b)},participantIdentity:r}),i.pendingResponses.set(m,{completionFuture:v,participantIdentity:r}),yield i.publishRpcRequest(r,m,s,a,p,d),w=setTimeout(()=>{var y;i.pendingResponses.delete(m),(y=v.reject)===null||y===void 0||y.call(v,tt.builtIn("RESPONSE_TIMEOUT"))},A);const k=v.promise.finally(()=>{clearTimeout(w),i.pendingAcks.has(m)&&(i.log.warn("RPC response received before ack",m),i.pendingAcks.delete(m),clearTimeout(b))});return[m,k]}()})}publishRpcRequest(e,t,i,r,s,a){return I(this,void 0,void 0,function*(){if(a>=Qd){const o=yield this.outgoingDataStreamManager.streamText({topic:dC,destinationIdentities:[e],attributes:{[yn.RPC_REQUEST_ID]:t,[yn.RPC_REQUEST_METHOD]:i,[yn.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[yn.RPC_REQUEST_VERSION]:"".concat(hC)}});yield o.write(r),yield o.close();return}this.emit("sendDataPacket",{packet:new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcRequest",value:new fm({id:t,method:i,payload:r,responseTimeoutMs:s,version:AT})}})})})}handleIncomingDataStream(e,t,i){return I(this,void 0,void 0,function*(){const r=i[yn.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(yn.RPC_REQUEST_ID," not set."));return}const s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(r,tt.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).resolve)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).reject)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var i=pe(a,2);const o=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var r=pe(a,2);const o=r[0];var s=r[1];const A=s.participantIdentity,c=s.completionFuture;A===e&&((t=c.reject)===null||t===void 0||t.call(c,tt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class lT extends oi.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return I(this,void 0,void 0,function*(){var i;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,tt.builtIn("UNSUPPORTED_VERSION"));return}const r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,tt.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof tt?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=tt.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((i=a==null?void 0:a.message)!==null&&i!==void 0?i:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,i){return I(this,void 0,void 0,function*(){const r=i[yn.RPC_REQUEST_ID],s=i[yn.RPC_REQUEST_METHOD],a=parseInt(i[yn.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[yn.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(yn.RPC_REQUEST_ID," / ").concat(yn.RPC_REQUEST_METHOD," / ").concat(yn.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(yn.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,tt.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),o!==hC){this.publishRpcResponsePacket(t,r,null,tt.builtIn("UNSUPPORTED_VERSION"));return}let A;try{A=yield e.readAll()}catch(d){this.log.warn("Error reading RPC request payload: ".concat(d)),this.publishRpcResponsePacket(t,r,null,tt.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:d}));return}const c=this.rpcHandlers.get(s);if(!c){this.publishRpcResponsePacket(t,r,null,tt.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:A,responseTimeout:a})}catch(d){let u;d instanceof tt?u=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),d),u=tt.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,u);return}yield this.publishRpcResponse(t,r,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcAck",value:new Eu({requestId:t})}})})}publishRpcResponsePacket(e,t,i,r){this.emit("sendDataPacket",{packet:new En({destinationIdentities:[e],kind:Fs.RELIABLE,value:{case:"rpcResponse",value:new mm({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}})})}publishRpcResponse(e,t,i){return I(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Qd){const a=yield this.outgoingDataStreamManager.streamText({topic:uC,destinationIdentities:[e],attributes:{[yn.RPC_REQUEST_ID]:t}});yield a.write(i),yield a.close();return}if(Km(i)>lC){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,tt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class dT extends W3{constructor(e,t,i,r,s,a){super(e,t,H.Kind.Audio,i,a),this.monitorReceiver=()=>I(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=Qu(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;ar()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ar())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return I(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(zp(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&zp(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(J.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(J.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return I(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})}}class qr extends oi.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=At.NONE,this.log=Te,this.handleMuted=()=>{this.emit(J.Muted)},this.handleUnmuted=()=>{this.emit(J.Unmuted)},this.log=si((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:mn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=H.Source.Unknown}setTrack(e){this.track&&(this.track.off(J.Muted,this.handleMuted),this.track.off(J.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(J.Muted,this.handleMuted),e.on(J.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),De(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==At.NONE}get audioTrack(){if(Sr(this.track))return this.track}get videoTrack(){if(as(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=H.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===H.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(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={}))})(qr||(qr={}));class Zp extends qr{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(J.Ended)},this.handleCpuConstrained=()=>{this.track&&as(this.track)&&this.emit(J.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(J.Ended,this.handleTrackEnded),this.track.off(J.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(J.Ended,this.handleTrackEnded),e.on(J.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 I(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return I(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return I(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return I(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Sr(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(hn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(hn.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(hn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(hn.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(hn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(hn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Nu(n,e){return I(this,void 0,void 0,function*(){n??(n={});let t=!1;const i=H3(n),r=i.audioProcessor,s=i.videoProcessor,a=i.optionsWithoutProcessor;let o=a.audio,A=a.video;if(r&&typeof a.audio=="object"&&(a.audio.processor=r),s&&typeof a.video=="object"&&(a.video.processor=s),n.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const u=a.audio.deviceId;a.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:u}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const u=a.video.deviceId;a.video.deviceId={exact:u},t=!0,A=Object.assign(Object.assign({},a.video),{deviceId:{ideal:u}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const c=_3(a,Y3,J3),l=Em(c),d=navigator.mediaDevices.getUserMedia(l);a.audio&&(pn.userMediaPromiseMap.set("audioinput",d),d.catch(()=>pn.userMediaPromiseMap.delete("audioinput"))),a.video&&(pn.userMediaPromiseMap.set("videoinput",d),d.catch(()=>pn.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>I(this,void 0,void 0,function*(){const p=h.kind==="audio";let m;const v=p?l.audio:l.video;typeof v!="boolean"&&(m=v);const w=h.getSettings().deviceId;m!=null&&m.deviceId&&Sa(m.deviceId)!==w?m.deviceId=w:m||(m={deviceId:w});const b=kE(h,m,e);return b.kind===H.Kind.Video?b.source=H.Source.Camera:b.kind===H.Kind.Audio&&(b.source=H.Source.Microphone),b.mediaStream=u,Sr(b)&&r?yield b.setProcessor(r):as(b)&&s&&(yield b.setProcessor(s)),b})))}catch(u){if(!t)throw u;return Nu(Object.assign(Object.assign({},n),{audio:o,video:A}),e)}})}function uT(n){return I(this,void 0,void 0,function*(){return(yield Nu({audio:!1,video:!0}))[0]})}function hT(n){return I(this,void 0,void 0,function*(){return(yield Nu({audio:!0,video:!1}))[0]})}var xs;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(xs||(xs={}));function pT(n){switch(n){case FA.EXCELLENT:return xs.Excellent;case FA.GOOD:return xs.Good;case FA.POOR:return xs.Poor;case FA.LOST:return xs.Lost;default:return xs.Unknown}}class pC extends oi.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===vc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===ho.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:vc.STANDARD;var A;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=xs.Unknown,this.log=Te,this.loggerOptions=a,this.log=si((A=a==null?void 0:a.loggerName)!==null&&A!==void 0?A:mn.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const i of this.trackPublications){var t=pe(i,2);const r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(const i of this.trackPublications){var t=pe(i,2);const r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new fn,this.once($.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(H.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(H.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(H.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var 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===ho.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==ho.ACTIVE&&this.emit($.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($.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit($.ParticipantNameChanged,e)}_setAttributes(e){const t=u8(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit($.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const A=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,d)=>{var u;return l!==((u=this.permissions)===null||u===void 0?void 0:u.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit($.ParticipantPermissionsChanged,A),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit($.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=pT(e),t!==this._connectionQuality&&this.emit($.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=>Sr(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(J.Muted,()=>{this.emit($.TrackMuted,e)}),e.on(J.Unmuted,()=>{this.emit($.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case H.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case H.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function fT(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 X4({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 mT extends pC{constructor(e,t,i,r,s,a,o,A){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=At.NONE,this.e2eeStateMutex=new bn,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new fn)},this.handleReconnected=()=>{var c,l;(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.resolve)===null||l===void 0||l.call(c),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var c,l,d,u,h,p;this.reconnectFuture&&(this.reconnectFuture.promise.catch(m=>this.log.warn(m.message)),(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.reject)===null||l===void 0||l.call(c,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(d=this.signalConnectedFuture).reject)===null||u===void 0||u.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(p=(h=this.activeAgentFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=c=>{var l,d;c.participant&&this.updateInfo(c.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new fn),(d=(l=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(l)},this.handleSignalRequestResponse=c=>{const l=c.requestId,d=c.reason,u=c.message,h=this.pendingSignalRequests.get(l);switch(h&&(d!==ua.OK&&h.reject(new lv(u,d)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let p;switch(c.reason){case ua.NOT_ALLOWED:p=on.notAllowed(c.message);break;case ua.DUPLICATE_NAME:p=on.duplicateName(c.message);break;case ua.INVALID_NAME:p=on.invalidName(c.message);break;case ua.LIMIT_EXCEEDED:p=on.limitReached(c.message);break;default:p=on.unknown(c.reason,c.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(c.request.value.pubHandle,{type:"error",error:p});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(c=>fT(c)))},this.onTrackUnmuted=c=>{this.onTrackMuted(c,c.isUpstreamPaused)},this.onTrackMuted=(c,l)=>{if(l===void 0&&(l=!0),!c.sid){this.log.error("could not update mute status for unpublished track",De(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",De(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",De(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{const l=this.audioTrackPublications.get(c.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(c.sid));return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(c,l)=>{this.log.debug("track cpu constrained",De(l)),this.emit($.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>I(this,void 0,void 0,function*(){var l,d,u,h,p;if(!(!((p=this.roomOptions)===null||p===void 0)&&p.dynacast))return;const m=this.videoTrackPublications.get(c.trackSid);if(!m){this.log.warn("received subscribed quality update for unknown track",{trackSid:c.trackSid});return}if(!m.videoTrack)return;const v=yield m.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var w=!0,b=$i(v),k;k=yield b.next(),l=k.done,!l;w=!0){h=k.value,w=!1;const y=h;o8(y)&&(this.log.debug("publish ".concat(y," for ").concat(m.videoTrack.sid),De(m)),yield this.publishAdditionalCodecForTrack(m.videoTrack,y,m.options))}}catch(y){d={error:y}}finally{try{!w&&!l&&(u=b.return)&&(yield u.call(b))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=c=>{const l=this.trackPublications.get(c.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",{trackSid:c.trackSid});return}this.unpublishTrack(l.track)},this.handleTrackEnded=c=>I(this,void 0,void 0,function*(){if(c.source===H.Source.ScreenShare||c.source===H.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",De(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(Nr(c)||hr(c))try{if(ti())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:c.source===H.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),De(c)),l.onchange=()=>{l.state!=="denied"&&(c.isMuted||c.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}c.isMuted||(this.log.debug("track ended, attempting to use a different device",De(c)),Nr(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",De(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==At.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(q.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(q.Connected,this.handleReconnected).on(q.SignalConnected,this.handleSignalConnected).on(q.SignalRestarted,this.handleReconnected).on(q.SignalResumed,this.handleReconnected).on(q.Restarting,this.handleReconnecting).on(q.Resuming,this.handleReconnecting).on(q.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(q.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(q.Closing,this.handleClosing).on(q.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return I(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return I(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return I(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return I(this,arguments,void 0,function(t){var i=this;let r=t.metadata,s=t.name,a=t.attributes;return function*(){return new Rn((o,A)=>I(i,void 0,void 0,function*(){var c,l;try{let d=!1;const u=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(l=s??this.name)!==null&&l!==void 0?l:"",a),h=performance.now();for(this.pendingSignalRequests.set(u,{resolve:o,reject:p=>{A(p),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-h<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(p=>{let m=pe(p,2),v=m[0],w=m[1];return this.attributes[v]===w||w===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(u),o();return}yield In(50)}A(new lv("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error?A(d):A(new Error(String(d)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(H.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(H.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(H.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return I(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?At.GCM:At.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(i=>i.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,r){return I(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let d;if(this.pendingPublishing.has(e)){const u=yield this.waitForPendingPublicationOfSource(e);return u||this.log.info("waiting for pending publication promise timed out",{source:e}),yield u==null?void 0:u.unmute(),u}this.pendingPublishing.add(e);try{switch(e){case H.Source.Camera:d=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case H.Source.Microphone:d=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case H.Source.ScreenShare:d=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Xr(e)}}catch(u){throw d==null||d.forEach(h=>{h.stop()}),u instanceof Error&&this.emit($.MediaDevicesError,u,Kp(e)),this.pendingPublishing.delete(e),u}for(const u of d){const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===H.Source.Microphone&&Sr(u)&&h.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),u.startPreConnectBuffer())}try{const u=[];for(const p of d)this.log.info("publishing track",De(p)),u.push(this.publishTrack(p,r));const h=yield Promise.all(u);var A=pe(h,1);o=A[0]}catch(u){throw d==null||d.forEach(h=>{h.stop()}),u}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",{source:e})),o&&o.track)if(e===H.Source.ScreenShare){const d=[this.unpublishTrack(o.track)],u=this.getTrackPublication(H.Source.ScreenShareAudio);u&&u.track&&d.push(this.unpublishTrack(u.track));var c=yield Promise.all(d),l=pe(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return I(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(H.Source.Camera)||this.pendingPublishing.has(H.Source.Microphone))){this.pendingPublishing.add(H.Source.Camera),this.pendingPublishing.add(H.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(H.Source.Camera),this.pendingPublishing.delete(H.Source.Microphone)}}})}createTracks(e){return I(this,void 0,void 0,function*(){var t,i;e??(e={});const r=_3(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 Nu(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Sr(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=H.Source.Microphone,this.emit($.AudioStreamAcquired)),as(o)&&(this.cameraError=void 0,o.source=H.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return I(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Sm("getDisplayMedia not supported");e.resolution===void 0&&!C8()&&(e.resolution=km.h1080fps30.resolution);const t=c8(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new Xr("no video track found");const s=new Od(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=H.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit($.AudioStreamAcquired);const o=new Rd(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=H.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return I(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,i)=>{const r=()=>{clearTimeout(o),this.engine.off(q.Restarted,s),this.engine.off(q.Closing,a)},s=()=>{r(),t()},a=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),i(new Error("timed out waiting for engine restart"))},e);this.engine.once(q.Restarted,s),this.engine.once(q.Closing,a)})}publishOrRepublishTrack(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return function*(){var A,c,l,d;Nr(i)&&i.setAudioContext(s.audioContext),yield(A=s.reconnectFuture)===null||A===void 0?void 0:A.promise,s.republishPromise&&!a&&(yield s.republishPromise),go(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case H.Source.Microphone:b="audioinput";break;case H.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Rd(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Od(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Xr("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",De(h)),h;const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),m="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=p.forceStereo)!==null&&c!==void 0?c:m;v&&(p.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",De(i)),p.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=p.dtx)!==null&&l!==void 0||(p.dtx=!1),(d=p.red)!==null&&d!==void 0||(p.red=!1)),!x8()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),p.simulcast=!1),p.source&&(i.source=p.source);const w=new Promise((b,k)=>I(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==st.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:De(i)});let y=!1;const B=setTimeout(()=>{y=!0,i.stop(),k(new cv("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(B),y)return;const E=yield this.publish(i,p,v);b(E)}else try{const y=yield this.publish(i,p,v);b(y)}catch(y){k(y)}}catch(y){k(y)}}));s.pendingPublishPromises.set(i,w);try{return yield w}catch(b){if(!o&&b instanceof xa)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:b}),s.pendingPublishPromises.delete(i),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(i,r,a,!0);throw b}finally{s.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new fn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",De(e)),!1;const t=this.permissions,i=t.canPublish,r=t.canPublishSources;return i&&(r.length===0||r.map(s=>h8(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",De(e)),!1)}publish(e,t,i){return I(this,void 0,void 0,function*(){var r,s,a,o,A,c,l,d,u,h;if(!this.hasPermissionsToPublish(e))throw new cv("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(D=>go(e)&&D.source===e.source)&&e.source!==H.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),De(e)),t.stopMicTrackOnMute&&Sr(e)&&(e.stopOnMute=!0),e.source===H.Source.ScreenShare&&Qa()&&(t.simulcast=!1),t.videoCodec==="av1"&&!v8()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!y8()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Yp),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(D=>t.videoCodec===ZA(D.mime))||(t.videoCodec=ZA(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(J.Muted,this.onTrackMuted),e.on(J.Unmuted,this.onTrackUnmuted),e.on(J.Ended,this.handleTrackEnded),e.on(J.UpstreamPaused,this.onTrackUpstreamPaused),e.on(J.UpstreamResumed,this.onTrackUpstreamResumed),e.on(J.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],w=!(!((r=t.dtx)!==null&&r!==void 0)||r),b=e.getSourceTrackSettings();b.autoGainControl&&v.push(hn.TF_AUTO_GAIN_CONTROL),b.echoCancellation&&v.push(hn.TF_ECHO_CANCELLATION),b.noiseSuppression&&v.push(hn.TF_NOISE_SUPPRESSION),b.channelCount&&b.channelCount>1&&v.push(hn.TF_STEREO),w&&v.push(hn.TF_NO_DTX),Nr(e)&&e.hasPreConnectBuffer&&v.push(hn.TF_PRECONNECT_BUFFER);const k=this.normalizeRequestedFrameMetadataOptions(e,t),y=new yc({cid:e.mediaStreamTrack.id,name:t.name,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),disableDtx:w,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:v,packetTrailerFeatures:k});let B;if(e.kind===H.Kind.Video){let D;try{D=yield e.waitForDimensions()}catch{const N=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:wc.h720.resolution;D={width:N.width,height:N.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},De(e)),{dims:D}))}y.width=D.width,y.height=D.height,hr(e)&&(er(m)&&(e.source===H.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",De(e)))),t.scalabilityMode=(A=t.scalabilityMode)!==null&&A!==void 0?A:"L3T3_KEY"),y.simulcastCodecs=[new Ip({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Yp}),t.backupCodec&&m!==t.backupCodec.codec&&y.encryption===At.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new Ip({codec:t.backupCodec.codec,cid:""})))),B=_d(e.source===H.Source.ScreenShare,y.width,y.height,t),y.layers=Dv(y.width,y.height,B,er(t.videoCodec))}else e.kind===H.Kind.Audio&&(B=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&d!==void 0?d:"high",networkPriority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Mt("cannot publish track when not connected");const E=()=>I(this,void 0,void 0,function*(){var D,O,N;if(!this.engine.pcManager)throw new Mt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,B),hr(e)&&(e.publishOptions=t),this.emit($.LocalSenderCreated,e.sender,e),hr(e)&&((D=t.degradationPreference)!==null&&D!==void 0||(t.degradationPreference=DE(e)),e.setDegradationPreference(t.degradationPreference)),B)if(Qa()&&e.kind===H.Kind.Audio){let j;for(const V of this.engine.pcManager.publisher.getTransceivers())if(V.sender===e.sender){j=V;break}j&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:j,codec:"opus",maxbr:!((O=B[0])===null||O===void 0)&&O.maxBitrate?B[0].maxBitrate/1e3:0})}else e.codec&&er(e.codec)&&(!((N=B[0])===null||N===void 0)&&N.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:B[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const F=new Promise((D,O)=>I(this,void 0,void 0,function*(){var N;try{T=yield this.engine.addTrack(y),D(T)}catch(j){if(e.sender&&(!((N=this.engine.pcManager)===null||N===void 0)&&N.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(V){this.log.error(V)}yield this.engine.negotiate().catch(V=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},De(e)),{error:V}))})}O(j)}}));if(this.enabledPublishVideoCodecs.length>0&&k.length===0)T=(yield Promise.all([F,E()]))[0];else{T=yield F;let D;if(T.codecs.forEach(O=>{D===void 0&&(D=O.mimeType)}),D&&e.kind===H.Kind.Video){const O=ZA(D);O!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},De(e)),{codec:O})),t.videoCodec=O,B=_d(e.source===H.Source.ScreenShare,y.width,y.height,t))}yield E()}const L=new Zp(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(L.on(J.CpuConstrained,D=>this.onTrackCpuConstrained(D,L)),L.options=t,e.sid=T.sid,hr(e)&&(e.publishOptions=t,y.width&&y.height&&(e.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:B,trackInfo:T}),hr(e)?e.startMonitor(this.engine.client):Nr(e)&&e.startMonitor(),this.addTrackPublication(L),this.emit($.LocalTrackPublished,L),Nr(e)&&T.audioFeatures.includes(hn.TF_PRECONNECT_BUFFER)){const D=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on($.LocalTrackSubscribed,N=>{if(N.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",De(e)),e.stopPreConnectBuffer()}}),D&&new Promise((j,V)=>I(this,void 0,void 0,function*(){var te,xe,ae,Ie,Ee,Pe;try{this.log.debug("waiting for agent",De(e));const ke=setTimeout(()=>{V(new Error("agent not active within 10 seconds"))},1e4),ze=yield this.waitUntilActiveAgentPresent();clearTimeout(ke),this.log.debug("sending preconnect buffer",De(e));const ht=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ze.identity],attributes:{trackId:L.trackSid,sampleRate:String((Ee=b.sampleRate)!==null&&Ee!==void 0?Ee:"48000"),channels:String((Pe=b.channelCount)!==null&&Pe!==void 0?Pe:"1")}});try{for(var ne=!0,we=$i(D),Le;Le=yield we.next(),te=Le.done,!te;ne=!0){Ie=Le.value,ne=!1;const Wt=Ie;yield ht.write(Wt)}}catch(Wt){xe={error:Wt}}finally{try{!ne&&!te&&(ae=we.return)&&(yield ae.call(we))}finally{if(xe)throw xe.error}}yield ht.close(),j()}catch(ke){V(ke)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",De(e))}).catch(j=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},De(e)),{error:j}))})}return L})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||xc((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const r=(i=t.frameMetadata)!==null&&i!==void 0?i:t.packetTrailer;if(e.kind!==H.Kind.Video||!Dd(r))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),De(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const s=W8(r),a=j8(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return I(this,void 0,void 0,function*(){var r;if(this.encryptionType!==At.NONE)return;let s;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(s=p)}),!s)throw new Xr("track is not published");if(!hr(e))throw new Xr("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=Z3(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",De(e));return}const A=e.addSimulcastTrack(t,o);if(!A)return;const c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new yc({cid:A.mediaStreamTrack.id,type:H.kindToProto(e.kind),muted:e.isMuted,source:H.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:A.mediaStreamTrack.id}]});if(l.layers=Dv(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Mt("cannot publish track when not connected");const d=()=>I(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,A,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:h})})}unpublishTrack(e,t){return I(this,void 0,void 0,function*(){var i,r;if(go(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",De(e)),yield l)}const s=this.getPublicationForTrack(e),a=s?De(s):void 0;if(this.log.info("unpublishing track",a),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=s.track,e.off(J.Muted,this.onTrackMuted),e.off(J.Unmuted,this.onTrackUnmuted),e.off(J.Ended,this.handleTrackEnded),e.off(J.UpstreamPaused,this.onTrackUpstreamPaused),e.off(J.UpstreamResumed,this.onTrackUpstreamResumed),e.off(J.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const A=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ut.FAILED&&A)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===A&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(A)}catch(l){this.log.warn(l),o=!0}if(hr(e)){for(const l of e.simulcastCodecs){var c=pe(l,2);const d=c[1];if(d.sender){try{o=this.engine.removeTrack(d.sender)}catch(u){this.log.warn(u),o=!0}d.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case H.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case H.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit($.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return I(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Rn((s,a)=>I(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(A=>{A.track&&(t&&(A.options=Object.assign(Object.assign({},A.options),t)),o.push(A))}),yield Promise.all(o.map(A=>I(this,void 0,void 0,function*(){const c=A.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==H.Source.ScreenShare&&c.source!==H.Source.ScreenShareAudio&&(Nr(c)||hr(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",{track:A.trackSid}),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,A.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return I(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?Me.RELIABLE:Me.LOSSY,a=r.reliable?Fs.RELIABLE:Fs.LOSSY,o=r.destinationIdentities,A=r.topic;let c=new pm({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:A});const l=new En({kind:a,value:{case:"user",value:c}});yield i.engine.sendDataPacket(l,s)}()})}publishDtmf(e,t){return I(this,void 0,void 0,function*(){const i=new En({kind:Fs.RELIABLE,value:{case:"sipDtmf",value:new Q4({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Me.RELIABLE)})}sendChatMessage(e,t){return I(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new En({value:{case:"chatMessage",value:new Id(Object.assign(Object.assign({},i),{timestamp:bt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Me.RELIABLE),this.emit($.ChatMessage,i),i})}editChatMessage(e,t){return I(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new En({value:{case:"chatMessage",value:new Id(Object.assign(Object.assign({},i),{timestamp:bt.parse(i.timestamp),editTimestamp:bt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Me.RELIABLE),this.emit($.ChatMessage,i),i})}sendText(e,t){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return I(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let i=pe(t,2);return i[0],i[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},De(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,r,s;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):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new fn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Nr(r)||hr(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return I(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>pe(s,1)[0].source===e);if(r)return r[1];yield In(20)}})}publishDataTrack(e){return I(this,void 0,void 0,function*(){const t=new _u(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class e2 extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class gT extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,r;super.set(e,t);const s=(i=this.pending)===null||i===void 0?void 0:i.get(e);if(s){for(const a of s)a.isResolved||(r=a.resolve)===null||r===void 0||r.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return I(this,void 0,void 0,function*(){const i=this.get(e);if(typeof i<"u")return i;if(t!=null&&t.aborted)throw new e2("The operation was aborted.",t.reason);const r=new fn(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){const a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new e2("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}}class vT extends qr{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(J.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Mu({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new D4({participantSid:"",trackSids:[this.trackSid]})]});this.emit(J.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?qr.SubscriptionStatus.Unsubscribed:super.isSubscribed?qr.SubscriptionStatus.Subscribed:qr.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?qr.PermissionStatus.Allowed:qr.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||(n0(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&n0(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:mi.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(J.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(J.VisibilityChanged,this.handleVisibilityChange),r.off(J.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(J.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(J.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(J.VisibilityChanged,this.handleVisibilityChange),e.on(J.Ended,this.handleEnded),this.emit(J.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(J.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?J.Muted:J.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(J.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(J.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 n0(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new W4({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===H.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)uv(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=p8(this.trackInfo,this.requestedMaxQuality);i&&uv(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:mi.HIGH})),e.quality=mi.HIGH)}this.emit(J.UpdateSettings,e)}}class Hd extends pC{static fromParticipantInfo(e,t,i,r){return new Hd(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(s=>{const a=Ld.from(s);return new cC(a,r,{publisherIdentity:t.identity})}),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let A=arguments.length>7&&arguments[7]!==void 0?arguments[7]:vc.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:L3;super(t,i||"",r,s,a,o,A),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new gT(c.map(d=>[d.info.name,d])),this.volumeMap=new Map,this.clientProtocol=l}addTrackPublication(e){super.addTrackPublication(e),e.on(J.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),De(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(J.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(J.SubscriptionPermissionChanged,t=>{this.emit($.TrackSubscriptionPermissionChanged,e,t)}),e.on(J.SubscriptionStatusChanged,t=>{this.emit($.TrackSubscriptionStatusChanged,e,t)}),e.on(J.Subscribed,t=>{this.emit($.TrackSubscribed,t,e)}),e.on(J.Unsubscribed,t=>{this.emit($.TrackUnsubscribed,t,e)}),e.on(J.SubscriptionFailed,t=>{this.emit($.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]:H.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]:H.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(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($.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),De(o))),this.emit($.TrackSubscriptionFailed,t);return}const A=e.kind==="video";let c;return A?c=new Fm(e,t,r,s):c=new dT(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Wp(c)&&Sr(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const A=H.kindFromProto(r.type);if(!A)return;o=new vT(A,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));c&&o.source!==H.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:De(c),newTrack:De(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),De(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit($.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case H.Kind.Audio:this.audioTrackPublications.delete(e);break;case H.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit($.TrackUnpublished,i)}setAudioOutput(e){return I(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Sr(i.track)&&Wp(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=pe(i,2);const r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Ye;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Ye||(Ye={}));const yT=4*1e3;class No extends oi.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,r,s,a,o,A;if(super(),t=this,this.state=Ye.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new bn,this.isVideoPlaybackBlocked=!1,this.log=Te,this.bufferedEvents=[],this.isResuming=!1,this.connect=(c,l,d)=>I(this,void 0,void 0,function*(){var u;if(!w8())throw ar()?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 h=yield this.disconnectLock.lock();if(this.state===Ye.Connected)return this.log.info("already connected to room ".concat(this.name)),h(),Promise.resolve();if(this.connectFuture)return h(),this.connectFuture.promise;this.setAndEmitConnectionState(Ye.Connecting),((u=this.regionUrlProvider)===null||u===void 0?void 0:u.getServerUrl().toString())!==q3(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ro(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ve(c,l):this.regionUrlProvider.updateToken(l),this.regionUrlProvider.fetchRegionSettings().then(v=>{var w;(w=this.regionUrlProvider)===null||w===void 0||w.setServerReportedRegions(v)}).catch(v=>{this.log.warn("could not fetch region settings",{error:v})}));const p=(v,w,b)=>I(this,void 0,void 0,function*(){var k,y;this.abortController&&this.abortController.abort();const B=new AbortController;this.abortController=B,h==null||h();try{if(yield vo.getInstance().getBackOffPromise(c),B.signal.aborted)throw fe.cancelled("Connection attempt aborted");yield this.attemptConnection(b??c,l,d,B),this.abortController=void 0,v()}catch(E){if(this.regionUrlProvider&&E instanceof fe&&E.reason!==at.Cancelled&&E.reason!==at.NotAllowed){let T=null;try{this.log.debug("Fetching next region"),T=yield this.regionUrlProvider.getNextBestRegionUrl((k=this.abortController)===null||k===void 0?void 0:k.signal)}catch(F){if(F instanceof fe&&(F.status===401||F.reason===at.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),w(F);return}}[at.InternalError,at.ServerUnreachable,at.Timeout].includes(E.reason)&&(this.log.debug("Adding failed connection attempt to back off"),vo.getInstance().addFailedConnectionAttempt(c)),T&&!(!((y=this.abortController)===null||y===void 0)&&y.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(E.message,". Retrying with another region: ").concat(T)),this.recreateEngine(!0),yield p(v,w,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,vv(E)),w(E))}else{let T=ir.UNKNOWN_REASON;E instanceof fe&&(T=vv(E)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),w(E)}}}),m=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new fn((v,w)=>{p(v,w,m)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,d,u,h,p)=>I(this,void 0,void 0,function*(){var m;const v=yield d.join(c,l,{autoSubscribe:u.autoSubscribe,adaptiveStream:typeof h.adaptiveStream=="object"?!0:h.adaptiveStream,clientInfoCapabilities:xc((m=h.frameMetadata)!==null&&m!==void 0?m:h.packetTrailer)||this.e2eeManager?[N4.CAP_PACKET_TRAILER]:void 0,maxRetries:u.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:u.websocketTimeout},p.signal,!h.singlePeerConnection),w=v.joinResponse,b=v.serverInfo;if(this.serverInfo=b,!b.version)throw new n8("unknown server version");return b.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),h.dynacast=!1),w}),this.applyJoinResponse=c=>{const l=c.participant;if(this.localParticipant.sid=l.sid,this.localParticipant.identity=l.identity,this.localParticipant.setEnabledPublishCodecs(c.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(c.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",{error:d})}this.handleParticipantUpdates([l,...c.otherParticipants]),c.room&&this.handleRoomUpdate(c.room)},this.attemptConnection=(c,l,d,u)=>I(this,void 0,void 0,function*(){var h,p;this.state===Ye.Reconnecting||this.isResuming||!((h=this.engine)===null||h===void 0)&&h.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((p=this.regionUrlProvider)===null||p===void 0)&&p.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},_m),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const m=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,u);this.applyJoinResponse(m),this.setupLocalParticipantEvents(),this.emit(G.SignalConnected)}catch(m){yield this.engine.close(),this.recreateEngine();const v=u.signal.aborted?fe.cancelled("Signal connection aborted"):fe.serverUnreachable("could not establish signal connection");throw m instanceof Error&&(v.message="".concat(v.message,": ").concat(m.message)),m instanceof fe&&(v.reason=m.reason,v.status=m.status),this.log.debug("error trying to establish signal connection",{error:m}),v}if(u.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),fe.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,u)}catch(m){throw yield this.engine.close(),this.recreateEngine(),m}ti()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ti()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Ye.Connected),this.emit(G.Connected),vo.getInstance().resetFailedConnectionAttempts(c),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var c=arguments.length,l=new Array(c),d=0;d<c;d++)l[d]=arguments[d];return I(t,[...l],void 0,function(){var u=this;let h=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var p,m,v;const w=yield u.disconnectLock.lock();try{if(u.state===Ye.Disconnected){u.log.debug("already disconnected");return}if(u.log.info("disconnect from room"),u.state===Ye.Connecting||u.state===Ye.Reconnecting||u.isResuming){const b="Abort connection attempt due to user initiated disconnect";u.log.warn(b),(p=u.abortController)===null||p===void 0||p.abort(b),(v=(m=u.connectFuture)===null||m===void 0?void 0:m.reject)===null||v===void 0||v.call(m,fe.cancelled("Client initiated disconnect")),u.connectFuture=void 0}u.engine&&(u.engine.client.isDisconnected||(yield u.engine.client.sendLeave()),yield u.engine.close()),u.handleDisconnect(h,ir.CLIENT_INITIATED),u.engine=void 0}finally{w()}}()})},this.onPageLeave=()=>I(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>I(this,void 0,void 0,function*(){const c=[],l=On();if(l&&l.os==="iOS"){const d="livekit-dummy-audio-el";let u=document.getElementById(d);if(!u){u=document.createElement("audio"),u.id=d,u.autoplay=!0,u.hidden=!0;const h=t0();h.enabled=!0;const p=new MediaStream([h]);u.srcObject=p,document.addEventListener("visibilitychange",()=>{u&&(u.srcObject=document.hidden?null:p,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(u),this.once(G.Disconnected,()=>{u==null||u.remove(),u=null})}c.push(u)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(u=>{u.track&&u.track.attachedElements.forEach(h=>{c.push(h)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>I(this,void 0,void 0,function*(){const c=[];for(const l of this.remoteParticipants.values())l.videoTrackPublications.forEach(d=>{var u;(u=d.track)===null||u===void 0||u.attachedElements.forEach(h=>{c.includes(h)||c.push(h)})});yield Promise.all(c.map(l=>l.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(l=>{l.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(Ye.Reconnecting)&&this.emit(G.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>I(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(c.serverRegion),{region:c.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(c);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(l){this.log.error("error trying to re-publish tracks after reconnection",{error:l})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:c.serverRegion})}catch{return}this.setAndEmitConnectionState(Ye.Connected),this.emit(G.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(const u of c){if(u.identity===this.localParticipant.identity){this.localParticipant.updateInfo(u);continue}u.identity===""&&(u.identity=(l=this.sidToIdentity.get(u.sid))!==null&&l!==void 0?l:"");let h=this.remoteParticipants.get(u.identity);u.state===ho.DISCONNECTED?this.handleParticipantDisconnected(u.identity,h):this.getOrCreateParticipant(u.identity,u)}const d=new Map(c.filter(u=>u.identity!==this.localParticipant.identity).map(u=>[u.identity,u.dataTracks.map(h=>Ld.from(h))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(d)},this.handleActiveSpeakersUpdate=c=>{const l=[],d={};c.forEach(u=>{if(d[u.sid]=!0,u.sid===this.localParticipant.sid)this.localParticipant.audioLevel=u.level,this.localParticipant.setIsSpeaking(!0),l.push(this.localParticipant);else{const h=this.getRemoteParticipantBySid(u.sid);h&&(h.audioLevel=u.level,h.setIsSpeaking(!0),l.push(h))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(u=>{d[u.sid]||(u.audioLevel=0,u.setIsSpeaking(!1))}),this.activeSpeakers=l,this.emitWhenConnected(G.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{const l=new Map;this.activeSpeakers.forEach(u=>{const h=this.remoteParticipants.get(u.identity);h&&h.sid!==u.sid||l.set(u.sid,u)}),c.forEach(u=>{let h=this.getRemoteParticipantBySid(u.sid);u.sid===this.localParticipant.sid&&(h=this.localParticipant),h&&(h.audioLevel=u.level,h.setIsSpeaking(u.active),u.active?l.set(u.sid,h):l.delete(u.sid))});const d=Array.from(l.values());d.sort((u,h)=>h.audioLevel-u.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(G.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{const d=this.getRemoteParticipantBySid(l.participantSid);if(!d)return;const u=d.getTrackPublicationBySid(l.trackSid);if(!u||!u.track)return;const h=H.streamStateFromProto(l.state);u.track.setStreamState(h),h!==u.track.streamState&&(d.emit($.TrackStreamStateChanged,u,u.track.streamState),this.emitWhenConnected(G.TrackStreamStateChanged,u,u.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);d&&d.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{const l=Array.from(this.remoteParticipants.values()).find(u=>u.trackPublications.has(c.trackSid));if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);d&&d.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{const d=this.remoteParticipants.get(c.participantIdentity);if(c.value.case==="user")this.handleUserPacket(d,c.value.value,c.kind,l);else if(c.value.case==="transcription")this.handleTranscription(d,c.value.value);else if(c.value.case==="sipDtmf")this.handleSipDtmf(d,c.value.value);else if(c.value.case==="chatMessage")this.handleChatMessage(d,c.value.value);else if(c.value.case==="metrics")this.handleMetrics(c.value.value,d);else if(c.value.case==="streamHeader"||c.value.case==="streamChunk"||c.value.case==="streamTrailer")this.handleDataStream(c,l);else if(c.value.case==="rpcRequest"){const u=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,u)}else if(c.value.case==="rpcResponse"){const u=c.value.value;switch(u.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(u.requestId,u.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(u.requestId,tt.fromProto(u.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(u.value.case),this.logContext);break}}else c.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(c.value.value.requestId)},this.handleUserPacket=(c,l,d,u)=>{this.emit(G.DataReceived,l.payload,c,d,l.topic,u),c==null||c.emit($.DataReceived,l.payload,d,u)},this.handleSipDtmf=(c,l)=>{this.emit(G.SipDTMFReceived,l,c),c==null||c.emit($.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{const d=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),u=d==null?void 0:d.trackPublications.get(l.trackId),h=M8(l,this.transcriptionReceivedTimes);u==null||u.emit(J.TranscriptionReceived,h),d==null||d.emit($.TranscriptionReceived,h,u),this.emit(G.TranscriptionReceived,h,d,u)},this.handleChatMessage=(c,l)=>{const d=U8(l);this.emit(G.ChatMessage,d,c)},this.handleMetrics=(c,l)=>{this.emit(G.MetricsReceived,c,l)},this.handleDataStream=(c,l)=>{this.incomingDataStreamManager.handleDataStreamPacket(c,l)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(G.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(G.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(G.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(G.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>I(this,void 0,void 0,function*(){var c;((c=On())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(G.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{const l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(G.RoomMetadataChanged,c.metadata),(l==null?void 0:l.activeRecording)!==c.activeRecording&&this.emitWhenConnected(G.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}const d=this.getRemoteParticipantBySid(l.participantSid);d&&d.setConnectionQuality(l.quality)})},this.getRemoteParticipantClientProtocol=c=>{var l,d;return(d=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.clientProtocol)!==null&&d!==void 0?d:L3},this.onLocalParticipantMetadataChanged=c=>{this.emit(G.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(G.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(G.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(G.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(G.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c==null?void 0:c.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>I(this,void 0,void 0,function*(){var l,d,u,h,p,m;(l=c.track)===null||l===void 0||l.on(J.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=c.track)===null||d===void 0||d.on(J.Restarted,this.onLocalTrackRestarted),(p=(h=(u=c.track)===null||u===void 0?void 0:u.getProcessor())===null||h===void 0?void 0:h.onPublish)===null||p===void 0||p.call(h,this),this.emit(G.LocalTrackPublished,c,this.localParticipant),Nr(c.track)&&(yield c.track.checkForSilence())&&this.emit(G.LocalAudioSilenceDetected,c);const v=yield(m=c.track)===null||m===void 0?void 0:m.getDeviceId(!1),w=Kp(c.source);w&&v&&v!==this.localParticipant.activeDeviceMap.get(w)&&(this.localParticipant.activeDeviceMap.set(w,v),this.emit(G.ActiveDeviceChanged,w,v))}),this.onLocalTrackUnpublished=c=>{var l,d;(l=c.track)===null||l===void 0||l.off(J.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=c.track)===null||d===void 0||d.off(J.Restarted,this.onLocalTrackRestarted),this.emit(G.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>I(this,void 0,void 0,function*(){const l=yield c.getDeviceId(!1),d=Kp(c.source);d&&l&&l!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(l," active")),this.localParticipant.activeDeviceMap.set(d,l),this.emit(G.ActiveDeviceChanged,d,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(G.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(G.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(G.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(G.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},yE),e),this.log=si((i=this.options.loggerName)!==null&&i!==void 0?i:mn.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Y3),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},J3),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},vE),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new jE,this.outgoingDataStreamManager=new XE(this.engine,this.log),this.incomingDataTrackManager=new aT({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",c=>{this.engine.client.sendUpdateDataSubscription(c.sid,c.subscribe)}).on("trackPublished",c=>{var l;c.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(G.DataTrackPublished,c.track),(l=this.remoteParticipants.get(c.track.publisherIdentity))===null||l===void 0||l.addRemoteDataTrack(c.track))}).on("trackUnpublished",c=>{var l;c.publisherIdentity!==this.localParticipant.identity&&(this.emit(G.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new Hm({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",c=>{this.engine.client.sendPublishDataTrackRequest(c.handle,c.name,c.usesE2ee)}).on("sfuUnpublishRequest",c=>{this.engine.client.sendUnPublishDataTrackRequest(c.handle)}).on("trackPublished",c=>{this.emit(G.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(G.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,d=c.bytes;this.engine.sendLossyBytes(d,Me.DATA_TRACK_LOSSY,"wait").finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new cT(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var c,l;return(l=(c=this.engine.latestJoinResponse)===null||c===void 0?void 0:c.serverInfo)===null||l===void 0?void 0:l.version}),this.rpcClientManager.on("sendDataPacket",c=>{let l=c.packet;var d;(d=this.engine)===null||d===void 0||d.sendDataPacket(l,Me.RELIABLE)}),this.rpcServerManager=new lT(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",c=>{let l=c.packet;var d;(d=this.engine)===null||d===void 0||d.sendDataPacket(l,Me.RELIABLE)}),this.disconnectLock=new bn,this.localParticipant=new mT("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.outgoingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Sa(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Sa(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",Sa(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),ti()){const c=new AbortController;let l;if(No.cleanupRegistry){const d=new WeakRef(this);l=()=>{const u=d.deref();u&&u.handleDeviceChange()},No.cleanupRegistry.register(this,()=>{c.abort()})}else l=this.handleDeviceChange;(A=(o=navigator.mediaDevices)===null||o===void 0?void 0:o.addEventListener)===null||A===void 0||A.call(o,"devicechange",l,{signal:c.signal})}}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){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return I(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield 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")}finally{t()}})}setupE2EE(){var e,t;const i=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new J8(r,i),this.e2eeManager.on(Es.ParticipantEncryptionStatusChanged,(s,a)=>{Q8(a)&&(this.isE2EEEnabled=s),this.emit(G.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(Es.EncryptionError,(s,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(G.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new $8(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(i=this.localParticipant)===null||i===void 0?void 0:i.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===Ye.Disconnected?Rn.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Rn.resolve(this.roomInfo.sid):new Rn((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(q.RoomUpdate,i),e(r.sid))};this.engine.on(q.RoomUpdate,i),this.once(G.Disconnected,()=>{this.engine.off(q.RoomUpdate,i),t(new Mt("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.isNewlyCreated||!this.engine.isClosed)||(this.engine=new VE(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(q.ParticipantUpdate,this.handleParticipantUpdates).on(q.RoomUpdate,this.handleRoomUpdate).on(q.SpeakersChanged,this.handleSpeakersChanged).on(q.StreamStateChanged,this.handleStreamStateUpdate).on(q.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(q.SubscriptionError,this.handleSubscriptionError).on(q.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(q.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(q.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(q.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(q.DataPacketReceived,this.handleDataPacket).on(q.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(Ye.SignalReconnecting)&&this.emit(G.SignalReconnecting)}).on(q.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Ye.Connected)&&this.emit(G.Reconnected)}).on(q.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Ye.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(q.Restarting,this.handleRestarting).on(q.Restarted,this.handleRestarted).on(q.SignalRestarted,this.handleSignalRestarted).on(q.Offline,()=>{this.setAndEmitConnectionState(Ye.Reconnecting)&&this.emit(G.Reconnecting)}).on(q.DCBufferStatusChanged,(e,t)=>{this.emit(G.DCBufferStatusChanged,e,t)}).on(q.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(q.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(G.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(q.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==At.NONE}})}).on(q.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(q.DataTrackSubscriberHandles,e=>{const t=new Map(Object.entries(e.subHandles).map(i=>{let r=pe(i,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(q.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(q.Joined,e=>{const t=new Map(e.otherParticipants.map(i=>[i.identity,i.dataTracks.map(r=>Ld.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(q.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(q.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Xp})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>I(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pn.getInstance().getDevices(e,t)}prepareConnection(e,t){return I(this,void 0,void 0,function*(){if(this.state===Ye.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(Ro(new URL(e))&&t){this.regionUrlProvider=new Ve(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Ye.Disconnected&&(this.regionUrl=i,yield fetch(Cc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Cc(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",{error:i})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return I(this,void 0,void 0,function*(){let i=()=>I(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new gr({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new gr({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new gr({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new gr({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=()=>I(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new gr({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>I(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new gr({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new gr({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>I(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Uu({reason:ir.CLIENT_INITIATED,action:po.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new gr({scenario:{case:"subscriberBandwidth",value:ca(t)}});break;case"leave-full-reconnect":r=new gr({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return I(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,A,c,l,d,u,h;let p=!0,m=!1;const v=a?{exact:r}:r;if(i==="audioinput"){m=s.localParticipant.audioTrackPublications.size===0;const w=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=v;const b=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===H.Source.Microphone);try{p=(yield Promise.all(b.map(y=>{var B;return(B=y.audioTrack)===null||B===void 0?void 0:B.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=w,y}const k=b.some(y=>{var B,E;return(E=(B=y.track)===null||B===void 0?void 0:B.isMuted)!==null&&E!==void 0?E:!1});p&&k&&(m=!0)}else if(i==="videoinput"){m=s.localParticipant.videoTrackPublications.size===0;const w=(A=s.getActiveDevice(i))!==null&&A!==void 0?A:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=v;const b=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===H.Source.Camera);try{p=(yield Promise.all(b.map(y=>{var B;return(B=y.videoTrack)===null||B===void 0?void 0:B.setDeviceId(v)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=w,y}const k=b.some(y=>{var B,E;return(E=(B=y.track)===null||B===void 0?void 0:B.isMuted)!==null&&E!==void 0?E:!1});p&&k&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!zp()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(c=yield pn.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(l=(h=s.options).audioOutput)!==null&&l!==void 0||(h.audioOutput={});const w=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((u=s.audioContext)===null||u===void 0||u.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(b=>b.setAudioOutput({deviceId:r})))}catch(b){throw s.options.audioOutput.deviceId=w,b}}return m&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(G.ActiveDeviceChanged,i,r)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on($.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on($.ParticipantNameChanged,this.onLocalParticipantNameChanged).on($.AttributesChanged,this.onLocalAttributesChanged).on($.TrackMuted,this.onLocalTrackMuted).on($.TrackUnmuted,this.onLocalTrackUnmuted).on($.LocalTrackPublished,this.onLocalTrackPublished).on($.LocalTrackUnpublished,this.onLocalTrackUnpublished).on($.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on($.MediaDevicesError,this.onMediaDevicesError).on($.AudioStreamAcquired,this.startAudio).on($.ChatMessage,this.onLocalChatMessageSent).on($.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t==null||t.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===Ye.Connecting||this.state===Ye.Reconnecting){const d=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(h=>h.id)}),this.onTrackAdded(e,t,i),u()},u=()=>{this.off(G.Reconnected,d),this.off(G.Connected,d),this.off(G.Disconnected,u)};this.once(G.Reconnected,d),this.once(G.Connected,d),this.once(G.Disconnected,u);return}if(this.state===Ye.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const r=g8(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const A=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!A){s.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));return}if(!o.startsWith("TR")){const d=this.engine.getTrackIdForReceiver(i);if(!d){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s));return}o=d}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(s,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:s,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const l=A.addSubscribedMediaTrack(e,o,t,i,c);l!=null&&l.isEncrypted&&!this.e2eeManager&&this.emit(G.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(A.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find(A=>A.trackSid===e),i=t();if(i){this.emitLocalTrackSubscribed(i);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});const r=1e4;let s;const a=A=>{A.trackSid===e&&(o(),this.emitLocalTrackSubscribed(A))},o=()=>{clearTimeout(s),this.localParticipant.off($.LocalTrackPublished,a),this.off(G.Disconnected,o)};this.localParticipant.on($.LocalTrackPublished,a),this.once(G.Disconnected,o),s=setTimeout(()=>{o();const A=t();A?this.emitLocalTrackSubscribed(A):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},r)}emitLocalTrackSubscribed(e){this.localParticipant.emit($.LocalTrackSubscribed,e),this.emitWhenConnected(G.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==Ye.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(a=>{s.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var a,o,A;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((a=s.track)===null||a===void 0||a.detach(),(o=s.track)===null||o===void 0||o.stop()):(A=s.track)===null||A===void 0||A.stopMonitor()}),this.localParticipant.off($.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off($.ParticipantNameChanged,this.onLocalParticipantNameChanged).off($.AttributesChanged,this.onLocalAttributesChanged).off($.TrackMuted,this.onLocalTrackMuted).off($.TrackUnmuted,this.onLocalTrackUnmuted).off($.LocalTrackPublished,this.onLocalTrackPublished).off($.LocalTrackUnpublished,this.onLocalTrackUnpublished).off($.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off($.MediaDevicesError,this.onMediaDevicesError).off($.AudioStreamAcquired,this.startAudio).off($.ChatMessage,this.onLocalChatMessageSent).off($.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),ti()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||r===void 0||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Ye.Disconnected),this.emit(G.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(G.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return I(this,void 0,void 0,function*(){var e,t,i;const r=pn.getInstance().previousDevices,s=yield pn.getInstance().getDevices(void 0,!1),a=On();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let A of s){const c=r.find(l=>l.deviceId===A.deviceId);c&&c.label!==""&&c.kind===A.kind&&c.label!==A.label&&this.getActiveDevice(A.kind)==="default"&&this.emit(G.ActiveDeviceChanged,A.kind,A.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let A of o){const c=A8(A),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const d=s.filter(h=>h.kind===A),u=this.getActiveDevice(A);if(u===((t=r.filter(h=>h.kind===A)[0])===null||t===void 0?void 0:t.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==u){yield this.switchActiveDevice(A,d[0].deviceId);continue}A==="audioinput"&&!bc()||A==="videoinput"||d.length>0&&!d.find(h=>h.deviceId===this.getActiveDevice(A))&&(A!=="audiooutput"||!bc())&&(yield this.switchActiveDevice(A,d[0].deviceId))}})}acquireAudioContext(){return I(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=N3())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),In(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(G.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=Hd.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new Hd(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(G.ParticipantConnected,i),i.on($.TrackPublished,r=>{this.emitWhenConnected(G.TrackPublished,r,i)}).on($.TrackSubscribed,(r,s)=>{r.kind===H.Kind.Audio?(r.on(J.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(J.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===H.Kind.Video&&(r.on(J.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(J.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(G.TrackSubscribed,r,s,i)}).on($.TrackUnpublished,r=>{this.emit(G.TrackUnpublished,r,i)}).on($.TrackUnsubscribed,(r,s)=>{this.emit(G.TrackUnsubscribed,r,s,i)}).on($.TrackMuted,r=>{this.emitWhenConnected(G.TrackMuted,r,i)}).on($.TrackUnmuted,r=>{this.emitWhenConnected(G.TrackUnmuted,r,i)}).on($.ParticipantMetadataChanged,r=>{this.emitWhenConnected(G.ParticipantMetadataChanged,r,i)}).on($.ParticipantNameChanged,r=>{this.emitWhenConnected(G.ParticipantNameChanged,r,i)}).on($.AttributesChanged,r=>{this.emitWhenConnected(G.ParticipantAttributesChanged,r,i)}).on($.ConnectionQualityChanged,r=>{this.emitWhenConnected(G.ConnectionQualityChanged,r,i)}).on($.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(G.ParticipantPermissionsChanged,r,i)}).on($.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(G.TrackSubscriptionStatusChanged,r,s,i)}).on($.TrackSubscriptionFailed,(r,s)=>{this.emit(G.TrackSubscriptionFailed,r,i,s)}).on($.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(G.TrackSubscriptionPermissionChanged,r,s,i)}).on($.Active,()=>{this.emitWhenConnected(G.ParticipantActive,i),i.kind===vc.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&F8(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(dC,(e,t)=>I(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return function*(){var o;const A=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(i,a,A)}()})),this.incomingDataStreamManager.registerTextStreamHandler(uC,(e,t)=>I(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return function*(){var o;const A=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(i,a,A)}()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Zt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ir.STATE_MISMATCH))):e=0},yT)}clearConnectionReconcile(){this.connectionReconcileInterval&&Zt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===Ye.Connected),this.emit(G.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=pe(e,2),i=t[0],r=t[1];this.emit(i,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===Ye.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Ye.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return I(this,void 0,void 0,function*(){var t,i,r,s;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 Su({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:bt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Fa({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(G.SignalConnected),this.emit(G.Connected),this.setAndEmitConnectionState(Ye.Connected),a.video){const A=new Zp(H.Kind.Video,new ao({source:Yt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO,name:"video-dummy"}),new Od(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:gv(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(A),this.localParticipant.emit($.LocalTrackPublished,A)}if(a.audio){const A=new Zp(H.Kind.Audio,new ao({source:Yt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO}),new Rd(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:t0(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(A),this.localParticipant.emit($.LocalTrackPublished,A)}for(let A=0;A<o.count-1;A+=1){let c=new Fa({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(A),state:ho.ACTIVE,tracks:[],joinedAt:bt.parse(Date.now())});const l=this.getOrCreateParticipant(c.identity,c);if(o.video){const d=gv(160*((s=o.aspectRatios[A%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),u=new ao({source:Yt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO});l.addSubscribedMediaTrack(d,u.sid,new MediaStream([d]),new RTCRtpReceiver),c.tracks=[...c.tracks,u]}if(o.audio){const d=t0(),u=new ao({source:Yt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Xi.AUDIO});l.addSubscribedMediaTrack(d,u.sid,new MediaStream([d]),new RTCRtpReceiver),c.tracks=[...c.tracks,u]}l.updateInfo(c)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==G.ActiveSpeakersChanged&&e!==G.TranscriptionReceived){const s=fC(i).filter(a=>a!==void 0);(e===G.TrackSubscribed||e===G.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...i)}}No.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});function fC(n){return n.map(e=>{if(e)return Array.isArray(e)?fC(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Yi;(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"})(Yi||(Yi={}));class Ws extends oi.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Yi.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new No(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return I(this,void 0,void 0,function*(){if(this.status!==Yi.IDLE)throw Error("check is running already");this.setStatus(Yi.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!==Yi.SKIPPED&&this.setStatus(this.isSuccess()?Yi.SUCCESS:Yi.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return I(this,void 0,void 0,function*(){return this.room.state===Ye.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return I(this,void 0,void 0,function*(){this.room&&this.room.state!==Ye.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Yi.SKIPPED)}switchProtocol(e){return I(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(G.Reconnecting,()=>{t=!0}),this.room.once(G.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield In(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 wT extends Ws{get description(){return"Cloud regions"}perform(){return I(this,void 0,void 0,function*(){const e=new Ve(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return I(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,A=1e6/a,c="A".repeat(a),l=Date.now();for(let p=0;p<A;p++)yield s.write(c);yield s.close();const d=Date.now(),u=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),h={region:r,rtt:1e4,duration:d-l};return u==null||u.forEach(p=>{p.type==="candidate-pair"&&p.nominated&&(h.rtt=p.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const u0=1e4;class bT extends Ws{get description(){return"Connection via UDP vs TCP"}perform(){return I(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/(u0/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(u0/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return I(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],c=(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},d=setInterval(()=>I(this,void 0,void 0,function*(){const u=yield c.getRTCStatsReport();u==null||u.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(u=>setTimeout(u,u0)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),l})}}class CT extends Ws{get description(){return"Can publish audio"}perform(){return I(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield hT();if(yield O3(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class BT extends Ws{get description(){return"Can publish video"}perform(){return I(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield uT();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return I(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(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,A;const c=document.createElement("canvas"),l=e.getSettings(),d=(a=(s=l.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,u=(A=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&A!==void 0?A:720;c.width=d,c.height=u;const h=c.getContext("2d");h.drawImage(i,0,0);const m=h.getImageData(0,0,c.width,c.height).data;let v=!0;for(let w=0;w<m.length;w+=4)if(m[w]!==0||m[w+1]!==0||m[w+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),t.getTracks().forEach(r=>r.stop()),i.remove()})}}class xT extends Ws{get description(){return"Resuming connection after interruption"}perform(){return I(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};t.on(G.SignalReconnecting,o).on(G.Reconnecting,o).on(G.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const A=t.engine.client.onClose;if(A&&A(""),yield a,i){if(!r||t.state!==Ye.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 ST extends Ws{get description(){return"Can connect via TURN"}perform(){return I(this,void 0,void 0,function*(){var e,t,i;Ro(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ve(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new Dm,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,A=!1;for(let c of s.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,A=!0):l.startsWith("turns:")&&(o=!0,A=!0,a=!0),l.startsWith("stun:")&&(A=!0);A?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(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(c=>setTimeout(c,0)))})}}class kT extends Ws{get description(){return"Establishing WebRTC connection"}perform(){return I(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(G.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){const o=new RTCIceCandidate(s);let A="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(ET(o.address)?A+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,A+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(A)}r&&r(s,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),Te.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 ET(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 TT extends Ws{get description(){return"Connecting to signal connection via WebSocket"}perform(){return I(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Dm,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Ro(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const A=yield new Ve(this.url,this.token).getNextBestRegionUrl();A&&(s=yield r.join(A,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"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===R4.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class IK extends oi.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:Yi.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!==Yi.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return I(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(TT)})}checkWebRTC(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(kT)})}checkTURN(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(ST)})}checkReconnect(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(xT)})}checkPublishAudio(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(CT)})}checkPublishVideo(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(BT)})}checkConnectionProtocol(){return I(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(bT);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return I(this,void 0,void 0,function*(){return this.createAndRunCheck(wT)})}}new TextEncoder;new TextDecoder;class Kn extends Error{constructor(e,t){var i;super(e,t),Re(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Re(Kn,"code","ERR_JOSE_GENERIC");class IT extends Kn{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),Re(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Re(this,"claim",void 0),Re(this,"reason",void 0),Re(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}Re(IT,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class MT extends Kn{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),Re(this,"code","ERR_JWT_EXPIRED"),Re(this,"claim",void 0),Re(this,"reason",void 0),Re(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}Re(MT,"code","ERR_JWT_EXPIRED");class UT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Re(UT,"code","ERR_JOSE_ALG_NOT_ALLOWED");class FT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Re(FT,"code","ERR_JOSE_NOT_SUPPORTED");class QT extends Kn{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),Re(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Re(QT,"code","ERR_JWE_DECRYPTION_FAILED");class PT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWE_INVALID")}}Re(PT,"code","ERR_JWE_INVALID");class DT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWS_INVALID")}}Re(DT,"code","ERR_JWS_INVALID");class LT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWT_INVALID")}}Re(LT,"code","ERR_JWT_INVALID");class RT extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWK_INVALID")}}Re(RT,"code","ERR_JWK_INVALID");class _T extends Kn{constructor(){super(...arguments),Re(this,"code","ERR_JWKS_INVALID")}}Re(_T,"code","ERR_JWKS_INVALID");class OT extends Kn{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),Re(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Re(OT,"code","ERR_JWKS_NO_MATCHING_KEY");class NT extends Kn{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),Re(this,Symbol.asyncIterator,void 0),Re(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Re(NT,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class HT extends Kn{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),Re(this,"code","ERR_JWKS_TIMEOUT")}}Re(HT,"code","ERR_JWKS_TIMEOUT");class KT extends Kn{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),Re(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Re(KT,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const VT="core-bridge-";function GT(n){return n.replace(/\/$/,"")}function zT(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`call-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}class qT{constructor(e){S(this,"serverUrl");S(this,"agentId");S(this,"callId");S(this,"authToken");S(this,"continuedCallId");S(this,"bridgePrefix");S(this,"onConnected");S(this,"onDisconnected");S(this,"onError");S(this,"room",null);S(this,"audioElements",[]);S(this,"connected",!1);S(this,"disconnecting",!1);if(!e.serverUrl)throw new Error("serverUrl is required");if(!e.agentId)throw new Error("agentId is required");this.serverUrl=GT(e.serverUrl),this.agentId=e.agentId,this.callId=e.callId??zT(),this.authToken=e.token,this.continuedCallId=e.continuedCallId,this.bridgePrefix=e.bridgeIdentityPrefix??VT,this.onConnected=e.onConnected,this.onDisconnected=e.onDisconnected,this.onError=e.onError}get isConnected(){return this.connected}reportError(e){var t;(t=this.onError)==null||t.call(this,e)}cleanupAudioElements(){for(const e of this.audioElements)try{e.pause(),e.srcObject=null,e.remove()}catch{}this.audioElements=[]}attachRemoteAudio(e){if(e.kind!==H.Kind.Audio)return;const t=e.attach();t.autoplay=!0,t.setAttribute("playsinline","true"),t.style.display="none",document.body.appendChild(t),t.play().catch(()=>{}),this.audioElements.push(t)}handleBridgeParticipant(e){e.identity.startsWith(this.bridgePrefix)&&e.trackPublications.forEach(t=>{t.track&&this.attachRemoteAudio(t.track)})}wireRoomEvents(e){e.on(G.TrackSubscribed,(t,i,r)=>{r.identity.startsWith(this.bridgePrefix)&&this.attachRemoteAudio(t)}),e.on(G.Disconnected,()=>{var t;this.connected=!1,this.cleanupAudioElements(),this.disconnecting||(t=this.onDisconnected)==null||t.call(this)})}async fetchLiveKitToken(){const e=new URLSearchParams({agent_id:this.agentId,call_id:this.callId});this.authToken&&e.set("token",this.authToken),this.continuedCallId&&e.set("continued_call_id",this.continuedCallId);const t=await fetch(`${this.serverUrl}/livekit/token?${e.toString()}`);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`GET /livekit/token failed (${t.status})${i?`: ${i}`:""}`)}return t.json()}async connect(){var e;if(this.connected||this.room)throw new Error("LiveKitVoiceClient is already connected");this.disconnecting=!1;try{const t=await this.fetchLiveKitToken();t.call_id&&(this.callId=t.call_id);const i=new No({adaptiveStream:!0,dynacast:!0});this.room=i,this.wireRoomEvents(i),await i.connect(t.url,t.token,{autoSubscribe:!0}),await i.localParticipant.setMicrophoneEnabled(!0);for(const r of i.remoteParticipants.values())this.handleBridgeParticipant(r);return this.connected=!0,(e=this.onConnected)==null||e.call(this,{roomName:t.room_name,identity:t.identity,callId:this.callId}),t}catch(t){if(this.cleanupAudioElements(),this.room)try{this.room.disconnect()}catch{}throw this.room=null,this.connected=!1,this.reportError(t),t}}disconnect(){var t;this.disconnecting=!0,this.connected=!1,this.cleanupAudioElements();const e=this.room;if(this.room=null,e)try{e.disconnect()}catch(i){this.reportError(i)}this.disconnecting=!1,(t=this.onDisconnected)==null||t.call(this)}}const lo=class lo{constructor(e){S(this,"tabId");S(this,"sessionKey");S(this,"channelName");S(this,"channel",null);S(this,"heartbeatTimer",null);S(this,"listeners",new Map);const t=e.replace(/[^a-z0-9_-]/gi,"_");this.sessionKey=`vaniraai_session_${t}`,this.channelName=`vaniraai_channel_${t}`,this.tabId=this._getOrCreateTabId(),this._setupChannel()}getTabId(){return this.tabId}claimSession(){const e=this._loadSession();if(e){const r=Date.now()-e.lastActive,s=e.tabId===this.tabId,a=r>lo.HEARTBEAT_TIMEOUT_MS;if(s)return this._startHeartbeat(),this._emit("session_restored"),!0;if(!a)return this._emit("tab_conflict"),!1}const t=e?{...e,tabId:this.tabId,lastActive:Date.now()}:{tabId:this.tabId,prospectId:"",chatId:null,conversationId:null,messages:[],lastActive:Date.now()};this._saveSession(t),this._startHeartbeat(),this._broadcast({type:"took_over",tabId:this.tabId});const i=!!(e!=null&&e.prospectId);return this._emit(i?"session_restored":"session_claimed"),!0}forceClaimSession(){const e=this._loadSession(),t=e?{...e,tabId:this.tabId,lastActive:Date.now()}:{tabId:this.tabId,prospectId:"",chatId:null,conversationId:null,messages:[],lastActive:Date.now()};this._saveSession(t),this._startHeartbeat(),this._broadcast({type:"took_over",tabId:this.tabId}),this._emit("session_claimed")}saveIds(e,t,i){const r=this._loadSession()??this._blankSession();this._saveSession({...r,prospectId:e,chatId:t,conversationId:i??r.conversationId??null,tabId:this.tabId,lastActive:Date.now()})}pushMessage(e,t){const i=this._loadSession()??this._blankSession();i.messages.push({role:e,content:t,timestamp:Date.now()}),i.messages.length>100&&(i.messages=i.messages.slice(-100)),this._saveSession({...i,tabId:this.tabId,lastActive:Date.now()})}updateLastAssistantMessage(e){const t=this._loadSession()??this._blankSession(),i=t.messages;let r=!1;for(let s=i.length-1;s>=0;s--)if(i[s].role==="assistant"&&i[s].content===""){i[s].content=e,r=!0;break}if(!r){for(let s=i.length-1;s>=0;s--)if(i[s].role==="assistant"){i[s].content=e,r=!0;break}}r||i.push({role:"assistant",content:e,timestamp:Date.now()}),this._saveSession({...t,tabId:this.tabId,lastActive:Date.now()})}getSession(){return this._loadSession()}clearSession(){localStorage.removeItem(this.sessionKey),this._broadcast({type:"session_cleared",tabId:this.tabId}),this._emit("session_cleared")}clearChatKeepProspect(){const e=this._loadSession();e&&this._saveSession({...e,chatId:null,conversationId:null,messages:[],lastActive:Date.now()})}destroy(){this._stopHeartbeat(),this.channel&&(this.channel.close(),this.channel=null)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){var i;return(i=this.listeners.get(e))==null||i.delete(t),this}_getOrCreateTabId(){let e=sessionStorage.getItem("vaniraai_tab_id");return e||(e=`tab_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionStorage.setItem("vaniraai_tab_id",e)),e}_setupChannel(){typeof BroadcastChannel>"u"||(this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=e=>{const t=e.data;t.tabId!==this.tabId&&(t.type==="took_over"&&(this._stopHeartbeat(),this._emit("tab_took_over")),t.type,t.type==="session_cleared"&&this._emit("session_cleared"))})}_broadcast(e){var t;(t=this.channel)==null||t.postMessage(e)}_startHeartbeat(){this._stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{const e=this._loadSession();e&&e.tabId===this.tabId&&(this._saveSession({...e,lastActive:Date.now()}),this._broadcast({type:"heartbeat",tabId:this.tabId}))},lo.HEARTBEAT_INTERVAL_MS)}_stopHeartbeat(){this.heartbeatTimer!==null&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}_loadSession(){try{const e=localStorage.getItem(this.sessionKey);return e?JSON.parse(e):null}catch{return null}}_saveSession(e){try{localStorage.setItem(this.sessionKey,JSON.stringify(e))}catch{}}_blankSession(){return{tabId:this.tabId,prospectId:"",chatId:null,conversationId:null,messages:[],lastActive:Date.now()}}_emit(e){var t;(t=this.listeners.get(e))==null||t.forEach(i=>i())}};S(lo,"HEARTBEAT_INTERVAL_MS",5e3),S(lo,"HEARTBEAT_TIMEOUT_MS",15e3);let Kd=lo;class mC{static async fetchWidgetConfig(e,t){var r;const i={"Content-Type":"application/json"};t&&(i["X-API-Key"]=t);try{const s=await fetch(`${Kc}/assistant/widget/${e}/config`,{method:"GET",headers:i});if(!s.ok)throw new Error(`Widget config fetch failed: HTTP ${s.status}`);const a=await s.json();return(r=a.agent)!=null&&r.client&&(a.client=a.agent.client),a}catch(s){throw s}}}let yA="https://inboxapi.vanira.io";const WT="https://coredb.vanira.io/v1/graphql";class Vr{static setChatUrl(e){yA=e}static async createChatProspect(e){var i,r;const t=`
|
|
58
58
|
mutation CreateChatProspect($prospectGroupId: uuid!, $name: String!) {
|
|
59
59
|
insert_prospects_one(object: {prospect_group_id: $prospectGroupId, name: $name, source: WEBSITE_WIDGET}) {
|
|
60
60
|
id
|
|
@@ -3455,7 +3455,7 @@ l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
|
|
|
3455
3455
|
<svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
|
|
3456
3456
|
Submit
|
|
3457
3457
|
</button>
|
|
3458
|
-
`,p.appendChild(b);const k=b.querySelector(".vnr-confirm-btn"),y=new Set,B=()=>{k.disabled=y.size===0},E=()=>{v.querySelectorAll(".vnr-mcq-option").forEach(T=>{const F=T.dataset.optionId;T.classList.toggle("vnr-mcq-sel",!!F&&y.has(F))}),B(),w.style.display="none"};o.forEach(T=>{const F=document.createElement("button");F.type="button",F.className="vnr-mcq-option",F.dataset.optionId=T.id;const L=document.createElement("span");L.className="vnr-mcq-option-id",L.textContent=`${T.id}.`;const D=document.createElement("span");D.className="vnr-mcq-option-label",D.textContent=T.label,F.appendChild(L),F.appendChild(D),F.addEventListener("click",()=>{A?y.has(T.id)?y.delete(T.id):y.add(T.id):(y.clear(),y.add(T.id)),E()}),v.appendChild(F)}),b.querySelector(".vnr-cancel-btn").addEventListener("click",()=>{this.dismiss(),s("User cancelled")}),k.addEventListener("click",()=>{if(y.size===0){w.textContent="Please select an answer.",w.style.display="block";return}k.disabled=!0,k.innerHTML='<div class="vnr-spinner"></div>';const T=yS(a,o,[...y],{allow_multiple:A,image_url:c,question_id:l});setTimeout(()=>{this.dismiss(),r(T)},200)})}renderKycCapture(e,t,i,r,s){const a=e==="document"?Q.KycDocumentCapture:Q.KycSelfieCapture;this.bindActiveModalPreset(t,a,i,r);const o=m=>{this.clearActiveModalPreset(),i({status:"success",preset_id:a,...m})},A=(m,v="cancelled")=>{this.clearActiveModalPreset(),r(m,{status:v})},c=String(t.args.document_side??t.clientFields.document_side??"front").toLowerCase()==="back"?"back":"front",l=e==="document"?c==="back"?"Scan back of ID":"Scan your ID":"Verify it's you",d=e==="document"?c==="back"?"Hold the back of your ID in the frame. We'll capture automatically when edges are clear.":"Hold your ID in the frame. On desktop, use your webcam; on mobile, we use the rear camera.":"Center your face in the oval. Blink or turn slightly when prompted — we'll capture automatically.",u=String(t.args.reason??t.clientFields.reason??(e==="document"?"kyc_document":"kyc_selfie")).trim();this.stopCaptureCamera();const h=this,p=hN({mode:e,presetId:a,title:String(t.clientFields.title??t.args.title??l),description:String(t.clientFields.description??t.args.description??d),reason:u,documentSide:c,toolCallId:t.toolCallId,host:{setCaptureActive:m=>{h.captureActive=m},setCaptureStream:m=>{h.captureStream=m},createOverlay:()=>h.createOverlay(),dismiss:()=>h.dismiss(),getBrowserPermissionHint:()=>h.getBrowserPermissionHint(),fillCameraPermissionPrompt:(m,v)=>h.fillCameraPermissionPrompt(m,v),notifyCameraPermissionDenied:(m,v)=>h.notifyCameraPermissionDenied(m,v)},client:s,onComplete:m=>{h.kycCaptureStop=null,o(m)},onCancel:m=>{h.kycCaptureStop=null,A(m)},isActive:()=>h.captureActive});this.kycCaptureStop=p.stop}renderKycSignatureCapture(e,t,i,r){const s=Q.KycSignatureCapture;this.bindActiveModalPreset(e,s,t,i);const a=l=>{this.clearActiveModalPreset(),t({status:"success",preset_id:s,...l})},o=(l,d="cancelled")=>{this.clearActiveModalPreset(),i(l,{status:d})},A=String(e.args.reason??e.clientFields.reason??"kyc_signature").trim(),c=fN({presetId:s,title:String(e.clientFields.title??e.args.title??"Sign here"),description:String(e.clientFields.description??e.args.description??"Draw your signature in the box below, then submit."),reason:A,host:{createOverlay:()=>this.createOverlay(),dismiss:()=>this.dismiss()},client:r,onComplete:a,onCancel:l=>o(l)});this.kycCaptureStop=c.stop}renderCamera(e,t,i,r){this.bindActiveModalPreset(e,Q.Camera,t,i);const s=ne=>{this.clearActiveModalPreset(),t({status:"success",preset_id:Q.Camera,...ne})},a=(ne,we="cancelled")=>{this.clearActiveModalPreset(),i(ne,{status:we})},o=this,A=e.clientFields.title||"Take a Photo",c=e.clientFields.description||"Point your camera at the subject, then tap capture.";let l=pw(e.clientFields.facing_mode||e.args.facing_mode,"environment");const d=mw(e.clientFields,e.args),u=e.clientFields.reason||"camera_capture",h=e.clientFields.liveness_check===!0||e.clientFields.liveness_check==="true"||e.args.liveness_check===!0||e.args.liveness_check==="true";let p=null,m=null;this.stopCaptureCamera(),this.captureActive=!0;const v=this.createOverlay(),w=document.createElement("div");w.className="vnr-modal",w.style.cssText="position:relative;max-width:480px;width:100%",w.innerHTML=`
|
|
3458
|
+
`,p.appendChild(b);const k=b.querySelector(".vnr-confirm-btn"),y=new Set,B=()=>{k.disabled=y.size===0},E=()=>{v.querySelectorAll(".vnr-mcq-option").forEach(T=>{const F=T.dataset.optionId;T.classList.toggle("vnr-mcq-sel",!!F&&y.has(F))}),B(),w.style.display="none"};o.forEach(T=>{const F=document.createElement("button");F.type="button",F.className="vnr-mcq-option",F.dataset.optionId=T.id;const L=document.createElement("span");L.className="vnr-mcq-option-id",L.textContent=`${T.id}.`;const D=document.createElement("span");D.className="vnr-mcq-option-label",D.textContent=T.label,F.appendChild(L),F.appendChild(D),F.addEventListener("click",()=>{A?y.has(T.id)?y.delete(T.id):y.add(T.id):(y.clear(),y.add(T.id)),E()}),v.appendChild(F)}),b.querySelector(".vnr-cancel-btn").addEventListener("click",()=>{this.dismiss(),s("User cancelled")}),k.addEventListener("click",()=>{if(y.size===0){w.textContent="Please select an answer.",w.style.display="block";return}k.disabled=!0,k.innerHTML='<div class="vnr-spinner"></div>';const T=yS(a,o,[...y],{allow_multiple:A,image_url:c,question_id:l});setTimeout(()=>{this.dismiss(),r(T)},200)})}renderKycCapture(e,t,i,r,s){const a=e==="document"?Q.KycDocumentCapture:Q.KycSelfieCapture;this.bindActiveModalPreset(t,a,i,r);const o=m=>{this.clearActiveModalPreset(),i({status:"success",preset_id:a,...m})},A=(m,v="cancelled")=>{this.clearActiveModalPreset(),r(m,{status:v})},c=String(t.args.document_side??t.clientFields.document_side??"front").toLowerCase()==="back"?"back":"front",l=e==="document"?c==="back"?"Scan back of ID":"Scan your ID":"Verify it's you",d=e==="document"?c==="back"?"Hold the back of your ID in the frame. We'll capture automatically when edges are clear.":"Hold your ID in the frame. On desktop, use your webcam; on mobile, we use the rear camera.":"Center your face in the oval. Blink or turn slightly when prompted — we'll capture automatically.",u=String(t.args.reason??t.clientFields.reason??(e==="document"?"kyc_document":"kyc_selfie")).trim();this.stopCaptureCamera();const h=this,p=hN({mode:e,presetId:a,title:String(t.clientFields.title??t.args.title??l),description:String(t.clientFields.description??t.args.description??t.clientFields.instructions??t.args.instructions??d),reason:u,documentSide:c,toolCallId:t.toolCallId,host:{setCaptureActive:m=>{h.captureActive=m},setCaptureStream:m=>{h.captureStream=m},createOverlay:()=>h.createOverlay(),dismiss:()=>h.dismiss(),getBrowserPermissionHint:()=>h.getBrowserPermissionHint(),fillCameraPermissionPrompt:(m,v)=>h.fillCameraPermissionPrompt(m,v),notifyCameraPermissionDenied:(m,v)=>h.notifyCameraPermissionDenied(m,v)},client:s,onComplete:m=>{h.kycCaptureStop=null,o(m)},onCancel:m=>{h.kycCaptureStop=null,A(m)},isActive:()=>h.captureActive});this.kycCaptureStop=p.stop}renderKycSignatureCapture(e,t,i,r){const s=Q.KycSignatureCapture;this.bindActiveModalPreset(e,s,t,i);const a=l=>{this.clearActiveModalPreset(),t({status:"success",preset_id:s,...l})},o=(l,d="cancelled")=>{this.clearActiveModalPreset(),i(l,{status:d})},A=String(e.args.reason??e.clientFields.reason??"kyc_signature").trim(),c=fN({presetId:s,title:String(e.clientFields.title??e.args.title??"Sign here"),description:String(e.clientFields.description??e.args.description??e.clientFields.instructions??e.args.instructions??"Draw your signature in the box below, then submit."),reason:A,host:{createOverlay:()=>this.createOverlay(),dismiss:()=>this.dismiss()},client:r,onComplete:a,onCancel:l=>o(l)});this.kycCaptureStop=c.stop}renderCamera(e,t,i,r){this.bindActiveModalPreset(e,Q.Camera,t,i);const s=ne=>{this.clearActiveModalPreset(),t({status:"success",preset_id:Q.Camera,...ne})},a=(ne,we="cancelled")=>{this.clearActiveModalPreset(),i(ne,{status:we})},o=this,A=e.clientFields.title||"Take a Photo",c=e.clientFields.description||"Point your camera at the subject, then tap capture.";let l=pw(e.clientFields.facing_mode||e.args.facing_mode,"environment");const d=mw(e.clientFields,e.args),u=e.clientFields.reason||"camera_capture",h=e.clientFields.liveness_check===!0||e.clientFields.liveness_check==="true"||e.args.liveness_check===!0||e.args.liveness_check==="true";let p=null,m=null;this.stopCaptureCamera(),this.captureActive=!0;const v=this.createOverlay(),w=document.createElement("div");w.className="vnr-modal",w.style.cssText="position:relative;max-width:480px;width:100%",w.innerHTML=`
|
|
3459
3459
|
<button class="vnr-close-btn" aria-label="Close">
|
|
3460
3460
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
|
3461
3461
|
</button>
|
|
@@ -3659,7 +3659,7 @@ ${D}`:D,j=O+N,V=this.activePresetGeneration,te=u<=0,xe=()=>{this.chalkboardConte
|
|
|
3659
3659
|
object-fit: contain;
|
|
3660
3660
|
display: block;
|
|
3661
3661
|
}
|
|
3662
|
-
`,document.head.appendChild(n)}function RN(n,e,t){LN();const i=document.createElement("figure");i.className="vnr-diagram-host-viewer vnr-diagram-host-viewer--minimal",i.setAttribute("aria-label",e.title);const r=document.createElement("div");r.className="vnr-diagram-host-viewer__body";const s=document.createElement("img");s.className="vnr-diagram-host-viewer__img",s.src=e.image_url,s.alt=e.title,s.referrerPolicy="no-referrer",r.appendChild(s),i.appendChild(r),n.innerHTML="",n.dataset.vnrDiagramHost="true",n.appendChild(i)}const ox="vanira:diagram_search_result";function bg(n){if(!n||typeof n!="object")return null;const e=n;if(e.found!==!0)return null;const t=e.image;if(!t||typeof t!="object")return null;const i=t,r=String(i.image_url??"").trim();return r?{image_url:r,title:String(i.title??"Educational diagram").trim()||"Educational diagram",page_url:String(i.page_url??"").trim(),file_type:i.file_type!=null?String(i.file_type):void 0,width:typeof i.width=="number"?i.width:void 0,height:typeof i.height=="number"?i.height:void 0}:null}function Ax(n){return bg(n)!==null}function Uw(n){typeof window>"u"||window.dispatchEvent(new CustomEvent(ox,{detail:n}))}function uh(n){return n.data??n}const cx="http://127.0.0.1:8000/diagram-search";function _N(){return typeof window<"u"?`${window.location.origin}/vanira-api/diagram-search`:cx}function lx(n){const t=uh(n).client_fields??n.client_fields,i=t&&typeof t=="object"?{...t}:{};if(typeof window>"u")return i;const r=window.__vaniraDiagramSearchClientFields;if(!r||typeof r!="object")return i;const s={...i};for(const A of["element_id","css_selector","route"]){const c=r[A];c!=null&&String(c).trim()&&(s[A]=c)}const a=String(s.element_id??"").trim(),o=String(s.css_selector??"").trim();return a?delete s.css_selector:o||delete s.css_selector,s}function ON(n){const e=uh(n),t=e.arguments??e.args??n.arguments??n.args??{};if(typeof t=="string")try{return JSON.parse(t)}catch{return{}}return typeof t=="object"&&t!==null?t:{}}function hh(n){return String(n??"").trim().toLowerCase()==="diagram_search"}function NN(n){const e=uh(n);return String(e.tool_call_id??e.call_id??n.tool_call_id??"")}async function HN(n,e){const t=sx(lx(n)),i=bg(e);if(!t||!i)return null;const{idOrSelector:r,route:s,target:a}=t;let o=!1;const A=async()=>{const c=await Kf(a);c&&(RN(c,i,e.query),o=!0)};if(s){if(!await DN(s,a,()=>A(),{toolName:"diagram_search"})||!o)return null}else if(await A(),!o)return null;return{...e,render_target:r,rendered_in_dom:!0}}async function Cg(n,e){const t=uh(n),i=String(t.name??t.tool_name??n.name??"");if(!hh(i))return!1;const r=NN(n);if(!r)return!0;const s=ON(n),a=String(s.query??"").trim();if(!a){const o={found:!1,error:"query is required"};return e.sendToolResult(r,o),!0}try{const o=await fetch(_N(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:a})});if(!o.ok){const c=await o.text().catch(()=>"");throw new Error(`diagram-search HTTP ${o.status}${c?`: ${c.slice(0,200)}`:""}`)}const A=await o.json();if(Ax(A)){const c=await HN(n,A);if(c)return Uw(c),e.sendToolResult(r,c),!0;const l={...A,render_fallback:sx(lx(n))?"Host element not found — showing floating diagram viewer.":void 0};return Uw(l),e.sendToolResult(r,l),!0}e.sendToolResult(r,A)}catch(o){const A=o instanceof Error?o.message:String(o);typeof e.sendToolError=="function"?e.sendToolError(r,A):e.sendToolResult(r,{found:!1,error:A})}return!0}const uo=class uo extends jT{constructor(t){super(t);S(this,"vaniraClient",null);S(this,"currentView",null);S(this,"presetRenderer",null);S(this,"boardAbortHandler",null);S(this,"clipRegionHandler",null);S(this,"isPanelOpen",!1);S(this,"callActive",!1);S(this,"callStatus","disconnected");S(this,"micMuted",!1);S(this,"eventSource",null);S(this,"pillAudioCtx",null);S(this,"pillAgentAnalyser",null);S(this,"pillAgentData",null);S(this,"pillActivityRaf",null);S(this,"pillLastTranscriptionAt",0);S(this,"pillActivityState","idle");S(this,"floatingButton",null);S(this,"floatingWelcomeChips",null);S(this,"voiceChatPill",null);S(this,"cleanCardLauncher",null);S(this,"humanPresenceLauncher",null);S(this,"panel",null);S(this,"welcomeChipsData",[]);S(this,"chatAdapter");S(this,"sessionManager",null);S(this,"sessionActive",!1);S(this,"widgetMode","voice_only");S(this,"agentId","");S(this,"prospectGroupId","");S(this,"chatServerUrl","");S(this,"prospectId","");S(this,"chatId",null);S(this,"conversationId",null);S(this,"widgetId","");S(this,"pkKey","");S(this,"chatInitialized",!1);S(this,"primaryColor","#000000");S(this,"secondaryColor","#111111");S(this,"gradient",null);S(this,"positionType","fixed");S(this,"position","bottom-right");S(this,"widgetIcon",null);S(this,"iconConfig",null);S(this,"chatWelcomeMessage",null);this.chatAdapter=new A9,this.processConfig(t)}initSessionManager(){const t=this.widgetId||this.agentId||"default";this.sessionManager=new Kd(t),this.sessionManager.on("tab_took_over",()=>{this.sessionActive=!1,this.showTabConflictBanner("taken_over")}),this.sessionManager.on("session_cleared",()=>{});const i=this.sessionManager.claimSession();return this.sessionActive=i,i}restoreSessionMessages(){var A,c,l;const t=(A=this.sessionManager)==null?void 0:A.getSession();if(!t)return;const i=(l=(c=this.currentView)==null?void 0:c.getChatWindow)==null?void 0:l.call(c);if(!i)return;const r=t.messages.filter(d=>d.content.trim()!==""),s=`vanira_calls_${this.widgetId||this.agentId}`,a=JSON.parse(localStorage.getItem(s)||"[]");if(r.length===0&&a.length===0)return;i.clearMessages();const o=[...r.map((d,u)=>({type:"msg",role:d.role,content:d.content,ts:d.timestamp??u})),...a.map(d=>({type:"call",durationMs:d.durationMs,startedAt:d.startedAt,ts:d.startedAt}))];o.sort((d,u)=>d.ts-u.ts),o.forEach(d=>{d.type==="msg"?i.addMessage(d.role,d.content,d.ts):i.addCallRecord(d.durationMs,d.startedAt)})}showTabConflictBanner(t){var i,r;this.root&&((i=this.root.querySelector(".vanira-tab-conflict-banner"))==null||i.remove(),t==="conflict"&&((r=this.sessionManager)==null||r.forceClaimSession(),this.sessionActive=!0,this.widgetMode.includes("chat")&&this.initializeChatSession(!1)))}playMessageSound(t){try{if(!uo.audioContext){const o=window.AudioContext||window.webkitAudioContext;if(!o)return;uo.audioContext=new o}const i=uo.audioContext;i.state==="suspended"&&i.resume().catch(()=>{});const r=i.createOscillator(),s=i.createGain();r.connect(s),s.connect(i.destination);const a=i.currentTime;t==="send"?(r.type="sine",r.frequency.setValueAtTime(300,a),r.frequency.exponentialRampToValueAtTime(500,a+.05),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.1,a+.01),s.gain.exponentialRampToValueAtTime(.001,a+.1),r.start(a),r.stop(a+.1)):(r.type="sine",r.frequency.setValueAtTime(500,a),r.frequency.exponentialRampToValueAtTime(800,a+.1),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.15,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.2),r.start(a),r.stop(a+.2))}catch{}}handleWelcomePayload(t,i="assistant"){var a,o,A,c,l,d,u,h;if(!t||this.widgetMode==="voice_only")return;t.buttons&&Array.isArray(t.buttons)?this.welcomeChipsData=t.buttons:((a=t.widget)==null?void 0:a.type)==="button_list"&&((o=t.widget.data)!=null&&o.buttons)&&(this.welcomeChipsData=t.widget.data.buttons),this.updateWelcomeChipsVisibility();const r=(c=(A=this.currentView)==null?void 0:A.getChatWindow)==null?void 0:c.call(A);let s=t.text||t.response||t.content||t.message||"";if(!s&&!this.welcomeChipsData.length&&(s="Hey! how can I help you ?"),!s&&typeof t=="string"&&t.trim().startsWith("{"))try{const p=JSON.parse(t);s=p.text||p.response||p.content||p.message||"",((l=p.widget)==null?void 0:l.type)==="button_list"&&((d=p.widget.data)!=null&&d.buttons)&&(this.welcomeChipsData=p.widget.data.buttons)}catch{}if(r){if(!s&&this.welcomeChipsData.length===0)return;const p=(u=this.sessionManager)==null?void 0:u.getSession();(p==null?void 0:p.messages.some(v=>v.content===s&&v.role===i))||(s&&(r.addMessage(i,s),(h=this.sessionManager)==null||h.pushMessage(i,s)),this.welcomeChipsData.length>0&&r.addButtons(this.welcomeChipsData))}}async initializeChatSession(t=!1){var i,r,s,a,o;if(this.sessionActive&&!this.chatInitialized){this.chatInitialized=!0;try{Vr.setChatUrl(this.chatServerUrl);const A=(i=this.sessionManager)==null?void 0:i.getSession();if(!t&&(A!=null&&A.prospectId)){this.prospectId=A.prospectId,this.chatId=A.chatId,this.conversationId=A.conversationId||null,this.restoreSessionMessages(),this.chatId&&!this.eventSource&&(this.eventSource=Vr.listenForAdminReplies(this.chatId,this.prospectId,l=>{var d,u,h;(u=(d=this.currentView)==null?void 0:d.getChatWindow)==null||u.call(d).addMessage("assistant",l),(h=this.sessionManager)==null||h.pushMessage("assistant",l),this.playMessageSound("receive")}));return}this.prospectId||(this.prospectGroupId?this.prospectId=await Vr.createChatProspect(this.prospectGroupId):this.prospectId=`anon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`);const c=await Vr.fetchWelcomeMessage(this.agentId,this.prospectId,this.widgetId||void 0,this.pkKey||void 0);c&&(this.handleWelcomePayload(c),c.chatId&&!this.chatId&&(this.chatId=c.chatId,this.eventSource||(this.eventSource=Vr.listenForAdminReplies(this.chatId,this.prospectId,l=>{var d,u,h;(u=(d=this.currentView)==null?void 0:d.getChatWindow)==null||u.call(d).addMessage("assistant",l),(h=this.sessionManager)==null||h.pushMessage("assistant",l),this.playMessageSound("receive")}))),c.conversationId&&(this.conversationId=c.conversationId)),(r=this.sessionManager)==null||r.saveIds(this.prospectId,this.chatId,this.conversationId)}catch{const c="Hey! how can I help you ?";(a=(s=this.currentView)==null?void 0:s.getChatWindow)==null||a.call(s).addMessage("assistant",c),(o=this.sessionManager)==null||o.pushMessage("assistant",c)}}}async initialize(t,i){await super.initialize(t),this.processConfig(t),i&&(this.root=i),this.root&&this.ui_renderer(this.root)}processConfig(t){var i,r;if(this.widgetId=t.widgetId||t.widget_id||this.widgetId||"",this.agentId=t.agentId||t.agent_id||this.agentId||"",this.prospectGroupId=t.prospectGroupId||((i=t.client)==null?void 0:i.base_prospect_group_id)||this.prospectGroupId||"",this.widgetMode=t.widgetMode||t.mode||this.widgetMode||"voice_only",this.pkKey=t.pkKey||t.pk_key||t.publicKey||t.public_key||this.pkKey||"",this.primaryColor=t.primaryColor||t.primary_color||"#000000",this.secondaryColor=t.secondaryColor||t.secondary_color||"#111111",this.gradient=t.gradient||null,this.position=t.position||"bottom-right",this.positionType=t.positionType||"fixed",this.widgetIcon=t.widgetIcon||t.icon||null,this.iconConfig=t.iconConfig||t.icon_config||null,this.chatWelcomeMessage=t.chatWelcomeMessage||t.chat_welcome_message||((r=t.agent)==null?void 0:r.chat_welcome_message)||null,typeof this.chatWelcomeMessage=="string")try{this.chatWelcomeMessage=JSON.parse(this.chatWelcomeMessage)}catch{}this.chatServerUrl=t.serverUrl||t.chatServerUrl||"https://inboxapi.vanira.io",this.updateWelcomeChipsVisibility()}async create_call(t="continue"){var i,r,s,a;if(!(this.callActive||!this.agentId)){this.sessionActive||((i=this.sessionManager)==null||i.forceClaimSession(),this.sessionActive=!0),t==="new"&&((r=this.presetRenderer)==null||r.resetBoardSession());try{if(this.callActive=!0,this.micMuted=!1,this.syncMicMuteUi(),this.updateViewCallState(!0),this.updateViewStatus("connecting"),this.updateLauncherVisibility(),this.isPanelOpen&&this.minimizePanel(),!this.pkKey)throw new Error("[VaniraAI Widget] pk-key is required for voice calls");const o=((s=this.config)==null?void 0:s.serverUrl)||((a=this.config)==null?void 0:a.chatServerUrl),A=o&&!o.includes("travelr.club")?o:Kc,c=t==="continue"?mc(this.agentId):null,l=new _s({agentId:this.agentId,apiKey:this.pkKey,sessionBehavior:t,prospectId:this.prospectId||(c==null?void 0:c.prospectId)||void 0,callId:t==="continue"?c==null?void 0:c.callId:void 0,backendUrl:A});l.on("session_started",({prospectId:d,callId:u})=>{var h;d&&(this.prospectId=d,(h=this.sessionManager)==null||h.saveIds(d,this.chatId)),u&&om(this.agentId,u,d)}),l.on("connected",()=>this.updateViewStatus("connected")).on("disconnected",()=>this.end_call()).on("error",d=>{this.updateViewStatus("error",d)}).on("transcription",({text:d,isFinal:u})=>{var h,p;d.trim()&&(this.pillLastTranscriptionAt=Date.now()),(p=(h=this.currentView)==null?void 0:h.setTranscription)==null||p.call(h,d,u)}).on("track",({track:d})=>{var u;d.kind==="audio"&&this.setupPillAgentAudio(d),this.widgetMode.includes("avatar")&&d.kind==="video"&&((u=this.currentView)!=null&&u.setVideoTrack)&&this.currentView.setVideoTrack(d)}).on("tool_call",d=>{var p,m,v;if((p=this.presetRenderer)==null?void 0:p.handle(d,w=>{const b=Qo(d.client_fields,d.arguments||d.args,d.name),k=d.tool_call_id;if(Fo(b)&&k){const y=typeof w=="object"&&w!==null?w:{response:w};if(y.status==="cancelled")return;if(b===Q.WriteLatexText&&y.latex_render_ok===!1)try{l.triggerActionInterrupt(),l.sendActionTrigger("latex_format_error",y)}catch{}try{l.sendToolResult(k,y)}catch{}return}if(!(w&&(w.media_id||w.url)&&Mo(b))){if(Uo(b)&&b){const y=typeof w=="object"&&w!==null?w:{response:w};if(y.status==="cancelled")return;const B=fc(b,d.name,d.client_fields);l.triggerActionInterrupt(),l.sendActionTrigger(B,y);return}if(b){const y=fc(b,d.name,d.client_fields);l.triggerInterrupt(y,w)}}},(w,b)=>{var B,E,T;const k=Qo(d.client_fields,d.arguments||d.args,d.name),y=d.tool_call_id;if(Fo(k)&&y){const F=(b==null?void 0:b.status)??"cancelled",L=String(((B=d.client_fields)==null?void 0:B.target_url)||(d.arguments||d.args||{}).target_url||"");try{const D=k===Q.Navigate?((E=this.presetRenderer)==null?void 0:E.getNavigateTerminalResult(F,w,L||void 0))??{status:F,reason:w||"Navigation cancelled",preset_id:k,target_url:L||void 0}:((T=this.presetRenderer)==null?void 0:T.getBoardTerminalResult(F,w,k))??{status:F,reason:w||"User dismissed",preset_id:k};l.sendToolResult(y,D)}catch{}return}if(Mo(k)&&y){try{l.sendToolResult(y,{status:"cancelled",reason:w||"User dismissed",preset_id:k})}catch{}return}if(Uo(k)&&y){try{l.sendToolResult(y,{status:"cancelled",reason:w||"User dismissed",preset_id:k})}catch{}return}try{l.sendToolResult(y,{status:"cancelled",reason:"User dismissed"})}catch{}},l))return;if(hh(d.name)){Cg(d,l);return}const h=new CustomEvent("vaniraai:tool_call",{detail:d,bubbles:!0,composed:!0});(v=(m=this.root)==null?void 0:m.host)==null||v.dispatchEvent(h)}),this.vaniraClient=l,await l.start(),this.boardAbortHandler=d=>{var h;const u=d.detail||{};(h=this.presetRenderer)==null||h.abortBoardTools(u.reason||"Server interrupted",u.toolCallId,u.presetId)},window.addEventListener(cu,this.boardAbortHandler)}catch(o){this.updateViewStatus("error",(o==null?void 0:o.message)||String(o))}}}isCallActive(){var t;return this.callActive&&!!((t=this.vaniraClient)!=null&&t.isConnected)}updateContext(t){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.updateContext(t),!0}catch{return!1}}triggerInterrupt(t,i={}){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.triggerInterrupt(t,i),!0}catch{return!1}}sendToolResult(t,i){var r;if(!((r=this.vaniraClient)!=null&&r.isConnected)||!t)return!1;try{return this.vaniraClient.sendToolResult(t,i),!0}catch{return!1}}end_call(){var r,s;this.boardAbortHandler&&(window.removeEventListener(cu,this.boardAbortHandler),this.boardAbortHandler=null),this.clipRegionHandler&&(window.removeEventListener(ad,this.clipRegionHandler),this.clipRegionHandler=null);const t=(r=this.root)==null?void 0:r.host;t==null||t.classList.remove("vanira-clip-suppressed"),this.callActive=!1,this.callStatus="disconnected",this.micMuted=!1,this.syncMicMuteUi(),this.stopPillActivityMonitor();const i=this.vaniraClient;this.vaniraClient=null,i&&i.stop(),(s=this.presetRenderer)==null||s.teardownSession(),this.updateViewCallState(!1),this.updateLauncherVisibility()}updateViewCallState(t){var i;(i=this.currentView)!=null&&i.setCallActive&&this.currentView.setCallActive(t)}toggleMicMute(){return this.vaniraClient?(this.micMuted=this.vaniraClient.toggleMicrophoneMuted(),this.syncMicMuteUi(),this.micMuted):this.micMuted}syncMicMuteUi(){var t,i,r;(t=this.voiceChatPill)==null||t.setMicMuted(this.micMuted),(r=(i=this.currentView)==null?void 0:i.setMicMuted)==null||r.call(i,this.micMuted)}wireMicMuteControls(){var i,r,s;const t=()=>this.toggleMicMute();(i=this.voiceChatPill)==null||i.bindMicMuteToggle(t),(s=(r=this.currentView)==null?void 0:r.bindMicMuteToggle)==null||s.call(r,t)}updateViewStatus(t,i){var r,s,a,o,A;t==="connecting"?this.callStatus="connecting":t==="connected"?this.callStatus="connected":t==="error"?this.callStatus="error":this.callStatus="disconnected",(r=this.currentView)!=null&&r.setStatus&&this.currentView.setStatus(t,i),this.voiceChatPill&&this.callActive&&!this.isPanelOpen?t==="connected"?(this.pillActivityState="listening",this.voiceChatPill.setActivity("listening"),(a=(s=this.currentView)==null?void 0:s.setActivity)==null||a.call(s,"listening"),this.startPillActivityLoop()):this.voiceChatPill.setStatus(this.callStatus):t==="connected"&&(this.pillActivityState="listening",(A=(o=this.currentView)==null?void 0:o.setActivity)==null||A.call(o,"listening"),this.startPillActivityLoop())}setupPillAgentAudio(t){try{this.pillAudioCtx||(this.pillAudioCtx=new AudioContext),this.pillAudioCtx.state==="suspended"&&this.pillAudioCtx.resume();const i=new MediaStream([t]),r=this.pillAudioCtx.createMediaStreamSource(i);this.pillAgentAnalyser=this.pillAudioCtx.createAnalyser(),this.pillAgentAnalyser.fftSize=256,r.connect(this.pillAgentAnalyser),this.pillAgentData=new Uint8Array(this.pillAgentAnalyser.frequencyBinCount),this.startPillActivityLoop()}catch{}}readPillAgentLevel(){if(!this.pillAgentAnalyser||!this.pillAgentData)return 0;this.pillAgentAnalyser.getByteFrequencyData(this.pillAgentData);let t=0;const i=Math.min(48,this.pillAgentData.length);for(let r=0;r<i;r++)t+=this.pillAgentData[r];return i>0?t/i/255:0}startPillActivityLoop(){if(this.pillActivityRaf!==null)return;const t=()=>{var o,A;if(this.pillActivityRaf=requestAnimationFrame(t),!this.callActive||this.callStatus!=="connected")return;const i=this.readPillAgentLevel(),r=Date.now()-this.pillLastTranscriptionAt<1200,a=i>.06||r?"speaking":"listening";a!==this.pillActivityState&&(this.pillActivityState=a,this.voiceChatPill&&!this.isPanelOpen&&this.voiceChatPill.setActivity(a),(A=(o=this.currentView)==null?void 0:o.setActivity)==null||A.call(o,a))};this.pillActivityRaf=requestAnimationFrame(t)}stopPillActivityMonitor(){this.pillActivityRaf!==null&&(cancelAnimationFrame(this.pillActivityRaf),this.pillActivityRaf=null),this.pillAgentAnalyser=null,this.pillAgentData=null,this.pillLastTranscriptionAt=0,this.pillActivityState="idle",this.pillAudioCtx&&(this.pillAudioCtx.close().catch(()=>{}),this.pillAudioCtx=null)}ui_renderer(t){var c,l,d,u,h;this.root=t,this.root.innerHTML="",this.presetRenderer=new rx(t),this.root.host&&(this.positionType==="fixed"?this.root.host.classList.add("vanira-portal"):this.root.host.classList.remove("vanira-portal")),this.clipRegionHandler&&window.removeEventListener(ad,this.clipRegionHandler),this.clipRegionHandler=p=>{var w,b;const m=!!((w=p.detail)!=null&&w.active),v=(b=this.root)==null?void 0:b.host;v&&v.classList.toggle("vanira-clip-suppressed",m)},window.addEventListener(ad,this.clipRegionHandler);const i=document.createElement("style");i.textContent=`@keyframes vanira-slide-up {
|
|
3662
|
+
`,document.head.appendChild(n)}function RN(n,e,t){LN();const i=document.createElement("figure");i.className="vnr-diagram-host-viewer vnr-diagram-host-viewer--minimal",i.setAttribute("aria-label",e.title);const r=document.createElement("div");r.className="vnr-diagram-host-viewer__body";const s=document.createElement("img");s.className="vnr-diagram-host-viewer__img",s.src=e.image_url,s.alt=e.title,s.referrerPolicy="no-referrer",r.appendChild(s),i.appendChild(r),n.innerHTML="",n.dataset.vnrDiagramHost="true",n.appendChild(i)}const ox="vanira:diagram_search_result";function bg(n){if(!n||typeof n!="object")return null;const e=n;if(e.found!==!0)return null;const t=e.image;if(!t||typeof t!="object")return null;const i=t,r=String(i.image_url??"").trim();return r?{image_url:r,title:String(i.title??"Educational diagram").trim()||"Educational diagram",page_url:String(i.page_url??"").trim(),file_type:i.file_type!=null?String(i.file_type):void 0,width:typeof i.width=="number"?i.width:void 0,height:typeof i.height=="number"?i.height:void 0}:null}function Ax(n){return bg(n)!==null}function Uw(n){typeof window>"u"||window.dispatchEvent(new CustomEvent(ox,{detail:n}))}function uh(n){return n.data??n}const cx="http://127.0.0.1:8000/diagram-search";function _N(){return typeof window<"u"?`${window.location.origin}/vanira-api/diagram-search`:cx}function lx(n){const t=uh(n).client_fields??n.client_fields,i=t&&typeof t=="object"?{...t}:{};if(typeof window>"u")return i;const r=window.__vaniraDiagramSearchClientFields;if(!r||typeof r!="object")return i;const s={...i};for(const A of["element_id","css_selector","route"]){const c=r[A];c!=null&&String(c).trim()&&(s[A]=c)}const a=String(s.element_id??"").trim(),o=String(s.css_selector??"").trim();return a?delete s.css_selector:o||delete s.css_selector,s}function ON(n){const e=uh(n),t=e.arguments??e.args??n.arguments??n.args??{};if(typeof t=="string")try{return JSON.parse(t)}catch{return{}}return typeof t=="object"&&t!==null?t:{}}function hh(n){return String(n??"").trim().toLowerCase()==="diagram_search"}function NN(n){const e=uh(n);return String(e.tool_call_id??e.call_id??n.tool_call_id??"")}async function HN(n,e){const t=sx(lx(n)),i=bg(e);if(!t||!i)return null;const{idOrSelector:r,route:s,target:a}=t;let o=!1;const A=async()=>{const c=await Kf(a);c&&(RN(c,i,e.query),o=!0)};if(s){if(!await DN(s,a,()=>A(),{toolName:"diagram_search"})||!o)return null}else if(await A(),!o)return null;return{...e,render_target:r,rendered_in_dom:!0}}async function Cg(n,e){const t=uh(n),i=String(t.name??t.tool_name??n.name??"");if(!hh(i))return!1;const r=NN(n);if(!r)return!0;const s=ON(n),a=String(s.query??"").trim();if(!a){const o={found:!1,error:"query is required"};return e.sendToolResult(r,o),!0}try{const o=await fetch(_N(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:a})});if(!o.ok){const c=await o.text().catch(()=>"");throw new Error(`diagram-search HTTP ${o.status}${c?`: ${c.slice(0,200)}`:""}`)}const A=await o.json();if(Ax(A)){const c=await HN(n,A);if(c)return Uw(c),e.sendToolResult(r,c),!0;const l={...A,render_fallback:sx(lx(n))?"Host element not found — showing floating diagram viewer.":void 0};return Uw(l),e.sendToolResult(r,l),!0}e.sendToolResult(r,A)}catch(o){const A=o instanceof Error?o.message:String(o);typeof e.sendToolError=="function"?e.sendToolError(r,A):e.sendToolResult(r,{found:!1,error:A})}return!0}const uo=class uo extends jT{constructor(t){super(t);S(this,"vaniraClient",null);S(this,"currentView",null);S(this,"presetRenderer",null);S(this,"boardAbortHandler",null);S(this,"clipRegionHandler",null);S(this,"isPanelOpen",!1);S(this,"callActive",!1);S(this,"callStatus","disconnected");S(this,"micMuted",!1);S(this,"eventSource",null);S(this,"pillAudioCtx",null);S(this,"pillAgentAnalyser",null);S(this,"pillAgentData",null);S(this,"pillActivityRaf",null);S(this,"pillLastTranscriptionAt",0);S(this,"pillActivityState","idle");S(this,"floatingButton",null);S(this,"floatingWelcomeChips",null);S(this,"voiceChatPill",null);S(this,"cleanCardLauncher",null);S(this,"humanPresenceLauncher",null);S(this,"panel",null);S(this,"welcomeChipsData",[]);S(this,"chatAdapter");S(this,"sessionManager",null);S(this,"sessionActive",!1);S(this,"widgetMode","voice_only");S(this,"agentId","");S(this,"prospectGroupId","");S(this,"chatServerUrl","");S(this,"prospectId","");S(this,"chatId",null);S(this,"conversationId",null);S(this,"widgetId","");S(this,"pkKey","");S(this,"chatInitialized",!1);S(this,"primaryColor","#000000");S(this,"secondaryColor","#111111");S(this,"gradient",null);S(this,"positionType","fixed");S(this,"position","bottom-right");S(this,"widgetIcon",null);S(this,"iconConfig",null);S(this,"chatWelcomeMessage",null);this.chatAdapter=new A9,this.processConfig(t)}initSessionManager(){const t=this.widgetId||this.agentId||"default";this.sessionManager=new Kd(t),this.sessionManager.on("tab_took_over",()=>{this.sessionActive=!1,this.showTabConflictBanner("taken_over")}),this.sessionManager.on("session_cleared",()=>{});const i=this.sessionManager.claimSession();return this.sessionActive=i,i}restoreSessionMessages(){var A,c,l;const t=(A=this.sessionManager)==null?void 0:A.getSession();if(!t)return;const i=(l=(c=this.currentView)==null?void 0:c.getChatWindow)==null?void 0:l.call(c);if(!i)return;const r=t.messages.filter(d=>d.content.trim()!==""),s=`vanira_calls_${this.widgetId||this.agentId}`,a=JSON.parse(localStorage.getItem(s)||"[]");if(r.length===0&&a.length===0)return;i.clearMessages();const o=[...r.map((d,u)=>({type:"msg",role:d.role,content:d.content,ts:d.timestamp??u})),...a.map(d=>({type:"call",durationMs:d.durationMs,startedAt:d.startedAt,ts:d.startedAt}))];o.sort((d,u)=>d.ts-u.ts),o.forEach(d=>{d.type==="msg"?i.addMessage(d.role,d.content,d.ts):i.addCallRecord(d.durationMs,d.startedAt)})}showTabConflictBanner(t){var i,r;this.root&&((i=this.root.querySelector(".vanira-tab-conflict-banner"))==null||i.remove(),t==="conflict"&&((r=this.sessionManager)==null||r.forceClaimSession(),this.sessionActive=!0,this.widgetMode.includes("chat")&&this.initializeChatSession(!1)))}playMessageSound(t){try{if(!uo.audioContext){const o=window.AudioContext||window.webkitAudioContext;if(!o)return;uo.audioContext=new o}const i=uo.audioContext;i.state==="suspended"&&i.resume().catch(()=>{});const r=i.createOscillator(),s=i.createGain();r.connect(s),s.connect(i.destination);const a=i.currentTime;t==="send"?(r.type="sine",r.frequency.setValueAtTime(300,a),r.frequency.exponentialRampToValueAtTime(500,a+.05),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.1,a+.01),s.gain.exponentialRampToValueAtTime(.001,a+.1),r.start(a),r.stop(a+.1)):(r.type="sine",r.frequency.setValueAtTime(500,a),r.frequency.exponentialRampToValueAtTime(800,a+.1),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.15,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.2),r.start(a),r.stop(a+.2))}catch{}}handleWelcomePayload(t,i="assistant"){var a,o,A,c,l,d,u,h;if(!t||this.widgetMode==="voice_only")return;t.buttons&&Array.isArray(t.buttons)?this.welcomeChipsData=t.buttons:((a=t.widget)==null?void 0:a.type)==="button_list"&&((o=t.widget.data)!=null&&o.buttons)&&(this.welcomeChipsData=t.widget.data.buttons),this.updateWelcomeChipsVisibility();const r=(c=(A=this.currentView)==null?void 0:A.getChatWindow)==null?void 0:c.call(A);let s=t.text||t.response||t.content||t.message||"";if(!s&&!this.welcomeChipsData.length&&(s="Hey! how can I help you ?"),!s&&typeof t=="string"&&t.trim().startsWith("{"))try{const p=JSON.parse(t);s=p.text||p.response||p.content||p.message||"",((l=p.widget)==null?void 0:l.type)==="button_list"&&((d=p.widget.data)!=null&&d.buttons)&&(this.welcomeChipsData=p.widget.data.buttons)}catch{}if(r){if(!s&&this.welcomeChipsData.length===0)return;const p=(u=this.sessionManager)==null?void 0:u.getSession();(p==null?void 0:p.messages.some(v=>v.content===s&&v.role===i))||(s&&(r.addMessage(i,s),(h=this.sessionManager)==null||h.pushMessage(i,s)),this.welcomeChipsData.length>0&&r.addButtons(this.welcomeChipsData))}}async initializeChatSession(t=!1){var i,r,s,a,o;if(this.sessionActive&&!this.chatInitialized){this.chatInitialized=!0;try{Vr.setChatUrl(this.chatServerUrl);const A=(i=this.sessionManager)==null?void 0:i.getSession();if(!t&&(A!=null&&A.prospectId)){this.prospectId=A.prospectId,this.chatId=A.chatId,this.conversationId=A.conversationId||null,this.restoreSessionMessages(),this.chatId&&!this.eventSource&&(this.eventSource=Vr.listenForAdminReplies(this.chatId,this.prospectId,l=>{var d,u,h;(u=(d=this.currentView)==null?void 0:d.getChatWindow)==null||u.call(d).addMessage("assistant",l),(h=this.sessionManager)==null||h.pushMessage("assistant",l),this.playMessageSound("receive")}));return}this.prospectId||(this.prospectGroupId?this.prospectId=await Vr.createChatProspect(this.prospectGroupId):this.prospectId=`anon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`);const c=await Vr.fetchWelcomeMessage(this.agentId,this.prospectId,this.widgetId||void 0,this.pkKey||void 0);c&&(this.handleWelcomePayload(c),c.chatId&&!this.chatId&&(this.chatId=c.chatId,this.eventSource||(this.eventSource=Vr.listenForAdminReplies(this.chatId,this.prospectId,l=>{var d,u,h;(u=(d=this.currentView)==null?void 0:d.getChatWindow)==null||u.call(d).addMessage("assistant",l),(h=this.sessionManager)==null||h.pushMessage("assistant",l),this.playMessageSound("receive")}))),c.conversationId&&(this.conversationId=c.conversationId)),(r=this.sessionManager)==null||r.saveIds(this.prospectId,this.chatId,this.conversationId)}catch{const c="Hey! how can I help you ?";(a=(s=this.currentView)==null?void 0:s.getChatWindow)==null||a.call(s).addMessage("assistant",c),(o=this.sessionManager)==null||o.pushMessage("assistant",c)}}}async initialize(t,i){await super.initialize(t),this.processConfig(t),i&&(this.root=i),this.root&&this.ui_renderer(this.root)}processConfig(t){var i,r;if(this.widgetId=t.widgetId||t.widget_id||this.widgetId||"",this.agentId=t.agentId||t.agent_id||this.agentId||"",this.prospectGroupId=t.prospectGroupId||((i=t.client)==null?void 0:i.base_prospect_group_id)||this.prospectGroupId||"",this.widgetMode=t.widgetMode||t.mode||this.widgetMode||"voice_only",this.pkKey=t.pkKey||t.pk_key||t.publicKey||t.public_key||this.pkKey||"",this.primaryColor=t.primaryColor||t.primary_color||"#000000",this.secondaryColor=t.secondaryColor||t.secondary_color||"#111111",this.gradient=t.gradient||null,this.position=t.position||"bottom-right",this.positionType=t.positionType||"fixed",this.widgetIcon=t.widgetIcon||t.icon||null,this.iconConfig=t.iconConfig||t.icon_config||null,this.chatWelcomeMessage=t.chatWelcomeMessage||t.chat_welcome_message||((r=t.agent)==null?void 0:r.chat_welcome_message)||null,typeof this.chatWelcomeMessage=="string")try{this.chatWelcomeMessage=JSON.parse(this.chatWelcomeMessage)}catch{}this.chatServerUrl=t.serverUrl||t.chatServerUrl||"https://inboxapi.vanira.io",this.updateWelcomeChipsVisibility()}async create_call(t="continue"){var i,r,s,a;if(!(this.callActive||!this.agentId)){this.sessionActive||((i=this.sessionManager)==null||i.forceClaimSession(),this.sessionActive=!0),t==="new"&&((r=this.presetRenderer)==null||r.resetBoardSession());try{if(this.callActive=!0,this.micMuted=!1,this.syncMicMuteUi(),this.updateViewCallState(!0),this.updateViewStatus("connecting"),this.updateLauncherVisibility(),this.isPanelOpen&&this.minimizePanel(),!this.pkKey)throw new Error("[VaniraAI Widget] pk-key is required for voice calls");const A=((s=this.config)==null?void 0:s.serverUrl)||((a=this.config)==null?void 0:a.chatServerUrl)||Kc,c=t==="continue"?mc(this.agentId):null,l=new _s({agentId:this.agentId,apiKey:this.pkKey,sessionBehavior:t,prospectId:this.prospectId||(c==null?void 0:c.prospectId)||void 0,callId:t==="continue"?c==null?void 0:c.callId:void 0,backendUrl:A});l.on("session_started",({prospectId:d,callId:u})=>{var h;d&&(this.prospectId=d,(h=this.sessionManager)==null||h.saveIds(d,this.chatId)),u&&om(this.agentId,u,d)}),l.on("connected",()=>this.updateViewStatus("connected")).on("disconnected",()=>this.end_call()).on("error",d=>{this.updateViewStatus("error",d)}).on("transcription",({text:d,isFinal:u})=>{var h,p;d.trim()&&(this.pillLastTranscriptionAt=Date.now()),(p=(h=this.currentView)==null?void 0:h.setTranscription)==null||p.call(h,d,u)}).on("track",({track:d})=>{var u;d.kind==="audio"&&this.setupPillAgentAudio(d),this.widgetMode.includes("avatar")&&d.kind==="video"&&((u=this.currentView)!=null&&u.setVideoTrack)&&this.currentView.setVideoTrack(d)}).on("tool_call",d=>{var p,m,v;if((p=this.presetRenderer)==null?void 0:p.handle(d,w=>{const b=Qo(d.client_fields,d.arguments||d.args,d.name),k=d.tool_call_id;if(Fo(b)&&k){const y=typeof w=="object"&&w!==null?w:{response:w};if(y.status==="cancelled")return;if(b===Q.WriteLatexText&&y.latex_render_ok===!1)try{l.triggerActionInterrupt(),l.sendActionTrigger("latex_format_error",y)}catch{}try{l.sendToolResult(k,y)}catch{}return}if(!(w&&(w.media_id||w.url)&&Mo(b))){if(Uo(b)&&b){const y=typeof w=="object"&&w!==null?w:{response:w};if(y.status==="cancelled")return;const B=fc(b,d.name,d.client_fields);l.triggerActionInterrupt(),l.sendActionTrigger(B,y);return}if(b){const y=fc(b,d.name,d.client_fields);l.triggerInterrupt(y,w)}}},(w,b)=>{var B,E,T;const k=Qo(d.client_fields,d.arguments||d.args,d.name),y=d.tool_call_id;if(Fo(k)&&y){const F=(b==null?void 0:b.status)??"cancelled",L=String(((B=d.client_fields)==null?void 0:B.target_url)||(d.arguments||d.args||{}).target_url||"");try{const D=k===Q.Navigate?((E=this.presetRenderer)==null?void 0:E.getNavigateTerminalResult(F,w,L||void 0))??{status:F,reason:w||"Navigation cancelled",preset_id:k,target_url:L||void 0}:((T=this.presetRenderer)==null?void 0:T.getBoardTerminalResult(F,w,k))??{status:F,reason:w||"User dismissed",preset_id:k};l.sendToolResult(y,D)}catch{}return}if(Mo(k)&&y){try{l.sendToolResult(y,{status:"cancelled",reason:w||"User dismissed",preset_id:k})}catch{}return}if(Uo(k)&&y){try{l.sendToolResult(y,{status:"cancelled",reason:w||"User dismissed",preset_id:k})}catch{}return}try{l.sendToolResult(y,{status:"cancelled",reason:"User dismissed"})}catch{}},l))return;if(hh(d.name)){Cg(d,l);return}const h=new CustomEvent("vaniraai:tool_call",{detail:d,bubbles:!0,composed:!0});(v=(m=this.root)==null?void 0:m.host)==null||v.dispatchEvent(h)}),this.vaniraClient=l,await l.start(),this.boardAbortHandler=d=>{var h;const u=d.detail||{};(h=this.presetRenderer)==null||h.abortBoardTools(u.reason||"Server interrupted",u.toolCallId,u.presetId)},window.addEventListener(cu,this.boardAbortHandler)}catch(o){this.updateViewStatus("error",(o==null?void 0:o.message)||String(o))}}}isCallActive(){var t;return this.callActive&&!!((t=this.vaniraClient)!=null&&t.isConnected)}updateContext(t){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.updateContext(t),!0}catch{return!1}}triggerInterrupt(t,i={}){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.triggerInterrupt(t,i),!0}catch{return!1}}sendToolResult(t,i){var r;if(!((r=this.vaniraClient)!=null&&r.isConnected)||!t)return!1;try{return this.vaniraClient.sendToolResult(t,i),!0}catch{return!1}}end_call(){var r,s;this.boardAbortHandler&&(window.removeEventListener(cu,this.boardAbortHandler),this.boardAbortHandler=null),this.clipRegionHandler&&(window.removeEventListener(ad,this.clipRegionHandler),this.clipRegionHandler=null);const t=(r=this.root)==null?void 0:r.host;t==null||t.classList.remove("vanira-clip-suppressed"),this.callActive=!1,this.callStatus="disconnected",this.micMuted=!1,this.syncMicMuteUi(),this.stopPillActivityMonitor();const i=this.vaniraClient;this.vaniraClient=null,i&&i.stop(),(s=this.presetRenderer)==null||s.teardownSession(),this.updateViewCallState(!1),this.updateLauncherVisibility()}updateViewCallState(t){var i;(i=this.currentView)!=null&&i.setCallActive&&this.currentView.setCallActive(t)}toggleMicMute(){return this.vaniraClient?(this.micMuted=this.vaniraClient.toggleMicrophoneMuted(),this.syncMicMuteUi(),this.micMuted):this.micMuted}syncMicMuteUi(){var t,i,r;(t=this.voiceChatPill)==null||t.setMicMuted(this.micMuted),(r=(i=this.currentView)==null?void 0:i.setMicMuted)==null||r.call(i,this.micMuted)}wireMicMuteControls(){var i,r,s;const t=()=>this.toggleMicMute();(i=this.voiceChatPill)==null||i.bindMicMuteToggle(t),(s=(r=this.currentView)==null?void 0:r.bindMicMuteToggle)==null||s.call(r,t)}updateViewStatus(t,i){var r,s,a,o,A;t==="connecting"?this.callStatus="connecting":t==="connected"?this.callStatus="connected":t==="error"?this.callStatus="error":this.callStatus="disconnected",(r=this.currentView)!=null&&r.setStatus&&this.currentView.setStatus(t,i),this.voiceChatPill&&this.callActive&&!this.isPanelOpen?t==="connected"?(this.pillActivityState="listening",this.voiceChatPill.setActivity("listening"),(a=(s=this.currentView)==null?void 0:s.setActivity)==null||a.call(s,"listening"),this.startPillActivityLoop()):this.voiceChatPill.setStatus(this.callStatus):t==="connected"&&(this.pillActivityState="listening",(A=(o=this.currentView)==null?void 0:o.setActivity)==null||A.call(o,"listening"),this.startPillActivityLoop())}setupPillAgentAudio(t){try{this.pillAudioCtx||(this.pillAudioCtx=new AudioContext),this.pillAudioCtx.state==="suspended"&&this.pillAudioCtx.resume();const i=new MediaStream([t]),r=this.pillAudioCtx.createMediaStreamSource(i);this.pillAgentAnalyser=this.pillAudioCtx.createAnalyser(),this.pillAgentAnalyser.fftSize=256,r.connect(this.pillAgentAnalyser),this.pillAgentData=new Uint8Array(this.pillAgentAnalyser.frequencyBinCount),this.startPillActivityLoop()}catch{}}readPillAgentLevel(){if(!this.pillAgentAnalyser||!this.pillAgentData)return 0;this.pillAgentAnalyser.getByteFrequencyData(this.pillAgentData);let t=0;const i=Math.min(48,this.pillAgentData.length);for(let r=0;r<i;r++)t+=this.pillAgentData[r];return i>0?t/i/255:0}startPillActivityLoop(){if(this.pillActivityRaf!==null)return;const t=()=>{var o,A;if(this.pillActivityRaf=requestAnimationFrame(t),!this.callActive||this.callStatus!=="connected")return;const i=this.readPillAgentLevel(),r=Date.now()-this.pillLastTranscriptionAt<1200,a=i>.06||r?"speaking":"listening";a!==this.pillActivityState&&(this.pillActivityState=a,this.voiceChatPill&&!this.isPanelOpen&&this.voiceChatPill.setActivity(a),(A=(o=this.currentView)==null?void 0:o.setActivity)==null||A.call(o,a))};this.pillActivityRaf=requestAnimationFrame(t)}stopPillActivityMonitor(){this.pillActivityRaf!==null&&(cancelAnimationFrame(this.pillActivityRaf),this.pillActivityRaf=null),this.pillAgentAnalyser=null,this.pillAgentData=null,this.pillLastTranscriptionAt=0,this.pillActivityState="idle",this.pillAudioCtx&&(this.pillAudioCtx.close().catch(()=>{}),this.pillAudioCtx=null)}ui_renderer(t){var c,l,d,u,h;this.root=t,this.root.innerHTML="",this.presetRenderer=new rx(t),this.root.host&&(this.positionType==="fixed"?this.root.host.classList.add("vanira-portal"):this.root.host.classList.remove("vanira-portal")),this.clipRegionHandler&&window.removeEventListener(ad,this.clipRegionHandler),this.clipRegionHandler=p=>{var w,b;const m=!!((w=p.detail)!=null&&w.active),v=(b=this.root)==null?void 0:b.host;v&&v.classList.toggle("vanira-clip-suppressed",m)},window.addEventListener(ad,this.clipRegionHandler);const i=document.createElement("style");i.textContent=`@keyframes vanira-slide-up {
|
|
3663
3663
|
from { opacity:0; transform:translateY(16px); }
|
|
3664
3664
|
to { opacity:1; transform:translateY(0); }
|
|
3665
3665
|
}`,this.root.appendChild(i);const r=document.createElement("style");r.textContent=`
|