obi-sdk 0.6.4 → 0.6.6
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/core/types.d.ts +2 -2
- package/dist/modular/chunks/index-d7a5d2f6.js +6 -0
- package/dist/modular/chunks/index-d7a5d2f6.js.map +1 -0
- package/dist/modular/chunks/{obi-widget-c52bfca4.js → obi-widget-94e8c026.js} +269 -220
- package/dist/modular/chunks/obi-widget-94e8c026.js.map +1 -0
- package/dist/modular/index.js +1 -1
- package/dist/modular/ui.js +10 -10
- package/dist/obi-sdk.standalone.iife.js +6 -6
- package/dist/obi-sdk.standalone.iife.js.map +1 -1
- package/dist/react.es.js +638 -593
- package/dist/react.es.js.map +1 -1
- package/dist/react.umd.js +14 -14
- package/dist/react.umd.js.map +1 -1
- package/package.json +3 -3
- package/dist/modular/chunks/index-d50e99a5.js +0 -6
- package/dist/modular/chunks/index-d50e99a5.js.map +0 -1
- package/dist/modular/chunks/obi-widget-c52bfca4.js.map +0 -1
package/dist/react.umd.js
CHANGED
|
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const r=i.sdp.split(`
|
|
|
39
39
|
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
|
40
40
|
`);A.RTCSessionDescription&&i instanceof A.RTCSessionDescription?arguments[0]=new A.RTCSessionDescription({type:i.type,sdp:r}):i.sdp=r}return t.apply(this,arguments)}}function Cr(A,e){if(!(A.RTCPeerConnection&&A.RTCPeerConnection.prototype))return;const t=A.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(A.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 wr(A,e){if(!(A.RTCPeerConnection&&A.RTCPeerConnection.prototype))return;const t=A.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(A.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>t.apply(this,[s]))})}var E0=Object.freeze({__proto__:null,removeExtmapAllowMixed:Vo,shimAddIceCandidateNullOrEmpty:Cr,shimConnectionState:Go,shimMaxMessageSize:Br,shimParameterlessSetLocalDescription:wr,shimRTCIceCandidate:mr,shimRTCIceCandidateRelayProtocol:Ko,shimSendThrowTypeError:vr});function S0(){let{window:A}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=jl,n=C0(A),i={browserDetails:n,commonShim:E0,extractVersion:pr,disableLog:B0,disableWarnings:v0,sdp:b0};switch(n.browser){case"chrome":if(!id||!Ho||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=id,Cr(A,n),wr(A),ql(A,n),Yl(A),Ho(A,n),zl(A),Ad(A,n),Zl(A),ed(A),nd(A,n),mr(A),Ko(A),Go(A),Br(A,n),vr(A),Vo(A,n);break;case"firefox":if(!gd||!Mo||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=gd,Cr(A,n),wr(A),rd(A,n),Mo(A,n),sd(A),cd(A),od(A),ad(A),ud(A),ld(A),dd(A),hd(A),fd(A),mr(A),Go(A),Br(A,n),vr(A);break;case"safari":if(!Sd||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Sd,Cr(A,n),wr(A),wd(A),bd(A),Bd(A),pd(A),md(A),yd(A),vd(A),Ed(A),mr(A),Ko(A),Br(A,n),vr(A),Vo(A,n);break;default:t("Unsupported browser!");break}return i}S0({window:typeof window>"u"?void 0:window});const U0=10,yr="lk_e2ee",T0={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:U0,keyringSize:16};var oA;(function(A){A.SetKey="setKey",A.RatchetRequest="ratchetRequest",A.KeyRatcheted="keyRatcheted"})(oA||(oA={}));var Qd;(function(A){A.KeyRatcheted="keyRatcheted"})(Qd||(Qd={}));var aA;(function(A){A.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",A.EncryptionError="encryptionError"})(aA||(aA={}));var Fd;(function(A){A.Error="cryptorError"})(Fd||(Fd={}));function Q0(){return F0()||jo()}function jo(){return typeof window.RTCRtpScriptTransform<"u"}function F0(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class T_ extends _t.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,i)=>{j.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},T0),e),this.on(oA.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const i={key:e,participantIdentity:t,keyIndex:n};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(n??0),i),this.emit(oA.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(oA.RatchetRequest,e,t)}}class cA extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var W;(function(A){A[A.NotAllowed=0]="NotAllowed",A[A.ServerUnreachable=1]="ServerUnreachable",A[A.InternalError=2]="InternalError",A[A.Cancelled=3]="Cancelled",A[A.LeaveRequest=4]="LeaveRequest"})(W||(W={}));class re extends cA{constructor(e,t,n,i){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=i,this.reasonName=W[t]}}class $o extends cA{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class jt extends cA{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class k0 extends cA{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ye extends cA{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Wo extends cA{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Jo extends cA{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class kd extends cA{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Po[t]}}var br;(function(A){A.PermissionDenied="PermissionDenied",A.NotFound="NotFound",A.DeviceInUse="DeviceInUse",A.Other="Other"})(br||(br={})),function(A){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?A.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?A.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?A.DeviceInUse:A.Other}A.getFailure=e}(br||(br={}));var Id;(function(A){A[A.InvalidKey=0]="InvalidKey",A[A.MissingKey=1]="MissingKey",A[A.InternalError=2]="InternalError"})(Id||(Id={}));var Q;(function(A){A.Connected="connected",A.Reconnecting="reconnecting",A.SignalReconnecting="signalReconnecting",A.Reconnected="reconnected",A.Disconnected="disconnected",A.ConnectionStateChanged="connectionStateChanged",A.Moved="moved",A.MediaDevicesChanged="mediaDevicesChanged",A.ParticipantConnected="participantConnected",A.ParticipantDisconnected="participantDisconnected",A.TrackPublished="trackPublished",A.TrackSubscribed="trackSubscribed",A.TrackSubscriptionFailed="trackSubscriptionFailed",A.TrackUnpublished="trackUnpublished",A.TrackUnsubscribed="trackUnsubscribed",A.TrackMuted="trackMuted",A.TrackUnmuted="trackUnmuted",A.LocalTrackPublished="localTrackPublished",A.LocalTrackUnpublished="localTrackUnpublished",A.LocalAudioSilenceDetected="localAudioSilenceDetected",A.ActiveSpeakersChanged="activeSpeakersChanged",A.ParticipantMetadataChanged="participantMetadataChanged",A.ParticipantNameChanged="participantNameChanged",A.ParticipantAttributesChanged="participantAttributesChanged",A.ParticipantActive="participantActive",A.RoomMetadataChanged="roomMetadataChanged",A.DataReceived="dataReceived",A.SipDTMFReceived="sipDTMFReceived",A.TranscriptionReceived="transcriptionReceived",A.ConnectionQualityChanged="connectionQualityChanged",A.TrackStreamStateChanged="trackStreamStateChanged",A.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",A.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",A.AudioPlaybackStatusChanged="audioPlaybackChanged",A.VideoPlaybackStatusChanged="videoPlaybackChanged",A.MediaDevicesError="mediaDevicesError",A.ParticipantPermissionsChanged="participantPermissionsChanged",A.SignalConnected="signalConnected",A.RecordingStatusChanged="recordingStatusChanged",A.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",A.EncryptionError="encryptionError",A.DCBufferStatusChanged="dcBufferStatusChanged",A.ActiveDeviceChanged="activeDeviceChanged",A.ChatMessage="chatMessage",A.LocalTrackSubscribed="localTrackSubscribed",A.MetricsReceived="metricsReceived"})(Q||(Q={}));var x;(function(A){A.TrackPublished="trackPublished",A.TrackSubscribed="trackSubscribed",A.TrackSubscriptionFailed="trackSubscriptionFailed",A.TrackUnpublished="trackUnpublished",A.TrackUnsubscribed="trackUnsubscribed",A.TrackMuted="trackMuted",A.TrackUnmuted="trackUnmuted",A.LocalTrackPublished="localTrackPublished",A.LocalTrackUnpublished="localTrackUnpublished",A.ParticipantMetadataChanged="participantMetadataChanged",A.ParticipantNameChanged="participantNameChanged",A.DataReceived="dataReceived",A.SipDTMFReceived="sipDTMFReceived",A.TranscriptionReceived="transcriptionReceived",A.IsSpeakingChanged="isSpeakingChanged",A.ConnectionQualityChanged="connectionQualityChanged",A.TrackStreamStateChanged="trackStreamStateChanged",A.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",A.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",A.MediaDevicesError="mediaDevicesError",A.AudioStreamAcquired="audioStreamAcquired",A.ParticipantPermissionsChanged="participantPermissionsChanged",A.PCTrackAdded="pcTrackAdded",A.AttributesChanged="attributesChanged",A.LocalTrackSubscribed="localTrackSubscribed",A.ChatMessage="chatMessage",A.Active="active"})(x||(x={}));var I;(function(A){A.TransportsCreated="transportsCreated",A.Connected="connected",A.Disconnected="disconnected",A.Resuming="resuming",A.Resumed="resumed",A.Restarting="restarting",A.Restarted="restarted",A.SignalResumed="signalResumed",A.SignalRestarted="signalRestarted",A.Closing="closing",A.MediaTrackAdded="mediaTrackAdded",A.ActiveSpeakersUpdate="activeSpeakersUpdate",A.DataPacketReceived="dataPacketReceived",A.RTPVideoMapUpdate="rtpVideoMapUpdate",A.DCBufferStatusChanged="dcBufferStatusChanged",A.ParticipantUpdate="participantUpdate",A.RoomUpdate="roomUpdate",A.SpeakersChanged="speakersChanged",A.StreamStateChanged="streamStateChanged",A.ConnectionQualityUpdate="connectionQualityUpdate",A.SubscriptionError="subscriptionError",A.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",A.RemoteMute="remoteMute",A.SubscribedQualityUpdate="subscribedQualityUpdate",A.LocalTrackUnpublished="localTrackUnpublished",A.LocalTrackSubscribed="localTrackSubscribed",A.Offline="offline",A.SignalRequestResponse="signalRequestResponse",A.SignalConnected="signalConnected",A.RoomMoved="roomMoved"})(I||(I={}));var k;(function(A){A.Message="message",A.Muted="muted",A.Unmuted="unmuted",A.Restarted="restarted",A.Ended="ended",A.Subscribed="subscribed",A.Unsubscribed="unsubscribed",A.UpdateSettings="updateSettings",A.UpdateSubscription="updateSubscription",A.AudioPlaybackStarted="audioPlaybackStarted",A.AudioPlaybackFailed="audioPlaybackFailed",A.AudioSilenceDetected="audioSilenceDetected",A.VisibilityChanged="visibilityChanged",A.VideoDimensionsChanged="videoDimensionsChanged",A.VideoPlaybackStarted="videoPlaybackStarted",A.VideoPlaybackFailed="videoPlaybackFailed",A.ElementAttached="elementAttached",A.ElementDetached="elementDetached",A.UpstreamPaused="upstreamPaused",A.UpstreamResumed="upstreamResumed",A.SubscriptionPermissionChanged="subscriptionPermissionChanged",A.SubscriptionStatusChanged="subscriptionStatusChanged",A.SubscriptionFailed="subscriptionFailed",A.TrackProcessorUpdate="trackProcessorUpdate",A.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",A.TranscriptionReceived="transcriptionReceived",A.TimeSyncUpdate="timeSyncUpdate"})(k||(k={}));function I0(A){return typeof A>"u"?A:typeof structuredClone=="function"?structuredClone(A):JSON.parse(JSON.stringify(A))}const _0=/version\/(\d+(\.?_?\d+)+)/i;let Xo;function wt(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof A>"u"&&typeof navigator>"u")return;const t=(A??navigator.userAgent).toLowerCase();if(Xo===void 0||e){const n=x0.find(i=>{let{test:r}=i;return r.test(t)});Xo=n?.describe(t)}return Xo}const x0=[{test:/firefox|iceweasel|fxios/i,describe(A){return{name:"Firefox",version:Er(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,A),os:A.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:qo(A)}}},{test:/chrom|crios|crmo/i,describe(A){return{name:"Chrome",version:Er(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,A),os:A.toLowerCase().includes("crios")?"iOS":void 0,osVersion:qo(A)}}},{test:/safari|applewebkit/i,describe(A){return{name:"Safari",version:Er(_0,A),os:A.includes("mobile/")?"iOS":"macOS",osVersion:qo(A)}}}];function Er(A,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(A);return n&&n.length>=t&&n[t]||""}function qo(A){return A.includes("mac os")?Er(/\(.+?(\d+_\d+(:?_\d+)?)/,A,1).replace(/_/g,"."):void 0}var R0="2.13.0";const P0=R0,D0=16;class Te{}Te.setTimeout=function(){return setTimeout(...arguments)},Te.setInterval=function(){return setInterval(...arguments)},Te.clearTimeout=function(){return clearTimeout(...arguments)},Te.clearInterval=function(){return clearInterval(...arguments)};const L0=5e3,ni=[];var ot;(function(A){A[A.LOW=0]="LOW",A[A.MEDIUM=1]="MEDIUM",A[A.HIGH=2]="HIGH"})(ot||(ot={}));class U extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=U.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=j,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),L0):this.handleAppVisibilityChanged()},this.log=Vt((i=n.loggerName)!==null&&i!==void 0?i:Ct.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=U.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Z(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===U.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===U.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(ni.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&ni.splice(ni.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Cn(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),i=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(i?k.AudioPlaybackStarted:k.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(i?k.AudioPlaybackFailed:k.VideoPlaybackFailed,r):r.name==="AbortError"?j.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):j.warn("could not playback ".concat(i?"audio":"video"),r),i&&e&&n.some(s=>s.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(k.ElementAttached,e),e}detach(e){try{if(e){wn(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(k.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{wn(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(k.ElementDetached,n)}),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=Vt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ni.forEach(n=>{n.parentElement||(t=!1)}),t&&ni.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===U.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Xe()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Xe()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Cn(A,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;A.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(A)||(n.forEach(i=>{t.removeTrack(i)}),t.addTrack(A)),(!uA()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(uA()||yn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function wn(A,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(A),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(A){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=A.Kind||(A.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=A.Source||(A.Source={}));let n;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(n=A.StreamState||(A.StreamState={}));function i(c){switch(c){case e.Audio:return pt.AUDIO;case e.Video:return pt.VIDEO;default:return pt.DATA}}A.kindToProto=i;function r(c){switch(c){case pt.AUDIO:return e.Audio;case pt.VIDEO:return e.Video;default:return e.Unknown}}A.kindFromProto=r;function s(c){switch(c){case t.Camera:return ve.CAMERA;case t.Microphone:return ve.MICROPHONE;case t.ScreenShare:return ve.SCREEN_SHARE;case t.ScreenShareAudio:return ve.SCREEN_SHARE_AUDIO;default:return ve.UNKNOWN}}A.sourceToProto=s;function o(c){switch(c){case ve.CAMERA:return t.Camera;case ve.MICROPHONE:return t.Microphone;case ve.SCREEN_SHARE:return t.ScreenShare;case ve.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}A.sourceFromProto=o;function a(c){switch(c){case Qo.ACTIVE:return n.Active;case Qo.PAUSED:return n.Paused;default:return n.Unknown}}A.streamStateFromProto=a})(U||(U={}));class ie{constructor(e,t,n,i,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const O0=["vp8","h264"],H0=["vp8","h264","vp9","av1"];function M0(A){return!!O0.find(e=>e===A)}var _d;(function(A){A[A.PREFER_REGRESSION=0]="PREFER_REGRESSION",A[A.SIMULCAST=1]="SIMULCAST",A[A.REGRESSION=2]="REGRESSION"})(_d||(_d={}));var Yo;(function(A){A.telephone={maxBitrate:12e3},A.speech={maxBitrate:24e3},A.music={maxBitrate:48e3},A.musicStereo={maxBitrate:64e3},A.musicHighQuality={maxBitrate:96e3},A.musicHighQualityStereo={maxBitrate:128e3}})(Yo||(Yo={}));const ii={h90:new ie(160,90,9e4,20),h180:new ie(320,180,16e4,20),h216:new ie(384,216,18e4,20),h360:new ie(640,360,45e4,20),h540:new ie(960,540,8e5,25),h720:new ie(1280,720,17e5,30),h1080:new ie(1920,1080,3e6,30),h1440:new ie(2560,1440,5e6,30),h2160:new ie(3840,2160,8e6,30)},zo={h120:new ie(160,120,7e4,20),h180:new ie(240,180,125e3,20),h240:new ie(320,240,14e4,20),h360:new ie(480,360,33e4,20),h480:new ie(640,480,5e5,20),h540:new ie(720,540,6e5,25),h720:new ie(960,720,13e5,30),h1080:new ie(1440,1080,23e5,30),h1440:new ie(1920,1440,38e5,30)},Zo={h360fps3:new ie(640,360,2e5,3,"medium"),h360fps15:new ie(640,360,4e5,15,"medium"),h720fps5:new ie(1280,720,8e5,5,"medium"),h720fps15:new ie(1280,720,15e5,15,"medium"),h720fps30:new ie(1280,720,2e6,30,"medium"),h1080fps15:new ie(1920,1080,25e5,15,"medium"),h1080fps30:new ie(1920,1080,5e6,30,"medium"),original:new ie(0,0,7e6,30,"medium")},N0="|",xd="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function K0(A){const e=A.split(N0);return e.length>1?[e[0],A.substr(e[0].length+1)]:[A,""]}function Je(A){return m(this,void 0,void 0,function*(){return new Promise(e=>Te.setTimeout(e,A))})}function ea(){return"addTransceiver"in RTCPeerConnection.prototype}function ta(){return"addTrack"in RTCPeerConnection.prototype}function G0(){if(!("getCapabilities"in RTCRtpSender)||uA())return!1;const A=RTCRtpSender.getCapabilities("video");let e=!1;if(A){for(const t of A.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function V0(){if(!("getCapabilities"in RTCRtpSender)||yn())return!1;if(uA()){const t=wt();if(t?.version&&NA(t.version,"16")<0)return!1}const A=RTCRtpSender.getCapabilities("video");let e=!1;if(A){for(const t of A.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function ri(A){return A==="av1"||A==="vp9"}function Aa(A){return document?(A||(A=document.createElement("audio")),"setSinkId"in A):!1}function j0(){return typeof RTCPeerConnection>"u"?!1:ea()||ta()}function yn(){var A;return((A=wt())===null||A===void 0?void 0:A.name)==="Firefox"}function uA(){var A;return((A=wt())===null||A===void 0?void 0:A.name)==="Safari"}function $0(){const A=wt();return A?.name==="Safari"&&A.version.startsWith("17.")}function Rd(){var A,e;return Xe()?(e=(A=navigator.userAgentData)===null||A===void 0?void 0:A.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function W0(){const A=wt(),e="17.2";if(A)return A.name!=="Safari"&&A.os!=="iOS"||A.os==="iOS"&&A.osVersion&&NA(e,A.osVersion)>=0?!0:A.name==="Safari"&&NA(e,A.version)>=0}function Xe(){return typeof document<"u"}function xt(){return navigator.product=="ReactNative"}function na(A){return A.hostname.endsWith(".livekit.cloud")||A.hostname.endsWith(".livekit.run")}function Pd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Dd(){if(!xt())return;let A=Pd();if(A)return A.platform}function Ld(){if(Xe())return window.devicePixelRatio;if(xt()){let A=Pd();if(A)return A.devicePixelRatio}return 1}function NA(A,e){const t=A.split("."),n=e.split("."),i=Math.min(t.length,n.length);for(let r=0;r<i;++r){const s=parseInt(t[r],10),o=parseInt(n[r],10);if(s>o)return 1;if(s<o)return-1;if(r===i-1&&s===o)return 0}return A===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function J0(A){for(const e of A)e.target.handleResize(e)}function X0(A){for(const e of A)e.target.handleVisibilityChanged(e)}let ia=null;const Od=()=>(ia||(ia=new ResizeObserver(J0)),ia);let ra=null;const Hd=()=>(ra||(ra=new IntersectionObserver(X0,{root:null,rootMargin:"0px"})),ra);function q0(){var A;const e=new HB({sdk:bl.JS,protocol:D0,version:P0});return xt()&&(e.os=(A=Dd())!==null&&A!==void 0?A:""),e}function Md(){let A=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,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=A,i.height=e;const r=i.getContext("2d");r?.fillRect(0,0,i.width,i.height),n&&r&&(r.beginPath(),r.arc(A/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const s=i.captureStream(),[o]=s.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let si;function sa(){if(!si){const A=new AudioContext,e=A.createOscillator(),t=A.createGain();t.gain.setValueAtTime(0,0);const n=A.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[si]=n.stream.getAudioTracks(),!si)throw Error("Could not get empty media stream audio track");si.enabled=!1}return si.clone()}class oa{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,i)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=i,e&&(yield e(n,i))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}function Y0(A){return H0.includes(A)}function lA(A){if(typeof A=="string"||typeof A=="number")return A;if(Array.isArray(A))return A[0];if(A.exact)return Array.isArray(A.exact)?A.exact[0]:A.exact;if(A.ideal)return Array.isArray(A.ideal)?A.ideal[0]:A.ideal;throw Error("could not unwrap constraint")}function z0(A){return A.startsWith("http")?A.replace(/^(http)/,"ws"):A}function aa(A){return A.startsWith("ws")?A.replace(/^(ws)/,"http"):A}function Z0(A,e){return A.segments.map(t=>{let{id:n,text:i,language:r,startTime:s,endTime:o,final:a}=t;var c;const u=(c=e.get(n))!==null&&c!==void 0?c:Date.now(),l=Date.now();return a?e.delete(n):e.set(n,u),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:r,firstReceivedTime:u,lastReceivedTime:l}})}function ev(A){const{id:e,timestamp:t,message:n,editTimestamp:i}=A;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:n}}function Nd(A){switch(A.reason){case W.LeaveRequest:return A.context;case W.Cancelled:return mt.CLIENT_INITIATED;case W.NotAllowed:return mt.USER_REJECTED;case W.ServerUnreachable:return mt.JOIN_FAILURE;default:return mt.UNKNOWN_REASON}}function Sr(A){return A!==void 0?Number(A):void 0}function KA(A){return A!==void 0?BigInt(A):void 0}function bn(A){return!!A&&!(A instanceof MediaStreamTrack)&&A.isLocal}function $t(A){return!!A&&A.kind==U.Kind.Audio}function En(A){return!!A&&A.kind==U.Kind.Video}function dA(A){return bn(A)&&En(A)}function GA(A){return bn(A)&&$t(A)}function ca(A){return!!A&&!A.isLocal}function tv(A){return!!A&&!A.isLocal}function ua(A){return ca(A)&&En(A)}function Av(A){return A.isLocal}function nv(A,e){const t=[];let n=new TextEncoder().encode(A);for(;n.length>e;){let i=e;for(;i>0;){const r=n[i];if(r!==void 0&&(r&192)!==128)break;i--}t.push(n.slice(0,i)),n=n.slice(i)}return n.length>0&&t.push(n),t}function Kd(A,e,t){var n,i,r,s;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:c}=$d(A??{}),u=e?.processor,l=t?.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(la(d.audio,e),(n=(r=d.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(a||u)&&(d.audio.processor=a??u)),d.video&&(la(d.video,t),(i=(s=d.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||l)&&(d.video.processor=c??l)),d}function la(A,e){return Object.keys(e).forEach(t=>{A[t]===void 0&&(A[t]=e[t])}),A}function da(A){var e,t,n,i;const r={};if(A.video)if(typeof A.video=="object"){const s={},o=s,a=A.video;Object.keys(a).forEach(c=>{switch(c){case"resolution":la(o,a.resolution);break;default:o[c]=a[c]}}),r.video=s,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=A.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return A.audio?typeof A.audio=="object"?(r.audio=A.audio,(t=(i=r.audio).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Gd(A){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=Vd();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=i.frequencyBinCount,s=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Je(t),i.getByteTimeDomainData(s);const a=s.some(c=>c!==128&&c!==0);return n.close(),!a}return!1}()})}function Vd(){var A;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((A=window.document)===null||A===void 0)&&A.body)){const n=()=>m(this,void 0,void 0,function*(){var i;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",n)});window.document.body.addEventListener("click",n)}return t}}function iv(A){return A==="audioinput"?U.Source.Microphone:A==="videoinput"?U.Source.Camera:U.Source.Unknown}function jd(A){return A===U.Source.Microphone?"audioinput":A===U.Source.Camera?"videoinput":void 0}function rv(A){var e,t;let n=(e=A.video)!==null&&e!==void 0?e:!0;return A.resolution&&A.resolution.width>0&&A.resolution.height>0&&(n=typeof n=="boolean"?{}:n,uA()?n=Object.assign(Object.assign({},n),{width:{max:A.resolution.width},height:{max:A.resolution.height},frameRate:A.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:A.resolution.width},height:{ideal:A.resolution.height},frameRate:A.resolution.frameRate})),{audio:(t=A.audio)!==null&&t!==void 0?t:!1,video:n,controller:A.controller,selfBrowserSurface:A.selfBrowserSurface,surfaceSwitching:A.surfaceSwitching,systemAudio:A.systemAudio,preferCurrentTab:A.preferCurrentTab}}function Ur(A){return A.split("/")[1].toLowerCase()}function sv(A){const e=[];return A.forEach(t=>{t.track!==void 0&&e.push(new xo({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Z(A){return"mediaStreamTrack"in A?{trackID:A.sid,source:A.source,muted:A.isMuted,enabled:A.mediaStreamTrack.enabled,kind:A.kind,streamID:A.mediaStreamID,streamTrackID:A.mediaStreamTrack.id}:{trackID:A.trackSid,enabled:A.isEnabled,muted:A.isMuted,trackInfo:Object.assign({mimeType:A.mimeType,name:A.trackName,encrypted:A.isEncrypted,kind:A.kind,source:A.source},A.track?Z(A.track):{})}}function ov(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function av(A,e){var t;A===void 0&&(A={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(A)],i={};for(const r of n)A[r]!==e[r]&&(i[r]=(t=e[r])!==null&&t!==void 0?t:"");return i}function $d(A){const e=Object.assign({},A);let t,n;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&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:I0(e)}}function cv(A){switch(A){case ve.CAMERA:return U.Source.Camera;case ve.MICROPHONE:return U.Source.Microphone;case ve.SCREEN_SHARE:return U.Source.ScreenShare;case ve.SCREEN_SHARE_AUDIO:return U.Source.ScreenShareAudio;default:return U.Source.Unknown}}class uv extends _t.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,i;const{kind:r,data:s}=t.data;switch(r){case"error":j.error(s.error.message),this.emit(aA.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(aA.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(aA.ParticipantEncryptionStatusChanged,s.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(oA.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=t=>{j.error("e2ee worker encountered an error:",{error:t.error}),this.emit(aA.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Q0())throw new $o("tried to setup end-to-end encryption on an unsupported browser");if(j.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:h0.getLevel()}};this.worker&&(j.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){j.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?j.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(I.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(Q.TrackPublished,(n,i)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==tt.NONE,i.identity)),e.on(Q.ConnectionStateChanged,n=>{n===z.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==tt.NONE,i.identity)})})}).on(Q.TrackUnsubscribed,(n,i,r)=>{var s;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(o)}).on(Q.TrackSubscribed,(n,i,r)=>{this.setupE2EEReceiver(n,r.identity,i.trackInfo)}).on(Q.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(x.LocalTrackPublished,n=>m(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(oA.SetKey,n=>this.postKey(n)).on(oA.RatchetRequest,(n,i)=>this.postRatchetRequest(n,i))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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,n){if(e.receiver){if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Ur(n.mimeType):void 0)}}setupE2EESender(e,t){if(!bn(e)||!t){t||j.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,i){return m(this,void 0,void 0,function*(){if(this.worker){if(jo()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(yr in e&&i){const a={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}};this.worker.postMessage(a);return}let r=e.writableStream,s=e.readableStream;if(!r||!s){const a=e.createEncodedStreams();e.writableStream=a.writable,r=a.writable,e.readableStream=a.readable,s=a.readable}const o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:i,participantIdentity:n}};this.worker.postMessage(o,[s,r])}e[yr]=!0}})}handleSender(e,t,n){var i;if(!(yr in e||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(jo()){j.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{j.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[r.readable,r.writable])}e[yr]=!0}}}const ha="default";class Ee{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Ee),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;if(((r=Ee.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){j.debug("awaiting getUserMedia promise");try{t?yield Ee.userMediaPromiseMap.get(t):yield Promise.all(Ee.userMediaPromiseMap.values())}catch{j.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(uA()&&n.hasDeviceInUse(t))&&(s.filter(a=>a.kind===t).length===0||s.some(a=>{const c=a.label==="",u=t?a.kind===t:!0;return c&&u}))){const a={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(u=>{u.stop()})}return n._previousDevices=s,t&&(s=s.filter(o=>o.kind===t)),s}()})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==ha)return t;const i=yield this.getDevices(e),r=i.find(o=>o.deviceId===ha);if(!r){j.warn("could not reliably determine default device");return}const s=i.find(o=>o.deviceId!==ha&&o.groupId===(n??r.groupId));if(!s){j.warn("could not reliably determine default device");return}return s?.deviceId})}hasDeviceInUse(e){return e?Ee.userMediaPromiseMap.has(e):Ee.userMediaPromiseMap.size>0}}Ee.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ee.userMediaPromiseMap=new Map;var oi;(function(A){A[A.WAITING=0]="WAITING",A[A.RUNNING=1]="RUNNING",A[A.COMPLETED=2]="COMPLETED"})(oi||(oi={}));class lv{constructor(){this.pendingTasks=new Map,this.taskMutex=new je,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:oi.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=oi.RUNNING,yield e()}finally{t.status=oi.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function dv(A,e){const t=new URL(z0(A));return e.forEach((n,i)=>{t.searchParams.set(i,n)}),Wd(t,"rtc")}function hv(A){const e=new URL(aa(A));return Wd(e,"validate")}function fv(A){return A.endsWith("/")?A:"".concat(A,"/")}function Wd(A,e){return A.pathname="".concat(fv(A.pathname)).concat(e),A.toString()}const gv=["syncState","trickle","offer","answer","simulate","leave"];function pv(A){const e=gv.indexOf(A.case)>=0;return j.trace("request allowed to bypass queue:",{canPass:e,req:A}),e}var oe;(function(A){A[A.CONNECTING=0]="CONNECTING",A[A.CONNECTED=1]="CONNECTED",A[A.RECONNECTING=2]="RECONNECTING",A[A.DISCONNECTING=3]="DISCONNECTING",A[A.DISCONNECTED=4]="DISCONNECTED"})(oe||(oe={}));class fa{get currentState(){return this.state}get isDisconnected(){return this.state===oe.DISCONNECTING||this.state===oe.DISCONNECTED}get isEstablishingConnection(){return this.state===oe.CONNECTING||this.state===oe.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 n;this.rtt=0,this.state=oe.DISCONNECTED,this.log=j,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Vt((n=t.loggerName)!==null&&n!==void 0?n:Ct.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new lv,this.queuedRequests=[],this.closingLock=new je,this.connectionLock=new je,this.state=oe.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,n,i){return m(this,void 0,void 0,function*(){return this.state=oe.CONNECTING,this.options=n,yield this.connect(e,t,n,i)})}reconnect(e,t,n,i){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=oe.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))})}connect(e,t,n,i){this.connectOptions=n;const r=q0(),s=mv(t,r,n),o=dv(e,s),a=hv(o);return new Promise((c,u)=>m(this,void 0,void 0,function*(){const l=yield this.connectionLock.lock();try{const d=()=>m(this,void 0,void 0,function*(){this.close(),clearTimeout(h),u(new re("room connection has been cancelled (signal)",W.Cancelled))}),h=setTimeout(()=>{this.close(),u(new re("room connection has timed out (signal)",W.ServerUnreachable))},n.websocketTimeout);i?.aborted&&d(),i?.addEventListener("abort",d);const f=new URL(o);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=g=>m(this,void 0,void 0,function*(){if(this.state!==oe.CONNECTED){this.state=oe.DISCONNECTED,clearTimeout(h);try{const p=yield fetch(a);if(p.status.toFixed(0).startsWith("4")){const B=yield p.text();u(new re(B,W.NotAllowed,p.status))}else u(new re("Encountered unknown websocket error during connection: ".concat(g.toString()),W.InternalError,p.status))}catch(p){u(new re(p instanceof Error?p.message:"server was not reachable",W.ServerUnreachable))}return}this.handleWSError(g)}),this.ws.onmessage=g=>m(this,void 0,void 0,function*(){var p,B,y;let b;if(typeof g.data=="string"){const v=JSON.parse(g.data);b=Fl.fromJson(v,{ignoreUnknownFields:!0})}else if(g.data instanceof ArrayBuffer)b=Fl.fromBinary(new Uint8Array(g.data));else{this.log.error("could not decode websocket message: ".concat(typeof g.data),this.logContext);return}if(this.state!==oe.CONNECTED){let v=!1;if(((p=b.message)===null||p===void 0?void 0:p.case)==="join"?(this.state=oe.CONNECTED,i?.removeEventListener("abort",d),this.pingTimeoutDuration=b.message.value.pingTimeout,this.pingIntervalDuration=b.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),c(b.message.value)):this.state===oe.RECONNECTING&&b.message.case!=="leave"?(this.state=oe.CONNECTED,i?.removeEventListener("abort",d),this.startPingInterval(),((B=b.message)===null||B===void 0?void 0:B.case)==="reconnect"?c(b.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),v=!0)):this.isEstablishingConnection&&b.message.case==="leave"?u(new re("Received leave request while trying to (re)connect",W.LeaveRequest,void 0,b.message.value.reason)):n.reconnect||u(new re("did not receive join response, got ".concat((y=b.message)===null||y===void 0?void 0:y.case," instead"),W.InternalError)),!v)return}this.signalLatency&&(yield Je(this.signalLatency)),this.handleSignalResponse(b)}),this.ws.onclose=g=>{this.isEstablishingConnection&&u(new re("Websocket got closed during a (re)connection attempt",W.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:g.reason,code:g.code,wasClean:g.wasClean,state:this.state})),this.handleOnClose(g.reason)}}finally{l()}}))}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=oe.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,Je(250)])),e.ws=void 0}}finally{t&&(e.state=oe.DISCONNECTED),n()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Tr(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Tr(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Io({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new _o({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new xl({requestId:o,metadata:n,name:i,attributes:s})}),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 _l({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Dl({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ue.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Hl({timestamp:ue.parse(Date.now()),rtt:ue.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Il({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new dr({reason:mt.CLIENT_INITIATED,action:Bn.DISCONNECT})})}sendRequest(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!pv(t)&&n.state===oe.RECONNECTING){n.queuedRequests.push(()=>m(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(i||(yield n.requestQueue.flush()),n.signalLatency&&(yield Je(n.signalLatency)),!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(t?.case),n.logContext);return}const s=new KB({message:t});try{n.useJSON?n.ws.send(s.toJsonString()):n.ws.send(s.toBinary())}catch(o){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,n;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(i.case==="answer"){const s=Jd(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=Jd(i.value);this.onOffer&&this.onOffer(s)}else if(i.case==="trickle"){const s=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(s,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=i.value.participants)!==null&&t!==void 0?t:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=i.value.speakers)!==null&&n!==void 0?n:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,void 0,void 0,function*(){if(this.state===oe.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Te.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Te.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Te.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Te.clearInterval(this.pingInterval)}}function Jd(A){const e={type:"offer",sdp:A.sdp};switch(A.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=A.type;break}return e}function Tr(A){return new HA({sdp:A.sdp,type:A.type})}function mv(A,e,t){var n;const i=new URLSearchParams;return i.set("access_token",A),t.reconnect&&(i.set("reconnect","1"),t.sid&&i.set("sid",t.sid)),i.set("auto_subscribe",t.autoSubscribe?"1":"0"),i.set("sdk",xt()?"reactnative":"js"),i.set("version",e.version),i.set("protocol",e.protocol.toString()),e.deviceModel&&i.set("device_model",e.deviceModel),e.os&&i.set("os",e.os),e.osVersion&&i.set("os_version",e.osVersion),e.browser&&i.set("browser",e.browser),e.browserVersion&&i.set("browser_version",e.browserVersion),t.adaptiveStream&&i.set("adaptive_stream","1"),t.reconnectReason&&i.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&i.set("network",navigator.connection.type),i}var yt={},ga={},pa={exports:{}},Xd;function ma(){if(Xd)return pa.exports;Xd=1;var A=pa.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(A).forEach(function(e){var t=A[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),pa.exports}var qd;function Bv(){return qd||(qd=1,function(A){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,a,c,u){if(u&&!c)a[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(a[c[l]]=e(o[l+1]))},n=function(o,a,c){var u=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:u&&!a[o.name]&&(a[o.name]={});var l=o.push?{}:u?a[o.name]:a;t(c.match(o.reg),l,o.names,o.name),o.push&&a[o.push].push(l)},i=ma(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);A.parse=function(o){var a={},c=[],u=a;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(l){var d=l[0],h=l.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(i[d]||[]).length;f+=1){var g=i[d][f];if(g.reg.test(h))return n(g,u,h)}}),a.media=c,a};var s=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};A.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(o){return o.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(o){for(var a=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)a.push({component:c[u],ip:c[u+1],port:c[u+2]});return a},A.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(s,{})})},A.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(c){var u,l=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),l=!0),{scid:u,paused:l}})})}}(ga)),ga}var Ba,Yd;function vv(){if(Yd)return Ba;Yd=1;var A=ma(),e=/%[sdv%]/g,t=function(s){var o=1,a=arguments,c=a.length;return s.replace(e,function(u){if(o>=c)return u;var l=a[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},n=function(s,o,a){var c=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,u=[s+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var d=o.names[l];o.name?u.push(a[o.name][d]):u.push(a[o.names[l]])}else u.push(a[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Ba=function(s,o){o=o||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(l){l.payloads==null&&(l.payloads="")});var a=o.outerOrder||i,c=o.innerOrder||r,u=[];return a.forEach(function(l){A[l].forEach(function(d){d.name in s&&s[d.name]!=null?u.push(n(l,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){u.push(n(l,d,h))})})}),s.media.forEach(function(l){u.push(n("m",A.m[0],l)),c.forEach(function(d){A[d].forEach(function(h){h.name in l&&l[h.name]!=null?u.push(n(d,h,l)):h.push in l&&l[h.push]!=null&&l[h.push].forEach(function(f){u.push(n(d,h,f))})})})}),u.join(`\r
|
|
41
41
|
`)+`\r
|
|
42
|
-
`},Ba}var zd;function Cv(){if(zd)return yt;zd=1;var A=Bv(),e=vv(),t=ma();return yt.grammar=t,yt.write=e,yt.parse=A.parse,yt.parseParams=A.parseParams,yt.parseFmtpConfig=A.parseFmtpConfig,yt.parsePayloads=A.parsePayloads,yt.parseRemoteCandidates=A.parseRemoteCandidates,yt.parseImageAttributes=A.parseImageAttributes,yt.parseSimulcastStreamList=A.parseSimulcastStreamList,yt}var hA=Cv();function va(A,e,t){var n,i,r;e===void 0&&(e=50),t===void 0&&(t={});var s=(n=t.isImmediate)!=null&&n,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(g,p){var B=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var b=A.apply(f,h);o&&o(b),u.forEach(function(v){return(0,v.resolve)(b)}),u=[]}},l()),B){var y=A.apply(f,h);return o&&o(y),g(y)}u.push({resolve:g,reject:p})})};return d.cancel=function(h){r!==void 0&&clearTimeout(r),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const wv=.7,yv=20,Sn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Zd extends _t.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 n;super(),this.log=j,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=va(i=>m(this,void 0,void 0,function*(){this.emit(Sn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),yv),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Vt((n=t.loggerName)!==null&&n!==void 0?n:Ct.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return m(this,void 0,void 0,function*(){var t;let n;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=bv(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=hA.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of r.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),n=hA.write(i)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Sn.NegotiationComplete),e.sdp&&hA.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Sn.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const r=this._pc.remoteDescription;if(e?.iceRestart&&r)yield this._pc.setRemoteDescription(r);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const i=hA.parse((t=n.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{th(r),r.type==="audio"?eh(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(ri(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*wv);for(const c of r.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(n,hA.write(i)),this.onOffer(n)})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=hA.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(i=>{th(i),i.type==="audio"&&eh(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,hA.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ye("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 ye("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=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),n.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Wo(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!((n=e.ext)===null||n===void 0?void 0:n.some(s=>s.uri===xd))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:xd})}}}function eh(A,e,t){let n=0;A.rtp.some(i=>i.codec==="opus"?(n=i.payload,!0):!1),n>0&&(A.rtcpFb||(A.rtcpFb=[]),t.includes(A.mid)&&!A.rtcpFb.some(i=>i.payload===n&&i.type==="nack")&&A.rtcpFb.push({payload:n,type:"nack"}),e.includes(A.mid)&&A.fmtp.some(i=>i.payload===n?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function bv(A){var e;const t=[],n=[],i=hA.parse((e=A.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===r&&a.type==="nack")&&n.push(s.mid),s.fmtp.some(a=>a.payload===r?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function th(A){if(A.connection){const e=A.connection.ip.indexOf(":")>=0;(A.connection.version===4&&e||A.connection.version===6&&!e)&&(A.connection.ip="0.0.0.0",A.connection.version=4)}}const Ca="vp8",Ev={audioPreset:Yo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Zo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ca,backupCodec:!0},Ah={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},nh={deviceId:{ideal:"default"},resolution:ii.h720.resolution},Sv={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new g0,disconnectOnPageLeave:!0,webAudioMix:!1},wa={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var he;(function(A){A[A.NEW=0]="NEW",A[A.CONNECTING=1]="CONNECTING",A[A.CONNECTED=2]="CONNECTED",A[A.FAILED=3]="FAILED",A[A.CLOSING=4]="CLOSING",A[A.CLOSED=5]="CLOSED"})(he||(he={}));class Uv{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var i;this.peerConnectionTimeout=wa.peerConnectionTimeout,this.log=j,this.updateState=()=>{var r;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=he.CONNECTED:o.some(a=>a==="failed")?this.state=he.FAILED:o.some(a=>a==="connecting")?this.state=he.CONNECTING:o.every(a=>a==="closed")?this.state=he.CLOSED:o.some(a=>a==="closed")?this.state=he.CLOSING:o.every(a=>a==="new")&&(this.state=he.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(he[s]," to ").concat(he[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Vt((i=n.loggerName)!==null&&i!==void 0?i:Ct.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Zd(e,n),this.subscriber=new Zd(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,vt.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,vt.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=he.NEW,this.connectionLock=new je,this.remoteOfferLock=new je}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===vt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;const i=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{i()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Sn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Sn.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),n(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===vt.PUBLISHER?this.publisher.getConnectedAddress():e===vt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((a,c)=>m(r,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Te.clearTimeout(l),c(new re("room connection has been cancelled",W.Cancelled))};i?.signal.aborted&&u(),i?.signal.addEventListener("abort",u);const l=Te.setTimeout(()=>{i?.signal.removeEventListener("abort",u),c(new re("could not establish pc connection",W.InternalError))},s);for(;this.state!==he.CONNECTED;)if(yield Je(50),i?.signal.aborted){c(new re("room connection has been cancelled",W.Cancelled));return}Te.clearTimeout(l),i?.signal.removeEventListener("abort",u),a()}))}()})}}class fe extends Error{constructor(e,t,n){super(t),this.code=e,this.message=rh(t,fe.MAX_MESSAGE_BYTES),this.data=n?rh(n,fe.MAX_DATA_BYTES):void 0}static fromProto(e){return new fe(e.code,e.message,e.data)}toProto(){return new Cl({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new fe(fe.ErrorCode[e],fe.ErrorMessage[e],t)}}fe.MAX_MESSAGE_BYTES=256,fe.MAX_DATA_BYTES=15360,fe.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},fe.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 ih=15360;function ya(A){return new TextEncoder().encode(A).length}function rh(A,e){if(ya(A)<=e)return A;let t=0,n=A.length;const i=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);i.encode(A.slice(0,r)).length<=e?t=r:n=r-1}return A.slice(0,t)}const ba=2e3;function Qr(A,e){if(!e)return 0;let t,n;return"bytesReceived"in A?(t=A.bytesReceived,n=e.bytesReceived):"bytesSent"in A&&(t=A.bytesSent,n=e.bytesSent),t===void 0||n===void 0||A.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(A.timestamp-e.timestamp)}const Tv=1e3;class sh extends U{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,n){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=va(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(k.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new je,this.pauseUpstreamLock=new je,this.processorLock=new je,this.restartLock=new je,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==U.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return m(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{wn(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Cn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Cn(i??e,r)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Tv;return function*(){var n;if(e.kind===U.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=wt())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Je(10));const i=Date.now();for(;Date.now()-i<t;){const r=e.dimensions;if(r)return r;yield Je(50)}throw new jt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===lA(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),lA(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===U.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===U.Kind.Audio?"audioinput":"videoinput";return t?Ee.getInstance().normalizeDeviceId(r,n,i):n}()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){if(!this.sender)throw new jt("unable to replace an unpublished track");let n,i;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:i}=e,r=p0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===U.Kind.Video?s.video=n||i?{deviceId:n,facingMode:i}:!0:s.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{wn(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(r),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(k.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?k.Muted:k.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Rd()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(k.UpstreamPaused,this);const n=wt();if(n?.name==="Safari"&&NA(n.version,"12.0")<0)throw new $o("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(k.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),a={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(a),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Cn(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const c of n.attachedElements)c!==n.processorElement&&i&&(wn(n._mediaStreamTrack,c),Cn(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(k.TrackProcessorUpdate,n.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(k.TrackProcessorUpdate))}()})}}class Fr extends sh{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,U.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=Qr(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(k.AudioTrackFeatureUpdate,this,Bt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(k.AudioTrackFeatureUpdate,this,Bt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===U.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==lA(this._constraints.deviceId);return this.source===U.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=da({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Xe()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ba)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.processorLock.lock();try{if(!xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),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(k.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(i=>{i.type==="outbound-rtp"&&(n={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Gd(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(k.AudioSilenceDetected)),e})}}function Qv(A,e,t){switch(A.kind){case"audio":return new Fr(A,e,!1,void 0,t);case"video":return new Ir(A,e,!1,t);default:throw new jt("unsupported track type: ".concat(A.kind))}}const Fv=Object.values(ii),kv=Object.values(zo),Iv=Object.values(Zo),_v=[ii.h180,ii.h360],xv=[zo.h180,zo.h360],Rv=A=>[{scaleResolutionDownBy:2,fps:A.encoding.maxFramerate}].map(t=>{var n,i;return new ie(Math.floor(A.width/t.scaleResolutionDownBy),Math.floor(A.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(A.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=A.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,A.encoding.priority)}),Ea=["q","h","f"];function Sa(A,e,t,n){var i,r;let s=n?.videoEncoding;A&&(s=n?.screenShareEncoding);const o=n?.simulcast,a=n?.scalabilityMode,c=n?.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Dv(A,e,t,c),j.debug("using video encoding",s));const u=s.maxFramerate,l=new ie(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&ri(c)){const f=new kr(a),g=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const p=wt();if(uA()||xt()||p?.name==="Chrome"&&NA(p?.version,"113")<0){const B=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)g.push({rid:Ea[2-y],maxBitrate:s.maxBitrate/Math.pow(B,y),maxFramerate:l.encoding.maxFramerate});g[0].scalabilityMode=a}else g.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(g[0].priority=l.encoding.priority,g[0].networkPriority=l.encoding.priority),j.debug("using svc encoding",{encodings:g}),g}if(!o)return[s];let d=[];A?d=(i=ah(n?.screenShareSimulcastLayers))!==null&&i!==void 0?i:oh(A,l):d=(r=ah(n?.videoSimulcastLayers))!==null&&r!==void 0?r:oh(A,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const g=Math.max(e,t);if(g>=960&&h)return Ua(e,t,[f,h,l],u);if(g>=480)return Ua(e,t,[f,l],u)}return Ua(e,t,[l])}function Pv(A,e,t){var n,i,r,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&j.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=A.mediaStreamTrack.getSettings(),a=(n=o.width)!==null&&n!==void 0?n:(i=A.dimensions)===null||i===void 0?void 0:i.width,c=(r=o.height)!==null&&r!==void 0?r:(s=A.dimensions)===null||s===void 0?void 0:s.height;return A.source===U.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Sa(A.source===U.Source.ScreenShare,a,c,t)}function Dv(A,e,t,n){const i=Lv(A,e,t);let{encoding:r}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(r=a.encoding,a.width>=s)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Lv(A,e,t){if(A)return Iv;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Fv:kv}function oh(A,e){if(A)return Rv(e);const{width:t,height:n}=e,i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?_v:xv}function Ua(A,e,t,n){const i=[];if(t.forEach((r,s)=>{if(s>=Ea.length)return;const o=Math.min(A,e),c={rid:Ea[s],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},u=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=yn()||s===0;r.encoding.priority&&l&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),xt()&&Dd()==="ios"){let r;i.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=r&&(s&&(s=!1,j.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),j.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(r)),o.maxFramerate=r)})}return i}function ah(A){if(A)return A.sort((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class kr{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 Ov(A){return A.source===U.Source.ScreenShare||A.constraints.height&&lA(A.constraints.height)>=1080?"maintain-resolution":"balanced"}const Hv=5e3;class Ir extends sh{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,U.Kind.Video,t,n,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=Qr(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new je}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Xe())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ba))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=sA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)r=c.value,o=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){n={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=sA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const u=r;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){n={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=n.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,r)=>{var s,o;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let n=ot.LOW;n<=ot.HIGH;n+=1)t.push(new Ro({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;let o;if(e){const l=da({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=sA(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){r=u.value,a=!1;const l=r;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){n={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,n,r),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=sA(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(g){o={error:g}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Hv))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s,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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=sA(e);i=yield n.next(),r=i.done,!r;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield ch(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield ch(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Rd()&&this.isInBackground&&this.source===U.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ch(A,e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=yield n.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:A,qualities:t,senderEncodings:e}));try{const o=A.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:e}));return}let c=!1;const u=wt();if(u?.name==="Chrome"&&NA(u?.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new kr(d.scalabilityMode);let f=fn.OFF;if(t.forEach(g=>{g.enabled&&(f===fn.OFF||g.quality>f)&&(f=g.quality)}),f===fn.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const g=new kr(e[0].scalabilityMode);h.spatial=f+1,h.suffix=g.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let g=(f=d.rid)!==null&&f!==void 0?f:"";g===""&&(g="q");const p=uh(g),B=t.find(y=>y.quality===p);B&&d.active!==B.enabled&&(c=!0,d.active=B.enabled,i.debug("setting layer ".concat(B.quality," to ").concat(d.active?"enabled":"disabled"),r),yn()&&(B.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield A.setParameters(o))}finally{s()}})}function uh(A){switch(A){case"f":return ot.HIGH;case"h":return ot.MEDIUM;case"q":return ot.LOW;default:return ot.HIGH}}function lh(A,e,t,n){if(!t)return[new OA({quality:ot.HIGH,width:A,height:e,bitrate:0,ssrc:0})];if(n){const i=t[0].scalabilityMode,r=new kr(i),s=[],o=r.suffix=="h"?1.5:2,a=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new OA({quality:Math.min(ot.HIGH,r.spatial-1)-c,width:Math.ceil(A/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 s}return t.map(i=>{var r,s,o;const a=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=uh((s=i.rid)!==null&&s!==void 0?s:"");return new OA({quality:c,width:Math.ceil(A/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const dh="_lossy",hh="_reliable",Mv=2*1e3,Ta="leave-reconnect";var bt;(function(A){A[A.New=0]="New",A[A.Connected=1]="Connected",A[A.Disconnected=2]="Disconnected",A[A.Reconnecting=3]="Reconnecting",A[A.Closed=4]="Closed"})(bt||(bt={}));class Nv extends _t.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=wa.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=bt.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=j,this.handleDataChannel=n=>m(this,[n],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===hh)r.reliableDCSub=s;else if(s.label===dh)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const a=We.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(I.ActiveSpeakersUpdate,a.value.value.speakers):(((r=a.value)===null||r===void 0?void 0:r.case)==="user"&&Gv(a,a.value.value),this.emit(I.DataPacketReceived,a))}finally{s()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:s}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Y.LOSSY:Y.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,i)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(I.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){r(s);return}n===Ta&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Te.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,i)=>{this.pcState===bt.Connected&&n();const r=()=>{this.off(I.Disconnected,s),n()},s=()=>{this.off(I.Restarted,r),i()};this.once(I.Restarted,r),this.once(I.Disconnected,s)}),this.updateAndEmitDCBufferStatus=n=>{const i=this.isBufferStatusLow(n);typeof i<"u"&&i!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,i),this.emit(I.DCBufferStatusChanged,i,n))},this.isBufferStatusLow=n=>{const i=this.dataChannelForKind(n);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===oe.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(gn.RR_SIGNAL_DISCONNECTED))},this.log=Vt((t=e.loggerName)!==null&&t!==void 0?t:Ct.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new fa(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new je,this.dataProcessLock=new je,this.dcBufferStatus=new Map([[Y.LOSSY,!0],[Y.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(I.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(I.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(I.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(I.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(I.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(I.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(I.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(I.SignalRequestResponse,n)}get logContext(){var e,t,n,i,r,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,n,i){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(I.SignalConnected)},10),r}catch(r){if(r instanceof re&&r.reason===W.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw r}})}close(){return m(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(I.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new jt("a track with the same ID has already been published");return new Promise((t,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new re("publication of local track timed out, no response from server",W.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),t(r)},reject:()=>{clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return m(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==he.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new Uv(i,e.subscriberPrimary,this.loggerOptions),this.emit(I.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===he.CONNECTED){const u=this.pcState===bt.New;this.pcState=bt.Connected,u&&this.emit(I.Connected,e)}else r===he.FAILED&&this.pcState===bt.Connected&&(this.pcState=bt.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?gn.RR_SUBSCRIBER_FAILED:gn.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===oe.RECONNECTING,c=[he.FAILED,he.CLOSING,he.CLOSED].includes(r);a&&c&&!this._isClosed&&this.emit(I.Offline)}),this.pcManager.onTrack=r=>{this.emit(I.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Kv((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(I.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(I.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(I.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(I.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(I.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",gn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Bn.DISCONNECT:this.emit(I.Disconnected,e?.reason),this.close();break;case Bn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ta);break;case Bn.RESUME:this.handleDisconnect(Ta)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),n.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ti.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(dh,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(hh,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(ea())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ta())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(ea())return this.createSimulcastTransceiverSender(e,t,n,i);if(ta())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),En(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,i;if(!this._isClosed){if(this.attemptingReconnect){j.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===ti.DISABLED||((i=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&i!==void 0?i:he.NEW)===he.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let s=!0;r instanceof ye?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Un||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",gn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(I.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return m(this,void 0,void 0,function*(){var t,n,i;try{if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Un;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof re&&s.reason===W.NotAllowed?new ye("could not reconnect, token might be expired"):new Un}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(I.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==oe.CONNECTED)throw new Un("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(I.Restarted)}catch(r){const s=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return m(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");if(!this.pcManager)throw new ye("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof re&&i.reason===W.NotAllowed?new ye("could not reconnect, token might be expired"):i instanceof re&&i.reason===W.LeaveRequest?i:new Un(r)}if(this.emit(I.SignalResumed),n){const i=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(i)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==oe.CONNECTED)throw new Un("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(),this.emit(I.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=bt.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Je(Mv),!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=bt.Connected}catch(e){throw this.pcState=bt.Disconnected,new re("could not establish PC connection, ".concat(e.message),W.InternalError)}})}publishRpcResponse(e,t,n,i){return m(this,void 0,void 0,function*(){const r=new We({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcResponse",value:new vl({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Y.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new We({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcAck",value:new Bl({requestId:t})}});yield this.sendDataPacket(n,Y.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(n),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,n)=>m(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>n("Engine closed");for(this.once(I.Closing,i);!this.dcBufferStatus.get(e);)yield Je(10);this.off(I.Closing,i),t()}}))}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new ye("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new re("".concat(o," connection not set"),W.InternalError);let a=!1;!i&&!n.dataChannelForKind(t,i)&&(n.createDataChannels(),a=!0),!a&&!i&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&n.negotiate();const c=n.dataChannelForKind(t,i);if(c?.readyState==="open")return;const u=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((r=n.dataChannelForKind(t,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield Je(50)}throw new re("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),W.InternalError)}()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==he.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Wo("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(I.Closing,i),this.pcManager.publisher.once(Sn.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(o=>{const a=o.codec.toLowerCase();Y0(a)&&s.set(o.payload,a)}),this.emit(I.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof Wo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",gn.RR_UNKNOWN),t(r)}finally{this.off(I.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===Y.LOSSY)return this.lossyDCSub;if(e===Y.RELIABLE)return this.reliableDCSub}else{if(e===Y.LOSSY)return this.lossyDC;if(e===Y.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new Ll({answer:r?Tr({sdp:r.sdp,type:r.type}):void 0,offer:s?Tr({sdp:s.sdp,type:s.type}):void 0,subscription:new lr({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:sv(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,i)=>{n?.id!==void 0&&n.id!==null&&e.push(new Ol({label:n.label,id:n.id,target:i}))};return t(this.dataChannelForKind(Y.LOSSY),vt.PUBLISHER),t(this.dataChannelForKind(Y.RELIABLE),vt.PUBLISHER),t(this.dataChannelForKind(Y.LOSSY,!0),vt.SUBSCRIBER),t(this.dataChannelForKind(Y.RELIABLE,!0),vt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Te.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Xe()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Xe()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Un extends Error{}function Kv(A){return A!==void 0&&A>13}function Gv(A,e){const t=A.participantIdentity?A.participantIdentity:e.participantIdentity;A.participantIdentity=t,e.participantIdentity=t;const n=A.destinationIdentities.length!==0?A.destinationIdentities:e.destinationIdentities;A.destinationIdentities=n,e.destinationIdentities=n}class Qa{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return na(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(i=>i.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),j.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(Vv(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new re("Could not fetch region settings: ".concat(t.statusText),t.status===401?W.NotAllowed:W.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Vv(A){return"".concat(A.protocol.replace("ws","http"),"//").concat(A.host,"/settings")}class fh{get info(){return this._info}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class jv extends fh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>m(this,void 0,void 0,function*(){try{const{done:t,value:n}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r=new Set;try{for(var s=!0,o=sA(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;r.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class $v extends fh{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Sr(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>m(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r="";try{for(var s=!0,o=sA(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,r+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return r})}}class gh{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Wv extends gh{}class Jv extends gh{}class ph extends U{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?k.Muted:k.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.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(k.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ba)),ov()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:i,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(k.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Xv extends ph{constructor(e,t,n,i,r,s){super(e,t,U.Kind.Audio,n,s),this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Qr(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(xt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Aa(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Aa(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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 n=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{n.connect(i),n=i}),this.gainNode=e.createGain(),n.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(k.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(k.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Fa=100;class qv extends ph{constructor(e,t,n,i,r){super(e,t,U.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=Qr(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=va(()=>{this.updateDimensions()},Fa),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?wn(this._mediaStreamTrack,t):Cn(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 Yv(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&i.set(r.id,r)}),t&&n!==""&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-n<Fa){Te.setTimeout(()=>{this.updateVisibility()},Fa);return}this.lastVisible=s,this.emit(k.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let n=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*r,a=s.height()*r;o+a>n+i&&(n=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:n,height:i},this.emit(k.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Ld():t||(Ld()>2?2:1)}}class Yv{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var i;const{target:r,isIntersecting:s}=n;r===this.element&&(this.isIntersecting=s,this.isPiP=ai(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var n,i,r;(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ai(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=ai(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??ka(e),this.isPiP=Xe()&&ai(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=ka(this.element),this.isPiP=ai(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Hd().observe(this.element),Od().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),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,r;(e=Hd())===null||e===void 0||e.unobserve(this.element),(t=Od())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function ai(A){var e,t;return document.pictureInPictureElement===A?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ka(A,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function ka(A,e){const t=e||window;let n=A.offsetTop,i=A.offsetLeft;const r=A.offsetWidth,s=A.offsetHeight,{hidden:o}=A,{display:a}=getComputedStyle(A);for(;A.offsetParent;)A=A.offsetParent,n+=A.offsetTop,i+=A.offsetLeft;return n<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&n+s>t.pageYOffset&&i+r>t.pageXOffset&&!o&&a!=="none"}class Wt extends _t.EventEmitter{constructor(e,t,n,i){var r;super(),this.metadataMuted=!1,this.encryption=tt.NONE,this.log=j,this.handleMuted=()=>{this.emit(k.Muted)},this.handleUnmuted=()=>{this.emit(k.Unmuted)},this.log=Vt((r=i?.loggerName)!==null&&r!==void 0?r:Ct.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=U.Source.Unknown}setTrack(e){this.track&&(this.track.off(k.Muted,this.handleMuted),this.track.off(k.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(k.Muted,this.handleMuted),e.on(k.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Z(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==tt.NONE}get audioTrack(){if($t(this.track))return this.track}get videoTrack(){if(En(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=U.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===U.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(A){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(A.SubscriptionStatus||(A.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(A.PermissionStatus||(A.PermissionStatus={}))})(Wt||(Wt={}));class Ia extends Wt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(k.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(k.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(k.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if($t(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Bt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Bt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Bt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Bt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(Bt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Bt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function _r(A,e){return m(this,void 0,void 0,function*(){A??(A={});let t=!1;const{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:r}=$d(A);let s=r.audio,o=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),i&&typeof r.video=="object"&&(r.video.processor=i),A.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const l=r.audio.deviceId;r.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:l}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const l=r.video.deviceId;r.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:l}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const a=Kd(r,Ah,nh),c=da(a),u=navigator.mediaDevices.getUserMedia(c);r.audio&&(Ee.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Ee.userMediaPromiseMap.delete("audioinput"))),r.video&&(Ee.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Ee.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>m(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let g;const p=h?c.audio:c.video;typeof p!="boolean"&&(g=p);const B=d.getSettings().deviceId;g?.deviceId&&lA(g.deviceId)!==B?g.deviceId=B:g||(g={deviceId:B});const y=Qv(d,g,e);return y.kind===U.Kind.Video?y.source=U.Source.Camera:y.kind===U.Kind.Audio&&(y.source=U.Source.Microphone),y.mediaStream=l,$t(y)&&n?yield y.setProcessor(n):En(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return _r(Object.assign(Object.assign({},A),{audio:s,video:o}),e)}})}function zv(A){return m(this,void 0,void 0,function*(){return(yield _r({audio:!1,video:A??!0}))[0]})}function Zv(A){return m(this,void 0,void 0,function*(){return(yield _r({audio:A??!0,video:!1}))[0]})}var fA;(function(A){A.Excellent="excellent",A.Good="good",A.Poor="poor",A.Lost="lost",A.Unknown="unknown"})(fA||(fA={}));function eC(A){switch(A){case ei.EXCELLENT:return fA.Excellent;case ei.GOOD:return fA.Good;case ei.POOR:return fA.Poor;case ei.LOST:return fA.Lost;default:return fA.Unknown}}class mh extends _t.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===ur.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===pn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,i,r,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ur.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=fA.Unknown,this.log=j,this.log=Vt((a=s?.loggerName)!==null&&a!==void 0?a:Ct.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new oa,this.once(x.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(U.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(U.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(U.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===pn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==pn.ACTIVE&&this.emit(x.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(x.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(x.ParticipantNameChanged,e)}_setAttributes(e){const t=av(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(x.AttributesChanged,t)}setPermissions(e){var t,n,i,r,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(x.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(x.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=eC(e),t!==this._connectionQuality&&this.emit(x.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=>$t(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(k.Muted,()=>{this.emit(x.TrackMuted,e)}),e.on(k.Unmuted,()=>{this.emit(x.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case U.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case U.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function tC(A){var e,t,n;if(!A.participantSid&&!A.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Pl({participantIdentity:(e=A.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=A.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=A.allowAll)!==null&&n!==void 0?n:!1,trackSids:A.allowedTrackSids||[]})}const Bh=15e3;class AC extends mh{constructor(e,t,n,i,r){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=tt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new oa)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,u=this.pendingSignalRequests.get(o);u&&(a!==Po.OK&&u.reject(new kd(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=fe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>tC(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Z(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Z(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Z(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>m(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const B=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,g=sA(B),p;p=yield g.next(),o=p.done,!o;f=!0){u=p.value,f=!1;const y=u;M0(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Z(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=g.return)&&(yield c.call(g))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>m(this,void 0,void 0,function*(){if(s.source===U.Source.ScreenShare||s.source===U.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Z(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(GA(s)||dA(s))try{if(Xe())try{const o=yield navigator?.permissions.query({name:s.source===U.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Z(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Z(s))),GA(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Z(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==tt.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){this.engine=e,this.engine.on(I.RemoteMute,(t,n)=>{const i=this.trackPublications.get(t);!i||!i.track||(n?i.mute():i.unmute())}),this.engine.on(I.Connected,this.handleReconnected).on(I.SignalRestarted,this.handleReconnected).on(I.SignalResumed,this.handleReconnected).on(I.Restarting,this.handleReconnecting).on(I.Resuming,this.handleReconnecting).on(I.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(I.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(I.Disconnected,this.handleDisconnected).on(I.SignalRequestResponse,this.handleSignalRequestResponse).on(I.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let{metadata:i,name:r,attributes:s}=t;return function*(){return new Promise((o,a)=>m(n,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=r??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[g,p]=f;return this.attributes[g]===p||p===""&&!this.attributes[g]}))){this.pendingSignalRequests.delete(d),o();return}yield Je(50)}a(new kd("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(U.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(U.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(U.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(x.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?tt.GCM:tt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,i){return m(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c?.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case U.Source.Camera:a=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case U.Source.Microphone:a=yield this.createTracks({audio:(s=n)!==null&&s!==void 0?s:!0});break;case U.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},n));break;default:throw new jt(e)}}catch(c){throw a?.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(x.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Z(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a?.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===U.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(U.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(U.Source.Camera)||this.pendingPublishing.has(U.Source.Microphone))){this.pendingPublishing.add(U.Source.Camera),this.pendingPublishing.add(U.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(U.Source.Camera),this.pendingPublishing.delete(U.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const i=Kd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield _r(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>($t(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=U.Source.Microphone,this.emit(x.AudioStreamAcquired)),En(o)&&(this.cameraError=void 0,o.source=U.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new $o("getDisplayMedia not supported");e.resolution===void 0&&!$0()&&(e.resolution=Zo.h1080fps30.resolution);const t=rv(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(i.length===0)throw new jt("no video track found");const r=new Ir(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=U.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(x.AudioStreamAcquired);const o=new Fr(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=U.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;GA(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!s&&(yield r.republishPromise),bn(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let l;if(n instanceof MediaStreamTrack)l=n.getConstraints();else{l=n.constraints;let B;switch(n.source){case U.Source.Microphone:B="audioinput";break;case U.Source.Camera:B="videoinput"}B&&r.activeDeviceMap.has(B)&&(l=Object.assign(Object.assign({},l),{deviceId:r.activeDeviceMap.get(B)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Fr(n,l,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new Ir(n,l,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new jt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let d;if(r.trackPublications.forEach(B=>{B.track&&B.track===n&&(d=B)}),d)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Z(d))),d;const h="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i?.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),Z(n))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(u=i.red)!==null&&u!==void 0||(i.red=!1));const g=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!W0()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),g.simulcast=!1),g.source&&(n.source=g.source);const p=new Promise((B,y)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==oe.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Z(n)}));const b=()=>m(this,void 0,void 0,function*(){try{const v=yield this.publish(n,g,f);B(v)}catch(v){y(v)}});setTimeout(()=>{this.engine.off(I.SignalConnected,b),y(new Jo("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(I.SignalConnected,b),this.engine.on(I.Closing,()=>{this.engine.off(I.SignalConnected,b),y(new Jo("publishing rejected as engine closed",499))})}else try{const b=yield this.publish(n,g,f);B(b)}catch(b){y(b)}}catch(b){y(b)}}));r.pendingPublishPromises.set(n,p);try{return yield p}catch(B){throw B}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Z(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(i=>cv(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Z(e))),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var i,r,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new Jo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(C=>bn(e)&&C.source===e.source)&&e.source!==U.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Z(e))),t.stopMicTrackOnMute&&$t(e)&&(e.stopOnMute=!0),e.source===U.Source.ScreenShare&&yn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!G0()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!V0()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Ca),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(C=>t.videoCodec===Ur(C.mime))||(t.videoCodec=Ur(this.enabledPublishVideoCodecs[0].mime)));const g=t.videoCodec;e.on(k.Muted,this.onTrackMuted),e.on(k.Unmuted,this.onTrackUnmuted),e.on(k.Ended,this.handleTrackEnded),e.on(k.UpstreamPaused,this.onTrackUpstreamPaused),e.on(k.UpstreamResumed,this.onTrackUpstreamResumed),e.on(k.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const p=new ko({cid:e.mediaStreamTrack.id,name:t.name,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy});let B;if(e.kind===U.Kind.Video){let C={width:0,height:0};try{C=yield e.waitForDimensions()}catch{const S=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:ii.h720.resolution;C={width:S.width,height:S.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Z(e)),{dims:C}))}p.width=C.width,p.height=C.height,dA(e)&&(ri(g)&&(e.source===U.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Z(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),p.simulcastCodecs=[new Fo({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Ca}),t.backupCodec&&g!==t.backupCodec.codec&&p.encryption===tt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),p.simulcastCodecs.push(new Fo({codec:t.backupCodec.codec,cid:""})))),B=Sa(e.source===U.Source.ScreenShare,p.width,p.height,t),p.layers=lh(p.width,p.height,B,ri(t.videoCodec))}else e.kind===U.Kind.Audio&&(B=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const y=()=>m(this,void 0,void 0,function*(){var C,w,S;if(!this.engine.pcManager)throw new ye("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,B),dA(e)&&((C=t.degradationPreference)!==null&&C!==void 0||(t.degradationPreference=Ov(e)),e.setDegradationPreference(t.degradationPreference)),B)if(yn()&&e.kind===U.Kind.Audio){let F;for(const _ of this.engine.pcManager.publisher.getTransceivers())if(_.sender===e.sender){F=_;break}F&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:F,codec:"opus",maxbr:!((w=B[0])===null||w===void 0)&&w.maxBitrate?B[0].maxBitrate/1e3:0})}else e.codec&&ri(e.codec)&&(!((S=B[0])===null||S===void 0)&&S.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:p.cid,codec:e.codec,maxbr:B[0].maxBitrate/1e3});yield this.engine.negotiate()});let b;if(this.enabledPublishVideoCodecs.length>0)b=(yield Promise.all([this.engine.addTrack(p),y()]))[0];else{b=yield this.engine.addTrack(p);let C;if(b.codecs.forEach(w=>{C===void 0&&(C=w.mimeType)}),C&&e.kind===U.Kind.Video){const w=Ur(C);w!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Z(e)),{codec:w})),t.videoCodec=w,B=Sa(e.source===U.Source.ScreenShare,p.width,p.height,t))}yield y()}const v=new Ia(e.kind,b,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return v.options=t,e.sid=b.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:B,trackInfo:b})),dA(e)?e.startMonitor(this.engine.client):GA(e)&&e.startMonitor(),this.addTrackPublication(v),this.emit(x.LocalTrackPublished,v),v})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var i;if(this.encryptionType!==tt.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new jt("track is not published");if(!dA(e))throw new jt("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),n),o=Pv(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Z(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ko({cid:a.mediaStreamTrack.id,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=lh(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,i;if(bn(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Z(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?Z(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(k.Muted,this.onTrackMuted),e.off(k.Unmuted,this.onTrackUnmuted),e.off(k.Ended,this.handleTrackEnded),e.off(k.UpstreamPaused,this.onTrackUpstreamPaused),e.off(k.UpstreamResumed,this.onTrackUpstreamResumed),e.off(k.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!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<he.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),dA(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case U.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case U.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(x.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,s)=>m(n,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=>m(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==U.Source.ScreenShare&&c.source!==U.Source.ScreenShareAudio&&(GA(c)||dA(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),r()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?Y.RELIABLE:Y.LOSSY,s=i.destinationIdentities,o=i.topic,a=new We({kind:r,value:{case:"user",value:new gl({participantIdentity:n.identity,payload:t,destinationIdentities:s,topic:o})}});yield n.engine.sendDataPacket(a,r)}()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new We({kind:Y.RELIABLE,value:{case:"sipDtmf",value:new pl({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Y.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},i=new We({value:{case:"chatMessage",value:new bo(Object.assign(Object.assign({},n),{timestamp:ue.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(x.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new We({value:{case:"chatMessage",value:new bo(Object.assign(Object.assign({},n),{timestamp:ue.parse(n.timestamp),editTimestamp:ue.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(x.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(n=t?.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((g,p)=>g+p,0);(h=t?.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield u.write(e),c(1,0),yield u.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>m(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return m(this,void 0,void 0,function*(){var t,n;const i=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes},s=new So({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:KA(r.timestamp),totalLength:KA(e?.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Tl({version:e?.version,attachedStreamIds:e?.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Eo.UPDATE:Eo.CREATE})}}),o=e?.destinationIdentities,a=new We({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,Y.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return m(this,void 0,void 0,function*(){for(const g of nv(f,Bh)){yield u.engine.waitForBufferStatusLow(Y.RELIABLE);const p=new Uo({content:g,streamId:i,chunkIndex:KA(c)}),B=new We({destinationIdentities:o,value:{case:"streamChunk",value:p}});yield u.engine.sendDataPacket(B,Y.RELIABLE),c+=1}})},close(){return m(this,void 0,void 0,function*(){const f=new To({streamId:i}),g=new We({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(g,Y.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>m(this,void 0,void 0,function*(){yield h.close()});u.engine.once(I.Closing,d);const h=new Wv(l,r,()=>this.engine.off(I.Closing,d));return h})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=n?.mimeType)!==null&&i!==void 0?i:t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield r.write(a)}return yield r.close(),r.info})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;const o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e?.destinationIdentities,c={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(i=e?.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown"},u=new So({totalLength:KA((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:KA(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Ql({name:c.name})}}),l=new We({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,Y.RELIABLE);let d=0;const h=new je,f=this.engine,g=this.log,p=new WritableStream({write(y){return m(this,void 0,void 0,function*(){const b=yield h.lock();let v=0;try{for(;v<y.byteLength;){const C=y.slice(v,v+Bh);yield f.waitForBufferStatusLow(Y.RELIABLE);const w=new We({destinationIdentities:a,value:{case:"streamChunk",value:new Uo({content:C,streamId:o,chunkIndex:KA(d)})}});yield f.sendDataPacket(w,Y.RELIABLE),d+=1,v+=C.byteLength}}finally{b()}})},close(){return m(this,void 0,void 0,function*(){const y=new To({streamId:o}),b=new We({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(b,Y.RELIABLE)})},abort(y){g.error("Sink error:",y)}});return new Jv(p,c)})}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>m(n,void 0,void 0,function*(){var l,d,h,f;if(ya(s)>ih){u(fe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&NA((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){u(fe.builtIn("UNSUPPORTED_SERVER"));return}const g=crypto.randomUUID();yield this.publishRpcRequest(i,g,r,s,o-2e3);const p=setTimeout(()=>{this.pendingAcks.delete(g),u(fe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(B)},2e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(p)},participantIdentity:i});const B=setTimeout(()=>{this.pendingResponses.delete(g),u(fe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(g,{resolve:(y,b)=>{clearTimeout(B),this.pendingAcks.has(g)&&(console.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(p)),b?u(b):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=new We({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcRequest",value:new ml({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,Y.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,fe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,i;const r=this.trackPublications.get(t.sid);if(r){const s=r.isMuted||((i=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Z(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(GA(i)||dA(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield Je(20)}})}}class nC extends Wt{constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ot.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(k.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new lr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new wl({participantSid:"",trackSids:[this.trackSid]})]});this.emit(k.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Wt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Wt.SubscriptionStatus.Subscribed:Wt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Wt.PermissionStatus.Allowed:Wt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(ua(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ua(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(k.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(k.VisibilityChanged,this.handleVisibilityChange),i.off(k.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(k.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(k.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(k.VisibilityChanged,this.handleVisibilityChange),e.on(k.Ended,this.handleEnded),this.emit(k.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(k.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?k.Muted:k.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(k.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(k.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===U.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ua(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new kl({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=ot.HIGH,this.emit(k.UpdateSettings,e)}}class xr extends mh{static fromParticipantInfo(e,t,n){return new xr(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ur.STANDARD;super(t,n||"",i,r,s,o,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(k.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Z(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(k.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(k.SubscriptionPermissionChanged,t=>{this.emit(x.TrackSubscriptionPermissionChanged,e,t)}),e.on(k.SubscriptionStatusChanged,t=>{this.emit(x.TrackSubscriptionStatusChanged,e,t)}),e.on(k.Subscribed,t=>{this.emit(x.TrackSubscribed,t,e)}),e.on(k.Unsubscribed,t=>{this.emit(x.TrackUnsubscribed,t,e)}),e.on(k.SubscriptionFailed,t=>{this.emit(x.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]:U.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:U.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,i,r,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(x.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,i,r,s-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),Z(o))),this.emit(x.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new qv(e,t,i,r):c=new Xv(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ca(c)&&$t(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,n=new Map;return e.tracks.forEach(i=>{var r,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=U.kindFromProto(i.type);if(!a)return;o=new nC(a,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),n.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===o?.source);c&&o.source!==U.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:Z(c),newTrack:Z(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Z(i))),this.unpublishTrack(i.trackSid,!0))}),n.forEach(i=>{this.emit(x.TrackPublished,i)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case U.Kind.Audio:this.audioTrackPublications.delete(e);break;case U.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(x.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var i;$t(n.track)&&ca(n.track)&&t.push(n.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var z;(function(A){A.Disconnected="disconnected",A.Connecting="connecting",A.Connected="connected",A.Reconnecting="reconnecting",A.SignalReconnecting="signalReconnecting"})(z||(z={}));const iC=4*1e3;class VA extends _t.EventEmitter{constructor(e){var t,n,i,r;if(super(),t=this,this.state=z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=j,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>m(this,void 0,void 0,function*(){var c;if(!j0())throw xt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===z.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(z.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),na(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Qa(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const l=(h,f,g)=>m(this,void 0,void 0,function*(){var p,B;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u?.();try{yield this.attemptConnection(g??s,o,a,y),this.abortController=void 0,h()}catch(b){if(this.regionUrlProvider&&b instanceof re&&b.reason!==W.Cancelled&&b.reason!==W.NotAllowed){let v=null;try{v=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(C){if(C instanceof re&&(C.status===401||C.reason===W.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(C);return}}v&&!(!((B=this.abortController)===null||B===void 0)&&B.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(b.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield l(h,f,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Nd(b)),f(b))}else{let v=mt.UNKNOWN_REASON;b instanceof re&&(v=Nd(b)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),f(b)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new oa((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>m(this,void 0,void 0,function*(){var d,h,f;const g=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let p=g.serverInfo;if(p||(p={version:g.serverVersion,region:g.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(B=>{let[y,b]=B;return"".concat(y,": ").concat(b)}).join(", ")),{room:(d=g.room)===null||d===void 0?void 0:d.name,roomSid:(h=g.room)===null||h===void 0?void 0:h.sid,identity:(f=g.participant)===null||f===void 0?void 0:f.identity}),!p.version)throw new k0("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),g}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>m(this,void 0,void 0,function*(){var u,l;this.state===z.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},wa),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(Q.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new re("could not establish signal connection",W.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof re&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new re("Connection attempt aborted",W.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Xe()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Xe()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(z.Connected),this.emit(Q.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return m(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const g=yield c.disconnectLock.lock();try{if(c.state===z.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===z.Connecting||c.state===z.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new re("Client initiated disconnect",W.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,mt.CLIENT_INITIATED),c.engine=void 0}finally{g()}}()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const s=[],o=wt();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=sa();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(Q.Disconnected,()=>{c?.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{s.includes(u)||s.push(u)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(Q.Reconnecting)},this.handleSignalRestarted=s=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(z.Connected),this.emit(Q.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===pn.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(Q.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(Q.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=U.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(x.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(Q.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(Q.DataReceived,o.payload,s,a,o.topic),s?.emit(x.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(Q.SipDTMFReceived,o,s),s?.emit(x.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a?.trackPublications.get(o.trackId),u=Z0(o,this.transcriptionReceivedTimes);c?.emit(k.TranscriptionReceived,u),a?.emit(x.TranscriptionReceived,u,c),this.emit(Q.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=ev(o);this.emit(Q.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(Q.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Q.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Q.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Q.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Q.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var s,o,a;const c=Ee.getInstance().previousDevices,u=yield Ee.getInstance().getDevices(void 0,!1),l=wt();if(l?.name==="Chrome"&&l.os!=="iOS")for(let h of u){const f=c.find(g=>g.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(Q.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=iv(h),g=this.localParticipant.getTrackPublication(f);if(g&&(!((s=g.track)===null||s===void 0)&&s.isUserProvided))continue;const p=u.filter(y=>y.kind===h),B=this.getActiveDevice(h);if(B===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&p.length>0&&((a=p[0])===null||a===void 0?void 0:a.deviceId)!==B){yield this.switchActiveDevice(h,p[0].deviceId);continue}h==="audioinput"&&!uA()||h==="videoinput"||p.length>0&&!p.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,p[0].deviceId))}this.emit(Q.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(Q.RoomMetadataChanged,s.metadata),o?.activeRecording!==s.activeRecording&&this.emitWhenConnected(Q.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(Q.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(Q.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(Q.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(Q.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(Q.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s?.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>m(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(k.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(k.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(Q.LocalTrackPublished,s,this.localParticipant),GA(s.track)&&(yield s.track.checkForSilence())&&this.emit(Q.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=jd(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(Q.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(k.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(k.Restarted,this.onLocalTrackRestarted),this.emit(Q.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>m(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=jd(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(Q.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(Q.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(Q.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(Q.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(Q.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Sv),e),this.log=Vt((n=this.options.loggerName)!==null&&n!==void 0?n:Ct.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ah),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},nh),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ev),e?.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new je,this.localParticipant=new AC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",lA(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",lA(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",lA(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Xe()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),VA.cleanupRegistry&&VA.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,n,i,r,s){return m(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,fe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,fe.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:r});ya(u)>ih?(a=fe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=u}catch(u){u instanceof fe?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),u),a=fe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new uv(this.options.e2ee),this.e2eeManager.on(aA.ParticipantEncryptionStatusChanged,(t,n)=>{Av(n)&&(this.isE2EEEnabled=t),this.emit(Q.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(aA.EncryptionError,t=>this.emit(Q.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return m(this,void 0,void 0,function*(){return this.state===z.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=i=>{i.sid!==""&&(this.engine.off(I.RoomUpdate,n),e(i.sid))};this.engine.on(I.RoomUpdate,n),this.once(Q.Disconnected,()=>{this.engine.off(I.RoomUpdate,n),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Nv(this.options),this.engine.on(I.ParticipantUpdate,this.handleParticipantUpdates).on(I.RoomUpdate,this.handleRoomUpdate).on(I.SpeakersChanged,this.handleSpeakersChanged).on(I.StreamStateChanged,this.handleStreamStateUpdate).on(I.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(I.SubscriptionError,this.handleSubscriptionError).on(I.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(I.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(I.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(I.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(I.DataPacketReceived,this.handleDataPacket).on(I.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(z.SignalReconnecting)&&this.emit(Q.SignalReconnecting)}).on(I.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(z.Connected)&&this.emit(Q.Reconnected)}).on(I.SignalResumed,()=>{this.bufferedEvents=[],(this.state===z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(I.Restarting,this.handleRestarting).on(I.SignalRestarted,this.handleSignalRestarted).on(I.Offline,()=>{this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(Q.Reconnecting)}).on(I.DCBufferStatusChanged,(e,t)=>{this.emit(Q.DCBufferStatusChanged,e,t)}).on(I.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:i}=n;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(x.LocalTrackSubscribed,t),this.emitWhenConnected(Q.LocalTrackSubscribed,t,this.localParticipant)}).on(I.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(Q.Moved,e.room.name,e.token),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ee.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(na(new URL(e))&&t){this.regionUrlProvider=new Qa(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===z.Disconnected&&(this.regionUrl=n,yield fetch(aa(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(aa(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let n=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new It({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new It({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new It({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new It({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":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new It({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new It({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":i=new It({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new dr({reason:mt.CLIENT_INITIATED,action:Bn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new It({scenario:{case:"subscriberBandwidth",value:KA(t)}});break;case"leave-full-reconnect":i=new It({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let g=!0,p=!1;const B=s?{exact:i}:i;if(n==="audioinput"){p=r.localParticipant.audioTrackPublications.size===0;const y=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=B;const b=Array.from(r.localParticipant.audioTrackPublications.values()).filter(v=>v.source===U.Source.Microphone);try{g=(yield Promise.all(b.map(v=>{var C;return(C=v.audioTrack)===null||C===void 0?void 0:C.setDeviceId(B)}))).every(v=>v===!0)}catch(v){throw r.options.audioCaptureDefaults.deviceId=y,v}}else if(n==="videoinput"){p=r.localParticipant.videoTrackPublications.size===0;const y=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=B;const b=Array.from(r.localParticipant.videoTrackPublications.values()).filter(v=>v.source===U.Source.Camera);try{g=(yield Promise.all(b.map(v=>{var C;return(C=v.videoTrack)===null||C===void 0?void 0:C.setDeviceId(B)}))).every(v=>v===!0)}catch(v){throw r.options.videoCaptureDefaults.deviceId=y,v}}else if(n==="audiooutput"){if(!Aa()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield Ee.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=r.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=r.getActiveDevice(n))!==null&&l!==void 0?l:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((d=r.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(b=>b.setAudioOutput({deviceId:i})))}catch(b){throw r.options.audioOutput.deviceId=y,b}}return(p||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(Q.ActiveDeviceChanged,n,i)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(x.AttributesChanged,this.onLocalAttributesChanged).on(x.TrackMuted,this.onLocalTrackMuted).on(x.TrackUnmuted,this.onLocalTrackUnmuted).on(x.LocalTrackPublished,this.onLocalTrackPublished).on(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(x.MediaDevicesError,this.onMediaDevicesError).on(x.AudioStreamAcquired,this.startAudio).on(x.ChatMessage,this.onLocalChatMessageSent).on(x.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===z.Connecting||this.state===z.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),l()},l=()=>{this.off(Q.Reconnected,u),this.off(Q.Connected,u),this.off(Q.Disconnected,l)};this.once(Q.Reconnected,u),this.once(Q.Connected,u),this.once(Q.Disconnected,l);return}if(this.state===z.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const i=K0(t.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,n,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==z.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(x.AttributesChanged,this.onLocalAttributesChanged).off(x.TrackMuted,this.onLocalTrackMuted).off(x.TrackUnmuted,this.onLocalTrackUnmuted).off(x.LocalTrackPublished,this.onLocalTrackPublished).off(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(x.MediaDevicesError,this.onMediaDevicesError).off(x.AudioStreamAcquired,this.startAudio).off(x.ChatMessage,this.onLocalChatMessageSent).off(x.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),Xe()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(z.Disconnected),this.emit(Q.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(Q.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return m(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Sr(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new jv(s,o,Sr(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new $v(s,o,Sr(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Vd())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Je(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(Q.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let i;return t?i=xr.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new xr(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Q.ParticipantConnected,n),n.on(x.TrackPublished,i=>{this.emitWhenConnected(Q.TrackPublished,i,n)}).on(x.TrackSubscribed,(i,r)=>{i.kind===U.Kind.Audio?(i.on(k.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(k.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===U.Kind.Video&&(i.on(k.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(k.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Q.TrackSubscribed,i,r,n)}).on(x.TrackUnpublished,i=>{this.emit(Q.TrackUnpublished,i,n)}).on(x.TrackUnsubscribed,(i,r)=>{this.emit(Q.TrackUnsubscribed,i,r,n)}).on(x.TrackMuted,i=>{this.emitWhenConnected(Q.TrackMuted,i,n)}).on(x.TrackUnmuted,i=>{this.emitWhenConnected(Q.TrackUnmuted,i,n)}).on(x.ParticipantMetadataChanged,i=>{this.emitWhenConnected(Q.ParticipantMetadataChanged,i,n)}).on(x.ParticipantNameChanged,i=>{this.emitWhenConnected(Q.ParticipantNameChanged,i,n)}).on(x.AttributesChanged,i=>{this.emitWhenConnected(Q.ParticipantAttributesChanged,i,n)}).on(x.ConnectionQualityChanged,i=>{this.emitWhenConnected(Q.ConnectionQualityChanged,i,n)}).on(x.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(Q.ParticipantPermissionsChanged,i,n)}).on(x.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(Q.TrackSubscriptionStatusChanged,i,r,n)}).on(x.TrackSubscriptionFailed,(i,r)=>{this.emit(Q.TrackSubscriptionFailed,i,n,r)}).on(x.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(Q.TrackSubscriptionPermissionChanged,i,r,n)}).on(x.Active,()=>{this.emitWhenConnected(Q.ParticipantActive,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,i)=>(n.push(...i.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&tv(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Te.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,mt.STATE_MISMATCH))):e=0},iC)}clearConnectionReconcile(){this.connectionReconcileInterval&&Te.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(Q.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(this.state===z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===z.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ar({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ue.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new LA({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Q.SignalConnected),this.emit(Q.Connected),this.setAndEmitConnectionState(z.Connected),i.video){const s=new Ia(U.Kind.Video,new mn({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO,name:"video-dummy"}),new Ir(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Md(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(x.LocalTrackPublished,s)}if(i.audio){const s=new Ia(U.Kind.Audio,new mn({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO}),new Fr(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(x.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let o=new LA({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:pn.ACTIVE,tracks:[],joinedAt:ue.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(r.video){const c=Md(160*((n=r.aspectRatios[s%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),u=new mn({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(r.audio){const c=sa(),u=new mn({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(e!==Q.ActiveSpeakersChanged&&e!==Q.TranscriptionReceived){const r=vh(n).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}VA.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(A=>{A()});function vh(A){return A.map(e=>{if(e)return Array.isArray(e)?vh(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Et;(function(A){A[A.IDLE=0]="IDLE",A[A.RUNNING=1]="RUNNING",A[A.SKIPPED=2]="SKIPPED",A[A.SUCCESS=3]="SUCCESS",A[A.FAILED=4]="FAILED"})(Et||(Et={}));class gA extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Et.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new VA(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Et.IDLE)throw Error("check is running already");this.setStatus(Et.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!==Et.SKIPPED&&this.setStatus(this.isSuccess()?Et.SUCCESS:Et.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Et.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(Q.Reconnecting,()=>{t=!0}),this.room.once(Q.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(n)return;yield Je(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 rC extends gA{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new Qa(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(n.has(s))continue;n.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield r.write(c);yield r.close();const l=Date.now(),d=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d?.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const _a=1e4;class sC extends gA{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(_a/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(_a/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>m(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d?.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,_a)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class oC extends gA{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Zv();if(yield Gd(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class aC extends gA{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield zv();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,yield new Promise(i=>{n.onplay=()=>{setTimeout(()=>{var r,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(r=u.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(n,0,0);const g=h.getImageData(0,0,c.width,c.height).data;let p=!0;for(let B=0;B<g.length;B+=4)if(g[B]!==0||g[B+1]!==0||g[B+2]!==0){p=!1;break}p?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},n.play()}),n.remove()})}}class cC extends gA{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),o=()=>{n=!0};t.on(Q.SignalReconnecting,o).on(Q.Reconnecting,o).on(Q.Reconnected,()=>{i=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,n){if(!i||t.state!==z.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class uC extends gA{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t;const n=new fa,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,r=!0),c.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class lC extends gA{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(Q.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(dC(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),j.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 dC(A){const e=A.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 hC extends gA{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new fa;const r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===yl.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield i.close()})}}class Q_ extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Et.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!==Et.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};n.on("update",i);const r=yield n.run();return n.off("update",i),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(hC)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(lC)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(uC)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(cC)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(oC)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(aC)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(sC);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(rC)})}}const qe=Symbol.for("@ts-pattern/matcher"),Ch=Symbol.for("@ts-pattern/isVariadic"),Rr="@ts-pattern/anonymous-select-key",xa=A=>!!(A&&typeof A=="object"),Pr=A=>A&&!!A[qe],Qe=(A,e,t)=>{if(Pr(A)){const n=A[qe](),{matched:i,selections:r}=n.match(e);return i&&r&&Object.keys(r).forEach(s=>t(s,r[s])),i}if(xa(A)){if(!xa(e))return!1;if(Array.isArray(A)){if(!Array.isArray(e))return!1;let n=[],i=[],r=[];for(const s of A.keys()){const o=A[s];Pr(o)&&o[Ch]?r.push(o):r.length?i.push(o):n.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<n.length+i.length)return!1;const s=e.slice(0,n.length),o=i.length===0?[]:e.slice(-i.length),a=e.slice(n.length,i.length===0?1/0:-i.length);return n.every((c,u)=>Qe(c,s[u],t))&&i.every((c,u)=>Qe(c,o[u],t))&&(r.length===0||Qe(r[0],a,t))}return A.length===e.length&&A.every((s,o)=>Qe(s,e[o],t))}return Reflect.ownKeys(A).every(n=>{const i=A[n];return(n in e||Pr(r=i)&&r[qe]().matcherType==="optional")&&Qe(i,e[n],t);var r})}return Object.is(e,A)},At=A=>{var e,t,n;return xa(A)?Pr(A)?(e=(t=(n=A[qe]()).getSelectionKeys)==null?void 0:t.call(n))!=null?e:[]:Array.isArray(A)?ci(A,At):ci(Object.values(A),At):[]},ci=(A,e)=>A.reduce((t,n)=>t.concat(e(n)),[]);function fC(...A){if(A.length===1){const[e]=A;return t=>Qe(e,t,()=>{})}if(A.length===2){const[e,t]=A;return Qe(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${A.length}.`)}function Fe(A){return Object.assign(A,{optional:()=>Pa(A),and:e=>ae(A,e),or:e=>wh(A,e),select:e=>e===void 0?ui(A):ui(e,A)})}function Ra(A){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const n=[{value:Object.assign(e,{[Ch]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var i;return(i=n[t++])!=null?i:n.at(-1)}}}}))(A),{optional:()=>Ra(Pa(A)),select:e=>Ra(e===void 0?ui(A):ui(e,A))})}function Pa(A){return Fe({[qe]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return e===void 0?(At(A).forEach(i=>n(i,void 0)),{matched:!0,selections:t}):{matched:Qe(A,e,n),selections:t}},getSelectionKeys:()=>At(A),matcherType:"optional"})})}const gC=(A,e)=>{for(const t of A)if(!e(t))return!1;return!0},pC=(A,e)=>{for(const[t,n]of A.entries())if(!e(n,t))return!1;return!0};function ae(...A){return Fe({[qe]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return{matched:A.every(i=>Qe(i,e,n)),selections:t}},getSelectionKeys:()=>ci(A,At),matcherType:"and"})})}function wh(...A){return Fe({[qe]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return ci(A,At).forEach(i=>n(i,void 0)),{matched:A.some(i=>Qe(i,e,n)),selections:t}},getSelectionKeys:()=>ci(A,At),matcherType:"or"})})}function J(A){return{[qe]:()=>({match:e=>({matched:!!A(e)})})}}function ui(...A){const e=typeof A[0]=="string"?A[0]:void 0,t=A.length===2?A[1]:typeof A[0]=="string"?void 0:A[0];return Fe({[qe]:()=>({match:n=>{let i={[e??Rr]:n};return{matched:t===void 0||Qe(t,n,(r,s)=>{i[r]=s}),selections:i}},getSelectionKeys:()=>[e??Rr].concat(t===void 0?[]:At(t))})})}function Rt(A){return typeof A=="number"}function pA(A){return typeof A=="string"}function mA(A){return typeof A=="bigint"}const yh=Fe(J(function(A){return!0})),mC=yh,BA=A=>Object.assign(Fe(A),{startsWith:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&n.startsWith(t)))));var t},endsWith:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&n.endsWith(t)))));var t},minLength:e=>BA(ae(A,(t=>J(n=>pA(n)&&n.length>=t))(e))),length:e=>BA(ae(A,(t=>J(n=>pA(n)&&n.length===t))(e))),maxLength:e=>BA(ae(A,(t=>J(n=>pA(n)&&n.length<=t))(e))),includes:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&n.includes(t)))));var t},regex:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&!!n.match(t)))));var t}}),BC=BA(J(pA)),Pt=A=>Object.assign(Fe(A),{between:(e,t)=>Pt(ae(A,((n,i)=>J(r=>Rt(r)&&n<=r&&i>=r))(e,t))),lt:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n<t))(e))),gt:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n>t))(e))),lte:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n<=t))(e))),gte:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n>=t))(e))),int:()=>Pt(ae(A,J(e=>Rt(e)&&Number.isInteger(e)))),finite:()=>Pt(ae(A,J(e=>Rt(e)&&Number.isFinite(e)))),positive:()=>Pt(ae(A,J(e=>Rt(e)&&e>0))),negative:()=>Pt(ae(A,J(e=>Rt(e)&&e<0)))}),vC=Pt(J(Rt)),vA=A=>Object.assign(Fe(A),{between:(e,t)=>vA(ae(A,((n,i)=>J(r=>mA(r)&&n<=r&&i>=r))(e,t))),lt:e=>vA(ae(A,(t=>J(n=>mA(n)&&n<t))(e))),gt:e=>vA(ae(A,(t=>J(n=>mA(n)&&n>t))(e))),lte:e=>vA(ae(A,(t=>J(n=>mA(n)&&n<=t))(e))),gte:e=>vA(ae(A,(t=>J(n=>mA(n)&&n>=t))(e))),positive:()=>vA(ae(A,J(e=>mA(e)&&e>0))),negative:()=>vA(ae(A,J(e=>mA(e)&&e<0)))}),CC=vA(J(mA)),wC=Fe(J(function(A){return typeof A=="boolean"})),yC=Fe(J(function(A){return typeof A=="symbol"})),bC=Fe(J(function(A){return A==null})),EC=Fe(J(function(A){return A!=null}));var SC={__proto__:null,matcher:qe,optional:Pa,array:function(...A){return Ra({[qe]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(A.length===0)return{matched:!0};const t=A[0];let n={};if(e.length===0)return At(t).forEach(r=>{n[r]=[]}),{matched:!0,selections:n};const i=(r,s)=>{n[r]=(n[r]||[]).concat([s])};return{matched:e.every(r=>Qe(t,r,i)),selections:n}},getSelectionKeys:()=>A.length===0?[]:At(A[0])})})},set:function(...A){return Fe({[qe]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(A.length===0)return{matched:!0};const n=(r,s)=>{t[r]=(t[r]||[]).concat([s])},i=A[0];return{matched:gC(e,r=>Qe(i,r,n)),selections:t}},getSelectionKeys:()=>A.length===0?[]:At(A[0])})})},map:function(...A){return Fe({[qe]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const n=(o,a)=>{t[o]=(t[o]||[]).concat([a])};if(A.length===0)return{matched:!0};var i;if(A.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(i=A[0])==null?void 0:i.toString()}`);const[r,s]=A;return{matched:pC(e,(o,a)=>{const c=Qe(r,a,n),u=Qe(s,o,n);return c&&u}),selections:t}},getSelectionKeys:()=>A.length===0?[]:[...At(A[0]),...At(A[1])]})})},intersection:ae,union:wh,not:function(A){return Fe({[qe]:()=>({match:e=>({matched:!Qe(A,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:J,select:ui,any:yh,_:mC,string:BC,number:vC,bigint:CC,boolean:wC,symbol:yC,nullish:bC,nonNullable:EC,instanceOf:function(A){return Fe(J(function(e){return t=>t instanceof e}(A)))},shape:function(A){return Fe(J(fC(A)))}};class UC extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const Da={matched:!1,value:void 0};function li(A){return new TC(A,Da)}let TC=class Iu{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],n=[e[0]];let i;e.length===3&&typeof e[1]=="function"?i=e[1]:e.length>2&&n.push(...e.slice(1,e.length-1));let r=!1,s={};const o=(c,u)=>{r=!0,s[c]=u},a=!n.some(c=>Qe(c,this.input,o))||i&&!i(this.input)?Da:{matched:!0,value:t(r?Rr in s?s[Rr]:s:this.input,this.input)};return new Iu(this.input,a)}when(e,t){if(this.state.matched)return this;const n=!!e(this.input);return new Iu(this.input,n?{matched:!0,value:t(this.input,this.input)}:Da)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=QC){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function QC(A){throw new UC(A)}const FC=/\{[^{}]+\}/g;function kC(){return Math.random().toString(36).slice(2,11)}function IC(A){let{baseUrl:e="",Request:t=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:r,headers:s,...o}={...A};e=Uh(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=n,Request:f=t,headers:g,params:p={},parseAs:B="json",querySerializer:y,bodySerializer:b=r??xC,body:v,...C}=l||{};d&&(e=Uh(d));let w=typeof i=="function"?i:Sh(i);y&&(w=typeof y=="function"?y:Sh({...typeof i=="object"?i:{},...y}));const S=v===void 0?void 0:b(v),F=S===void 0||S instanceof FormData?{}:{"Content-Type":"application/json"},_={redirect:"follow",...o,...C,body:S,headers:PC(F,s,g,p.header)};let D,O,M=new t(RC(u,{baseUrl:e,params:p,querySerializer:w}),_);for(const G in C)G in M||(M[G]=C[G]);if(a.length){D=kC(),O=Object.freeze({baseUrl:e,fetch:h,parseAs:B,querySerializer:w,bodySerializer:b});for(const G of a)if(G&&typeof G=="object"&&typeof G.onRequest=="function"){const q=await G.onRequest({request:M,schemaPath:u,params:p,options:O,id:D});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");M=q}}}let K=await h(M);if(a.length)for(let G=a.length-1;G>=0;G--){const q=a[G];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const et=await q.onResponse({request:M,response:K,schemaPath:u,params:p,options:O,id:D});if(et){if(!(et instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");K=et}}}if(K.status===204||K.headers.get("Content-Length")==="0")return K.ok?{data:{},response:K}:{error:{},response:K};if(K.ok)return B==="stream"?{data:K.body,response:K}:{data:await K[B](),response:K};let Pe=await K.text();try{Pe=JSON.parse(Pe)}catch{}return{error:Pe,response:K}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function Dr(A,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${A}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function bh(A,e,t){if(!e||typeof e!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)n.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=n.join(",");switch(t.style){case"form":return`${A}=${s}`;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${A}[${s}]`:s;n.push(Dr(o,e[s],t))}const r=n.join(i);return t.style==="label"||t.style==="matrix"?`${i}${r}`:r}function Eh(A,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const r={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(r);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return`${A}=${s}`}}const n={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const r of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?r:encodeURIComponent(r)):i.push(Dr(A,r,t));return t.style==="label"||t.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Sh(A){return function(t){const n=[];if(t&&typeof t=="object")for(const i in t){const r=t[i];if(r!=null){if(Array.isArray(r)){if(r.length===0)continue;n.push(Eh(i,r,{style:"form",explode:!0,...A?.array,allowReserved:A?.allowReserved||!1}));continue}if(typeof r=="object"){n.push(bh(i,r,{style:"deepObject",explode:!0,...A?.object,allowReserved:A?.allowReserved||!1}));continue}n.push(Dr(i,r,A))}}return n.join("&")}}function _C(A,e){let t=A;for(const n of A.match(FC)??[]){let i=n.substring(1,n.length-1),r=!1,s="simple";if(i.endsWith("*")&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const o=e[i];if(Array.isArray(o)){t=t.replace(n,Eh(i,o,{style:s,explode:r}));continue}if(typeof o=="object"){t=t.replace(n,bh(i,o,{style:s,explode:r}));continue}if(s==="matrix"){t=t.replace(n,`;${Dr(i,o)}`);continue}t=t.replace(n,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function xC(A){return A instanceof FormData?A:JSON.stringify(A)}function RC(A,e){let t=`${e.baseUrl}${A}`;e.params?.path&&(t=_C(t,e.params.path));let n=e.querySerializer(e.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(t+=`?${n}`),t}function PC(...A){const e=new Headers;for(const t of A){if(!t||typeof t!="object")continue;const n=t instanceof Headers?t.entries():Object.entries(t);for(const[i,r]of n)if(r===null)e.delete(i);else if(Array.isArray(r))for(const s of r)e.append(i,s);else r!==void 0&&e.set(i,r)}return e}function Uh(A){return A.endsWith("/")?A.substring(0,A.length-1):A}class Th{constructor(e){this.client=IC({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}async getAuthUrl(e){return await this.client.GET("/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/logout")}async getCurrentUser(){return await this.client.GET("/me")}async createPresignedUploadUrl(e){return await this.client.POST("/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/onboardees")}async getOnboardeeWhitelistedDomains(e){return await this.client.GET("/onboardees/{id}/whitelisted-domains",{params:{path:{id:e}}})}async listPlans(){return await this.client.GET("/plans")}async createPlan(e){return await this.client.POST("/plans",{body:e})}async getPlan(e){return await this.client.GET("/plans/{id}",{params:{path:{id:e}}})}async replacePlan(e,t){return await this.client.PUT("/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/plans/{id}",{params:{path:{id:e}},body:t})}async listSessions(e){return await this.client.GET("/sessions",{params:{query:e?{token:e}:{}}})}async createSession(e){return await this.client.POST("/sessions",{body:e})}async getSession(e){return await this.client.GET("/sessions/{id}",{params:{path:{id:e}}})}async getSessionRecording(e){return await this.client.GET("/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/sessions/{id}/product-url",{params:{path:{id:e}}})}async getJoinToken(e,{skipIntro:t}={}){return await this.client.GET("/join-token",{params:{query:{token:e,...t&&{skip_intro:"true"}}}})}getClient(){return this.client}}const DC="https://app.coragents.ai/api";var H;(function(A){A.READY="ready",A.ERROR="error",A.PAUSED="paused",A.LOADING="loading",A.THINKING="thinking",A.RESEARCHING="researching",A.AGENT_SPEAKING="agent_speaking",A.USER_SPEAKING="user_speaking",A.AWAITING_USER_INPUT="awaiting_user_input"})(H||(H={}));class LC{constructor({sessionId:e,apiBaseUrl:t}){this.currentState=H.READY,this.livekitState="speaking",this.assistantAudioContext=null,this.userAudioContext=null,this._assistantAudioTimer=null,this._userAudioTimer=null,this.sessionId=e,this.apiBaseUrl=t||DC,this.client=new Th({baseUrl:this.apiBaseUrl}),this.emitter=new Rm}emit(e,t){this.emitter.emit(e,t)}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setupRoomEventListeners(){this.room&&(this.room.on(Q.LocalTrackUnpublished,e=>{e.source===U.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(Q.Disconnected,()=>{this.disconnect()}),this.room.on(Q.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(Q.TrackSubscribed,(e,t,n)=>{if(e.kind==="audio"&&e.attach(),e.source===U.Source.Microphone&&n.identity.includes("agent-")){const i=e.mediaStream;if(!i){console.error("No media stream available for assistant track");return}const r=new AudioContext,s=r.createAnalyser();r.createMediaStreamSource(i).connect(s),s.fftSize=2048;const a=new Uint8Array(s.frequencyBinCount);this.analyzeAudio(s,a,"ASSISTANT"),this.assistantAudioContext=r}}),this.room.on(Q.ParticipantAttributesChanged,e=>{if(!e["lk.agent.state"]||this.currentState===H.RESEARCHING||this.currentState===H.PAUSED)return;const t=e["lk.agent.state"],n=li(t).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).with("thinking",()=>H.THINKING).otherwise(()=>{});n&&(this.setState(n),this.livekitState=t)}),this.room.on(Q.DataReceived,async e=>{try{const t=JSON.parse(new TextDecoder().decode(e)),n=t.status||t.request;li(n).with("using_tool",()=>{this.currentState=H.RESEARCHING,this.emitter.emit("stateChanged",H.RESEARCHING)}).with("using_tool_ended",()=>{this.currentState=H.AGENT_SPEAKING,this.emitter.emit("stateChanged",H.AGENT_SPEAKING)}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML")}).with("fill",()=>{this.emitter.emit("fill",t.value)}).otherwise(()=>{console.warn("Unknown data received:",t)})}catch(t){console.error("Error parsing data:",t)}}),this.room.localParticipant.registerRpcMethod("screen_capture",async e=>(this.emitter.emit("screenCaptureRequested"),new Promise(t=>{this.emitter.once("screenCaptureComplete",async n=>{if(n==="error"){t("error");return}try{await this.room.localParticipant.sendFile(new File([n],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),t("ok")}catch{t("error")}})}))))}async connect(){if(!this.sessionId){console.error("No session ID found"),this.emitter.emit("error",new Error("No session ID provided"));return}try{await this.requestMicrophone(),this.room=new VA({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=await this.client.getJoinToken(this.sessionId,{skipIntro:!0});if(await this.room.connect(e.data.url,e.data.token),this.microphoneStream){const t=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(t,{name:"microphone",source:U.Source.Microphone})}return{url:e.data.url,token:e.data.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",e instanceof Error?e:new Error(String(e))),e}}async disconnect(){this.room&&(this.room.disconnect(!0),this.room.removeAllListeners(),this.room=void 0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(e=>e.stop()),this._userAudioTimer&&(window.clearTimeout(this._userAudioTimer),this._userAudioTimer=null),this._assistantAudioTimer&&(window.clearTimeout(this._assistantAudioTimer),this._assistantAudioTimer=null),await this.userAudioContext?.close().catch(()=>{}),this.userAudioContext=null,await this.assistantAudioContext?.close().catch(()=>{}),this.assistantAudioContext=null,this.setState(H.READY),this.emitter.emit("disconnected")}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",e))}getCurrentState(){return this.currentState}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const n=t.createAnalyser(),i=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,i.connect(r),r.connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){if(!this.room){console.warn("[obi] shareScreen called while not connected");return}this.emitter.emit("preScreenShare");try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}pauseRecording(){this.room&&(this.setState(H.PAUSED),this.room.localParticipant.getTrackPublications().forEach(e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach(t=>t.enabled=!1)}),this.microphoneStream?.getTracks().forEach(e=>e.enabled=!1),this.screenStream?.track?.mute())}resumeRecording(){if(!this.room)return;const e=li(this.livekitState).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).otherwise(()=>H.THINKING);this.setState(e),this.room.localParticipant.getTrackPublications().forEach(t=>{t.handleUnmuted(),t.track?.mediaStream?.getTracks().forEach(n=>n.enabled=!0)}),this.microphoneStream?.getTracks().forEach(t=>t.enabled=!0),this.screenStream?.track?.unmute()}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,n){if(n==="USER"&&this.currentState===H.USER_SPEAKING||n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING){e.getByteFrequencyData(t);const i=t.reduce((o,a)=>o+a,0)/t.length,r=Math.max(.01,Math.min(1,i/128));let s;n==="USER"&&this.currentState===H.USER_SPEAKING?s="USER":n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING&&(s="ASSISTANT"),s&&this.emitter.emit("volume",{speaker:s,spectrum:Array.from(t),volume:r})}n==="USER"?this._userAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200):this._assistantAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},n=JSON.stringify(t),r=new TextEncoder().encode(n);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",t instanceof Error?t:new Error(String(t)))}}async reconnect(e,t,n){try{if(!e||!t)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",new Error("Missing room URL or token for reconnection")),!1;if(await this.requestMicrophone(),this.room=new VA({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,t),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:U.Source.Microphone})}return this.setState(n),n===H.PAUSED&&this.pauseRecording(),!0}catch(i){return console.error("Failed to reconnect to room:",i),this.disconnect(),this.emitter.emit("error",i instanceof Error?i:new Error(String(i))),!1}}}/**
|
|
42
|
+
`},Ba}var zd;function Cv(){if(zd)return yt;zd=1;var A=Bv(),e=vv(),t=ma();return yt.grammar=t,yt.write=e,yt.parse=A.parse,yt.parseParams=A.parseParams,yt.parseFmtpConfig=A.parseFmtpConfig,yt.parsePayloads=A.parsePayloads,yt.parseRemoteCandidates=A.parseRemoteCandidates,yt.parseImageAttributes=A.parseImageAttributes,yt.parseSimulcastStreamList=A.parseSimulcastStreamList,yt}var hA=Cv();function va(A,e,t){var n,i,r;e===void 0&&(e=50),t===void 0&&(t={});var s=(n=t.isImmediate)!=null&&n,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(g,p){var B=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var b=A.apply(f,h);o&&o(b),u.forEach(function(v){return(0,v.resolve)(b)}),u=[]}},l()),B){var y=A.apply(f,h);return o&&o(y),g(y)}u.push({resolve:g,reject:p})})};return d.cancel=function(h){r!==void 0&&clearTimeout(r),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const wv=.7,yv=20,Sn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Zd extends _t.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 n;super(),this.log=j,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=va(i=>m(this,void 0,void 0,function*(){this.emit(Sn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),yv),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Vt((n=t.loggerName)!==null&&n!==void 0?n:Ct.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return m(this,void 0,void 0,function*(){var t;let n;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=bv(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=hA.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of r.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),n=hA.write(i)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Sn.NegotiationComplete),e.sdp&&hA.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Sn.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const r=this._pc.remoteDescription;if(e?.iceRestart&&r)yield this._pc.setRemoteDescription(r);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const i=hA.parse((t=n.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{th(r),r.type==="audio"?eh(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(ri(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*wv);for(const c of r.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(n,hA.write(i)),this.onOffer(n)})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=hA.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(i=>{th(i),i.type==="audio"&&eh(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,hA.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ye("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 ye("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=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),n.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Wo(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!((n=e.ext)===null||n===void 0?void 0:n.some(s=>s.uri===xd))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:xd})}}}function eh(A,e,t){let n=0;A.rtp.some(i=>i.codec==="opus"?(n=i.payload,!0):!1),n>0&&(A.rtcpFb||(A.rtcpFb=[]),t.includes(A.mid)&&!A.rtcpFb.some(i=>i.payload===n&&i.type==="nack")&&A.rtcpFb.push({payload:n,type:"nack"}),e.includes(A.mid)&&A.fmtp.some(i=>i.payload===n?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function bv(A){var e;const t=[],n=[],i=hA.parse((e=A.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===r&&a.type==="nack")&&n.push(s.mid),s.fmtp.some(a=>a.payload===r?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function th(A){if(A.connection){const e=A.connection.ip.indexOf(":")>=0;(A.connection.version===4&&e||A.connection.version===6&&!e)&&(A.connection.ip="0.0.0.0",A.connection.version=4)}}const Ca="vp8",Ev={audioPreset:Yo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Zo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ca,backupCodec:!0},Ah={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},nh={deviceId:{ideal:"default"},resolution:ii.h720.resolution},Sv={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new g0,disconnectOnPageLeave:!0,webAudioMix:!1},wa={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var he;(function(A){A[A.NEW=0]="NEW",A[A.CONNECTING=1]="CONNECTING",A[A.CONNECTED=2]="CONNECTED",A[A.FAILED=3]="FAILED",A[A.CLOSING=4]="CLOSING",A[A.CLOSED=5]="CLOSED"})(he||(he={}));class Uv{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var i;this.peerConnectionTimeout=wa.peerConnectionTimeout,this.log=j,this.updateState=()=>{var r;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=he.CONNECTED:o.some(a=>a==="failed")?this.state=he.FAILED:o.some(a=>a==="connecting")?this.state=he.CONNECTING:o.every(a=>a==="closed")?this.state=he.CLOSED:o.some(a=>a==="closed")?this.state=he.CLOSING:o.every(a=>a==="new")&&(this.state=he.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(he[s]," to ").concat(he[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Vt((i=n.loggerName)!==null&&i!==void 0?i:Ct.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Zd(e,n),this.subscriber=new Zd(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,vt.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,vt.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=he.NEW,this.connectionLock=new je,this.remoteOfferLock=new je}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===vt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;const i=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{i()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Sn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Sn.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),n(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===vt.PUBLISHER?this.publisher.getConnectedAddress():e===vt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((a,c)=>m(r,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Te.clearTimeout(l),c(new re("room connection has been cancelled",W.Cancelled))};i?.signal.aborted&&u(),i?.signal.addEventListener("abort",u);const l=Te.setTimeout(()=>{i?.signal.removeEventListener("abort",u),c(new re("could not establish pc connection",W.InternalError))},s);for(;this.state!==he.CONNECTED;)if(yield Je(50),i?.signal.aborted){c(new re("room connection has been cancelled",W.Cancelled));return}Te.clearTimeout(l),i?.signal.removeEventListener("abort",u),a()}))}()})}}class fe extends Error{constructor(e,t,n){super(t),this.code=e,this.message=rh(t,fe.MAX_MESSAGE_BYTES),this.data=n?rh(n,fe.MAX_DATA_BYTES):void 0}static fromProto(e){return new fe(e.code,e.message,e.data)}toProto(){return new Cl({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new fe(fe.ErrorCode[e],fe.ErrorMessage[e],t)}}fe.MAX_MESSAGE_BYTES=256,fe.MAX_DATA_BYTES=15360,fe.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},fe.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 ih=15360;function ya(A){return new TextEncoder().encode(A).length}function rh(A,e){if(ya(A)<=e)return A;let t=0,n=A.length;const i=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);i.encode(A.slice(0,r)).length<=e?t=r:n=r-1}return A.slice(0,t)}const ba=2e3;function Qr(A,e){if(!e)return 0;let t,n;return"bytesReceived"in A?(t=A.bytesReceived,n=e.bytesReceived):"bytesSent"in A&&(t=A.bytesSent,n=e.bytesSent),t===void 0||n===void 0||A.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(A.timestamp-e.timestamp)}const Tv=1e3;class sh extends U{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,n){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=va(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(k.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new je,this.pauseUpstreamLock=new je,this.processorLock=new je,this.restartLock=new je,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==U.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return m(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{wn(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Cn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Cn(i??e,r)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Tv;return function*(){var n;if(e.kind===U.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=wt())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Je(10));const i=Date.now();for(;Date.now()-i<t;){const r=e.dimensions;if(r)return r;yield Je(50)}throw new jt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===lA(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),lA(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===U.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===U.Kind.Audio?"audioinput":"videoinput";return t?Ee.getInstance().normalizeDeviceId(r,n,i):n}()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){if(!this.sender)throw new jt("unable to replace an unpublished track");let n,i;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:i}=e,r=p0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===U.Kind.Video?s.video=n||i?{deviceId:n,facingMode:i}:!0:s.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{wn(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(r),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(k.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?k.Muted:k.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Rd()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(k.UpstreamPaused,this);const n=wt();if(n?.name==="Safari"&&NA(n.version,"12.0")<0)throw new $o("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(k.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),a={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(a),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Cn(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const c of n.attachedElements)c!==n.processorElement&&i&&(wn(n._mediaStreamTrack,c),Cn(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(k.TrackProcessorUpdate,n.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(k.TrackProcessorUpdate))}()})}}class Fr extends sh{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,U.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=Qr(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(k.AudioTrackFeatureUpdate,this,Bt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(k.AudioTrackFeatureUpdate,this,Bt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===U.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==lA(this._constraints.deviceId);return this.source===U.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=da({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Xe()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ba)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.processorLock.lock();try{if(!xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),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(k.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(i=>{i.type==="outbound-rtp"&&(n={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Gd(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(k.AudioSilenceDetected)),e})}}function Qv(A,e,t){switch(A.kind){case"audio":return new Fr(A,e,!1,void 0,t);case"video":return new Ir(A,e,!1,t);default:throw new jt("unsupported track type: ".concat(A.kind))}}const Fv=Object.values(ii),kv=Object.values(zo),Iv=Object.values(Zo),_v=[ii.h180,ii.h360],xv=[zo.h180,zo.h360],Rv=A=>[{scaleResolutionDownBy:2,fps:A.encoding.maxFramerate}].map(t=>{var n,i;return new ie(Math.floor(A.width/t.scaleResolutionDownBy),Math.floor(A.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(A.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=A.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,A.encoding.priority)}),Ea=["q","h","f"];function Sa(A,e,t,n){var i,r;let s=n?.videoEncoding;A&&(s=n?.screenShareEncoding);const o=n?.simulcast,a=n?.scalabilityMode,c=n?.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Dv(A,e,t,c),j.debug("using video encoding",s));const u=s.maxFramerate,l=new ie(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&ri(c)){const f=new kr(a),g=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const p=wt();if(uA()||xt()||p?.name==="Chrome"&&NA(p?.version,"113")<0){const B=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)g.push({rid:Ea[2-y],maxBitrate:s.maxBitrate/Math.pow(B,y),maxFramerate:l.encoding.maxFramerate});g[0].scalabilityMode=a}else g.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(g[0].priority=l.encoding.priority,g[0].networkPriority=l.encoding.priority),j.debug("using svc encoding",{encodings:g}),g}if(!o)return[s];let d=[];A?d=(i=ah(n?.screenShareSimulcastLayers))!==null&&i!==void 0?i:oh(A,l):d=(r=ah(n?.videoSimulcastLayers))!==null&&r!==void 0?r:oh(A,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const g=Math.max(e,t);if(g>=960&&h)return Ua(e,t,[f,h,l],u);if(g>=480)return Ua(e,t,[f,l],u)}return Ua(e,t,[l])}function Pv(A,e,t){var n,i,r,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&j.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=A.mediaStreamTrack.getSettings(),a=(n=o.width)!==null&&n!==void 0?n:(i=A.dimensions)===null||i===void 0?void 0:i.width,c=(r=o.height)!==null&&r!==void 0?r:(s=A.dimensions)===null||s===void 0?void 0:s.height;return A.source===U.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Sa(A.source===U.Source.ScreenShare,a,c,t)}function Dv(A,e,t,n){const i=Lv(A,e,t);let{encoding:r}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(r=a.encoding,a.width>=s)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Lv(A,e,t){if(A)return Iv;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Fv:kv}function oh(A,e){if(A)return Rv(e);const{width:t,height:n}=e,i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?_v:xv}function Ua(A,e,t,n){const i=[];if(t.forEach((r,s)=>{if(s>=Ea.length)return;const o=Math.min(A,e),c={rid:Ea[s],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},u=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=yn()||s===0;r.encoding.priority&&l&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),xt()&&Dd()==="ios"){let r;i.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=r&&(s&&(s=!1,j.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),j.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(r)),o.maxFramerate=r)})}return i}function ah(A){if(A)return A.sort((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class kr{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 Ov(A){return A.source===U.Source.ScreenShare||A.constraints.height&&lA(A.constraints.height)>=1080?"maintain-resolution":"balanced"}const Hv=5e3;class Ir extends sh{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,U.Kind.Video,t,n,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=Qr(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new je}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Xe())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ba))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=sA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)r=c.value,o=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){n={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=sA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const u=r;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){n={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=n.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,r)=>{var s,o;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let n=ot.LOW;n<=ot.HIGH;n+=1)t.push(new Ro({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;let o;if(e){const l=da({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=sA(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){r=u.value,a=!1;const l=r;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){n={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,n,r),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=sA(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(g){o={error:g}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Hv))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s,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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=sA(e);i=yield n.next(),r=i.done,!r;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield ch(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield ch(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Rd()&&this.isInBackground&&this.source===U.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ch(A,e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=yield n.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:A,qualities:t,senderEncodings:e}));try{const o=A.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:e}));return}let c=!1;const u=wt();if(u?.name==="Chrome"&&NA(u?.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new kr(d.scalabilityMode);let f=fn.OFF;if(t.forEach(g=>{g.enabled&&(f===fn.OFF||g.quality>f)&&(f=g.quality)}),f===fn.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const g=new kr(e[0].scalabilityMode);h.spatial=f+1,h.suffix=g.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let g=(f=d.rid)!==null&&f!==void 0?f:"";g===""&&(g="q");const p=uh(g),B=t.find(y=>y.quality===p);B&&d.active!==B.enabled&&(c=!0,d.active=B.enabled,i.debug("setting layer ".concat(B.quality," to ").concat(d.active?"enabled":"disabled"),r),yn()&&(B.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield A.setParameters(o))}finally{s()}})}function uh(A){switch(A){case"f":return ot.HIGH;case"h":return ot.MEDIUM;case"q":return ot.LOW;default:return ot.HIGH}}function lh(A,e,t,n){if(!t)return[new OA({quality:ot.HIGH,width:A,height:e,bitrate:0,ssrc:0})];if(n){const i=t[0].scalabilityMode,r=new kr(i),s=[],o=r.suffix=="h"?1.5:2,a=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new OA({quality:Math.min(ot.HIGH,r.spatial-1)-c,width:Math.ceil(A/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 s}return t.map(i=>{var r,s,o;const a=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=uh((s=i.rid)!==null&&s!==void 0?s:"");return new OA({quality:c,width:Math.ceil(A/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const dh="_lossy",hh="_reliable",Mv=2*1e3,Ta="leave-reconnect";var bt;(function(A){A[A.New=0]="New",A[A.Connected=1]="Connected",A[A.Disconnected=2]="Disconnected",A[A.Reconnecting=3]="Reconnecting",A[A.Closed=4]="Closed"})(bt||(bt={}));class Nv extends _t.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=wa.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=bt.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=j,this.handleDataChannel=n=>m(this,[n],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===hh)r.reliableDCSub=s;else if(s.label===dh)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const a=We.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(I.ActiveSpeakersUpdate,a.value.value.speakers):(((r=a.value)===null||r===void 0?void 0:r.case)==="user"&&Gv(a,a.value.value),this.emit(I.DataPacketReceived,a))}finally{s()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:s}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Y.LOSSY:Y.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,i)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(I.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){r(s);return}n===Ta&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Te.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,i)=>{this.pcState===bt.Connected&&n();const r=()=>{this.off(I.Disconnected,s),n()},s=()=>{this.off(I.Restarted,r),i()};this.once(I.Restarted,r),this.once(I.Disconnected,s)}),this.updateAndEmitDCBufferStatus=n=>{const i=this.isBufferStatusLow(n);typeof i<"u"&&i!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,i),this.emit(I.DCBufferStatusChanged,i,n))},this.isBufferStatusLow=n=>{const i=this.dataChannelForKind(n);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===oe.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(gn.RR_SIGNAL_DISCONNECTED))},this.log=Vt((t=e.loggerName)!==null&&t!==void 0?t:Ct.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new fa(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new je,this.dataProcessLock=new je,this.dcBufferStatus=new Map([[Y.LOSSY,!0],[Y.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(I.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(I.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(I.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(I.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(I.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(I.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(I.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(I.SignalRequestResponse,n)}get logContext(){var e,t,n,i,r,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,n,i){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(I.SignalConnected)},10),r}catch(r){if(r instanceof re&&r.reason===W.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw r}})}close(){return m(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(I.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new jt("a track with the same ID has already been published");return new Promise((t,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new re("publication of local track timed out, no response from server",W.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),t(r)},reject:()=>{clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return m(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==he.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new Uv(i,e.subscriberPrimary,this.loggerOptions),this.emit(I.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===he.CONNECTED){const u=this.pcState===bt.New;this.pcState=bt.Connected,u&&this.emit(I.Connected,e)}else r===he.FAILED&&this.pcState===bt.Connected&&(this.pcState=bt.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?gn.RR_SUBSCRIBER_FAILED:gn.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===oe.RECONNECTING,c=[he.FAILED,he.CLOSING,he.CLOSED].includes(r);a&&c&&!this._isClosed&&this.emit(I.Offline)}),this.pcManager.onTrack=r=>{this.emit(I.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Kv((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(I.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(I.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(I.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(I.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(I.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",gn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Bn.DISCONNECT:this.emit(I.Disconnected,e?.reason),this.close();break;case Bn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ta);break;case Bn.RESUME:this.handleDisconnect(Ta)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),n.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ti.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(dh,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(hh,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(ea())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ta())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(ea())return this.createSimulcastTransceiverSender(e,t,n,i);if(ta())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),En(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,i;if(!this._isClosed){if(this.attemptingReconnect){j.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===ti.DISABLED||((i=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&i!==void 0?i:he.NEW)===he.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let s=!0;r instanceof ye?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Un||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",gn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(I.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return m(this,void 0,void 0,function*(){var t,n,i;try{if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Un;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof re&&s.reason===W.NotAllowed?new ye("could not reconnect, token might be expired"):new Un}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(I.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==oe.CONNECTED)throw new Un("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(I.Restarted)}catch(r){const s=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return m(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");if(!this.pcManager)throw new ye("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof re&&i.reason===W.NotAllowed?new ye("could not reconnect, token might be expired"):i instanceof re&&i.reason===W.LeaveRequest?i:new Un(r)}if(this.emit(I.SignalResumed),n){const i=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(i)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==oe.CONNECTED)throw new Un("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(),this.emit(I.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=bt.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Je(Mv),!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=bt.Connected}catch(e){throw this.pcState=bt.Disconnected,new re("could not establish PC connection, ".concat(e.message),W.InternalError)}})}publishRpcResponse(e,t,n,i){return m(this,void 0,void 0,function*(){const r=new We({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcResponse",value:new vl({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Y.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new We({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcAck",value:new Bl({requestId:t})}});yield this.sendDataPacket(n,Y.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(n),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,n)=>m(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>n("Engine closed");for(this.once(I.Closing,i);!this.dcBufferStatus.get(e);)yield Je(10);this.off(I.Closing,i),t()}}))}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new ye("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new re("".concat(o," connection not set"),W.InternalError);let a=!1;!i&&!n.dataChannelForKind(t,i)&&(n.createDataChannels(),a=!0),!a&&!i&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&n.negotiate();const c=n.dataChannelForKind(t,i);if(c?.readyState==="open")return;const u=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((r=n.dataChannelForKind(t,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield Je(50)}throw new re("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),W.InternalError)}()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==he.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Wo("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(I.Closing,i),this.pcManager.publisher.once(Sn.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(o=>{const a=o.codec.toLowerCase();Y0(a)&&s.set(o.payload,a)}),this.emit(I.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof Wo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",gn.RR_UNKNOWN),t(r)}finally{this.off(I.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===Y.LOSSY)return this.lossyDCSub;if(e===Y.RELIABLE)return this.reliableDCSub}else{if(e===Y.LOSSY)return this.lossyDC;if(e===Y.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new Ll({answer:r?Tr({sdp:r.sdp,type:r.type}):void 0,offer:s?Tr({sdp:s.sdp,type:s.type}):void 0,subscription:new lr({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:sv(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,i)=>{n?.id!==void 0&&n.id!==null&&e.push(new Ol({label:n.label,id:n.id,target:i}))};return t(this.dataChannelForKind(Y.LOSSY),vt.PUBLISHER),t(this.dataChannelForKind(Y.RELIABLE),vt.PUBLISHER),t(this.dataChannelForKind(Y.LOSSY,!0),vt.SUBSCRIBER),t(this.dataChannelForKind(Y.RELIABLE,!0),vt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Te.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Xe()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Xe()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Un extends Error{}function Kv(A){return A!==void 0&&A>13}function Gv(A,e){const t=A.participantIdentity?A.participantIdentity:e.participantIdentity;A.participantIdentity=t,e.participantIdentity=t;const n=A.destinationIdentities.length!==0?A.destinationIdentities:e.destinationIdentities;A.destinationIdentities=n,e.destinationIdentities=n}class Qa{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return na(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(i=>i.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),j.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(Vv(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new re("Could not fetch region settings: ".concat(t.statusText),t.status===401?W.NotAllowed:W.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Vv(A){return"".concat(A.protocol.replace("ws","http"),"//").concat(A.host,"/settings")}class fh{get info(){return this._info}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class jv extends fh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>m(this,void 0,void 0,function*(){try{const{done:t,value:n}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r=new Set;try{for(var s=!0,o=sA(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;r.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class $v extends fh{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Sr(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>m(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r="";try{for(var s=!0,o=sA(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,r+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return r})}}class gh{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Wv extends gh{}class Jv extends gh{}class ph extends U{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?k.Muted:k.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.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(k.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ba)),ov()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:i,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(k.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Xv extends ph{constructor(e,t,n,i,r,s){super(e,t,U.Kind.Audio,n,s),this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Qr(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(xt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Aa(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Aa(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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 n=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{n.connect(i),n=i}),this.gainNode=e.createGain(),n.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(k.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(k.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Fa=100;class qv extends ph{constructor(e,t,n,i,r){super(e,t,U.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=Qr(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=va(()=>{this.updateDimensions()},Fa),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?wn(this._mediaStreamTrack,t):Cn(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 Yv(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&i.set(r.id,r)}),t&&n!==""&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-n<Fa){Te.setTimeout(()=>{this.updateVisibility()},Fa);return}this.lastVisible=s,this.emit(k.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let n=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*r,a=s.height()*r;o+a>n+i&&(n=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:n,height:i},this.emit(k.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Ld():t||(Ld()>2?2:1)}}class Yv{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var i;const{target:r,isIntersecting:s}=n;r===this.element&&(this.isIntersecting=s,this.isPiP=ai(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var n,i,r;(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ai(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=ai(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??ka(e),this.isPiP=Xe()&&ai(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=ka(this.element),this.isPiP=ai(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Hd().observe(this.element),Od().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),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,r;(e=Hd())===null||e===void 0||e.unobserve(this.element),(t=Od())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function ai(A){var e,t;return document.pictureInPictureElement===A?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ka(A,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function ka(A,e){const t=e||window;let n=A.offsetTop,i=A.offsetLeft;const r=A.offsetWidth,s=A.offsetHeight,{hidden:o}=A,{display:a}=getComputedStyle(A);for(;A.offsetParent;)A=A.offsetParent,n+=A.offsetTop,i+=A.offsetLeft;return n<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&n+s>t.pageYOffset&&i+r>t.pageXOffset&&!o&&a!=="none"}class Wt extends _t.EventEmitter{constructor(e,t,n,i){var r;super(),this.metadataMuted=!1,this.encryption=tt.NONE,this.log=j,this.handleMuted=()=>{this.emit(k.Muted)},this.handleUnmuted=()=>{this.emit(k.Unmuted)},this.log=Vt((r=i?.loggerName)!==null&&r!==void 0?r:Ct.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=U.Source.Unknown}setTrack(e){this.track&&(this.track.off(k.Muted,this.handleMuted),this.track.off(k.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(k.Muted,this.handleMuted),e.on(k.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Z(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==tt.NONE}get audioTrack(){if($t(this.track))return this.track}get videoTrack(){if(En(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=U.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===U.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(A){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(A.SubscriptionStatus||(A.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(A.PermissionStatus||(A.PermissionStatus={}))})(Wt||(Wt={}));class Ia extends Wt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(k.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(k.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(k.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if($t(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Bt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Bt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Bt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Bt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(Bt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Bt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function _r(A,e){return m(this,void 0,void 0,function*(){A??(A={});let t=!1;const{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:r}=$d(A);let s=r.audio,o=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),i&&typeof r.video=="object"&&(r.video.processor=i),A.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const l=r.audio.deviceId;r.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:l}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const l=r.video.deviceId;r.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:l}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const a=Kd(r,Ah,nh),c=da(a),u=navigator.mediaDevices.getUserMedia(c);r.audio&&(Ee.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Ee.userMediaPromiseMap.delete("audioinput"))),r.video&&(Ee.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Ee.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>m(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let g;const p=h?c.audio:c.video;typeof p!="boolean"&&(g=p);const B=d.getSettings().deviceId;g?.deviceId&&lA(g.deviceId)!==B?g.deviceId=B:g||(g={deviceId:B});const y=Qv(d,g,e);return y.kind===U.Kind.Video?y.source=U.Source.Camera:y.kind===U.Kind.Audio&&(y.source=U.Source.Microphone),y.mediaStream=l,$t(y)&&n?yield y.setProcessor(n):En(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return _r(Object.assign(Object.assign({},A),{audio:s,video:o}),e)}})}function zv(A){return m(this,void 0,void 0,function*(){return(yield _r({audio:!1,video:A??!0}))[0]})}function Zv(A){return m(this,void 0,void 0,function*(){return(yield _r({audio:A??!0,video:!1}))[0]})}var fA;(function(A){A.Excellent="excellent",A.Good="good",A.Poor="poor",A.Lost="lost",A.Unknown="unknown"})(fA||(fA={}));function eC(A){switch(A){case ei.EXCELLENT:return fA.Excellent;case ei.GOOD:return fA.Good;case ei.POOR:return fA.Poor;case ei.LOST:return fA.Lost;default:return fA.Unknown}}class mh extends _t.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===ur.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===pn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,i,r,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ur.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=fA.Unknown,this.log=j,this.log=Vt((a=s?.loggerName)!==null&&a!==void 0?a:Ct.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new oa,this.once(x.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(U.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(U.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(U.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===pn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==pn.ACTIVE&&this.emit(x.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(x.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(x.ParticipantNameChanged,e)}_setAttributes(e){const t=av(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(x.AttributesChanged,t)}setPermissions(e){var t,n,i,r,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(x.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(x.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=eC(e),t!==this._connectionQuality&&this.emit(x.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=>$t(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(k.Muted,()=>{this.emit(x.TrackMuted,e)}),e.on(k.Unmuted,()=>{this.emit(x.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case U.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case U.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function tC(A){var e,t,n;if(!A.participantSid&&!A.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Pl({participantIdentity:(e=A.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=A.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=A.allowAll)!==null&&n!==void 0?n:!1,trackSids:A.allowedTrackSids||[]})}const Bh=15e3;class AC extends mh{constructor(e,t,n,i,r){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=tt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new oa)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,u=this.pendingSignalRequests.get(o);u&&(a!==Po.OK&&u.reject(new kd(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=fe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>tC(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Z(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Z(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Z(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>m(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const B=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,g=sA(B),p;p=yield g.next(),o=p.done,!o;f=!0){u=p.value,f=!1;const y=u;M0(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Z(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=g.return)&&(yield c.call(g))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>m(this,void 0,void 0,function*(){if(s.source===U.Source.ScreenShare||s.source===U.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Z(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(GA(s)||dA(s))try{if(Xe())try{const o=yield navigator?.permissions.query({name:s.source===U.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Z(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Z(s))),GA(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Z(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==tt.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){this.engine=e,this.engine.on(I.RemoteMute,(t,n)=>{const i=this.trackPublications.get(t);!i||!i.track||(n?i.mute():i.unmute())}),this.engine.on(I.Connected,this.handleReconnected).on(I.SignalRestarted,this.handleReconnected).on(I.SignalResumed,this.handleReconnected).on(I.Restarting,this.handleReconnecting).on(I.Resuming,this.handleReconnecting).on(I.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(I.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(I.Disconnected,this.handleDisconnected).on(I.SignalRequestResponse,this.handleSignalRequestResponse).on(I.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let{metadata:i,name:r,attributes:s}=t;return function*(){return new Promise((o,a)=>m(n,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=r??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[g,p]=f;return this.attributes[g]===p||p===""&&!this.attributes[g]}))){this.pendingSignalRequests.delete(d),o();return}yield Je(50)}a(new kd("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(U.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(U.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(U.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(x.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?tt.GCM:tt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,i){return m(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c?.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case U.Source.Camera:a=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case U.Source.Microphone:a=yield this.createTracks({audio:(s=n)!==null&&s!==void 0?s:!0});break;case U.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},n));break;default:throw new jt(e)}}catch(c){throw a?.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(x.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Z(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a?.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===U.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(U.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(U.Source.Camera)||this.pendingPublishing.has(U.Source.Microphone))){this.pendingPublishing.add(U.Source.Camera),this.pendingPublishing.add(U.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(U.Source.Camera),this.pendingPublishing.delete(U.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const i=Kd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield _r(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>($t(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=U.Source.Microphone,this.emit(x.AudioStreamAcquired)),En(o)&&(this.cameraError=void 0,o.source=U.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new $o("getDisplayMedia not supported");e.resolution===void 0&&!$0()&&(e.resolution=Zo.h1080fps30.resolution);const t=rv(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(i.length===0)throw new jt("no video track found");const r=new Ir(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=U.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(x.AudioStreamAcquired);const o=new Fr(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=U.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;GA(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!s&&(yield r.republishPromise),bn(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let l;if(n instanceof MediaStreamTrack)l=n.getConstraints();else{l=n.constraints;let B;switch(n.source){case U.Source.Microphone:B="audioinput";break;case U.Source.Camera:B="videoinput"}B&&r.activeDeviceMap.has(B)&&(l=Object.assign(Object.assign({},l),{deviceId:r.activeDeviceMap.get(B)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Fr(n,l,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new Ir(n,l,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new jt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let d;if(r.trackPublications.forEach(B=>{B.track&&B.track===n&&(d=B)}),d)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Z(d))),d;const h="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i?.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),Z(n))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(u=i.red)!==null&&u!==void 0||(i.red=!1));const g=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!W0()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),g.simulcast=!1),g.source&&(n.source=g.source);const p=new Promise((B,y)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==oe.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Z(n)}));const b=()=>m(this,void 0,void 0,function*(){try{const v=yield this.publish(n,g,f);B(v)}catch(v){y(v)}});setTimeout(()=>{this.engine.off(I.SignalConnected,b),y(new Jo("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(I.SignalConnected,b),this.engine.on(I.Closing,()=>{this.engine.off(I.SignalConnected,b),y(new Jo("publishing rejected as engine closed",499))})}else try{const b=yield this.publish(n,g,f);B(b)}catch(b){y(b)}}catch(b){y(b)}}));r.pendingPublishPromises.set(n,p);try{return yield p}catch(B){throw B}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Z(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(i=>cv(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Z(e))),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var i,r,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new Jo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(C=>bn(e)&&C.source===e.source)&&e.source!==U.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Z(e))),t.stopMicTrackOnMute&&$t(e)&&(e.stopOnMute=!0),e.source===U.Source.ScreenShare&&yn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!G0()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!V0()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Ca),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(C=>t.videoCodec===Ur(C.mime))||(t.videoCodec=Ur(this.enabledPublishVideoCodecs[0].mime)));const g=t.videoCodec;e.on(k.Muted,this.onTrackMuted),e.on(k.Unmuted,this.onTrackUnmuted),e.on(k.Ended,this.handleTrackEnded),e.on(k.UpstreamPaused,this.onTrackUpstreamPaused),e.on(k.UpstreamResumed,this.onTrackUpstreamResumed),e.on(k.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const p=new ko({cid:e.mediaStreamTrack.id,name:t.name,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy});let B;if(e.kind===U.Kind.Video){let C={width:0,height:0};try{C=yield e.waitForDimensions()}catch{const S=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:ii.h720.resolution;C={width:S.width,height:S.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Z(e)),{dims:C}))}p.width=C.width,p.height=C.height,dA(e)&&(ri(g)&&(e.source===U.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Z(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),p.simulcastCodecs=[new Fo({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Ca}),t.backupCodec&&g!==t.backupCodec.codec&&p.encryption===tt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),p.simulcastCodecs.push(new Fo({codec:t.backupCodec.codec,cid:""})))),B=Sa(e.source===U.Source.ScreenShare,p.width,p.height,t),p.layers=lh(p.width,p.height,B,ri(t.videoCodec))}else e.kind===U.Kind.Audio&&(B=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const y=()=>m(this,void 0,void 0,function*(){var C,w,S;if(!this.engine.pcManager)throw new ye("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,B),dA(e)&&((C=t.degradationPreference)!==null&&C!==void 0||(t.degradationPreference=Ov(e)),e.setDegradationPreference(t.degradationPreference)),B)if(yn()&&e.kind===U.Kind.Audio){let F;for(const _ of this.engine.pcManager.publisher.getTransceivers())if(_.sender===e.sender){F=_;break}F&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:F,codec:"opus",maxbr:!((w=B[0])===null||w===void 0)&&w.maxBitrate?B[0].maxBitrate/1e3:0})}else e.codec&&ri(e.codec)&&(!((S=B[0])===null||S===void 0)&&S.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:p.cid,codec:e.codec,maxbr:B[0].maxBitrate/1e3});yield this.engine.negotiate()});let b;if(this.enabledPublishVideoCodecs.length>0)b=(yield Promise.all([this.engine.addTrack(p),y()]))[0];else{b=yield this.engine.addTrack(p);let C;if(b.codecs.forEach(w=>{C===void 0&&(C=w.mimeType)}),C&&e.kind===U.Kind.Video){const w=Ur(C);w!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Z(e)),{codec:w})),t.videoCodec=w,B=Sa(e.source===U.Source.ScreenShare,p.width,p.height,t))}yield y()}const v=new Ia(e.kind,b,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return v.options=t,e.sid=b.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:B,trackInfo:b})),dA(e)?e.startMonitor(this.engine.client):GA(e)&&e.startMonitor(),this.addTrackPublication(v),this.emit(x.LocalTrackPublished,v),v})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var i;if(this.encryptionType!==tt.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new jt("track is not published");if(!dA(e))throw new jt("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),n),o=Pv(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Z(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ko({cid:a.mediaStreamTrack.id,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=lh(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,i;if(bn(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Z(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?Z(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(k.Muted,this.onTrackMuted),e.off(k.Unmuted,this.onTrackUnmuted),e.off(k.Ended,this.handleTrackEnded),e.off(k.UpstreamPaused,this.onTrackUpstreamPaused),e.off(k.UpstreamResumed,this.onTrackUpstreamResumed),e.off(k.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!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<he.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),dA(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case U.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case U.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(x.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,s)=>m(n,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=>m(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==U.Source.ScreenShare&&c.source!==U.Source.ScreenShareAudio&&(GA(c)||dA(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),r()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?Y.RELIABLE:Y.LOSSY,s=i.destinationIdentities,o=i.topic,a=new We({kind:r,value:{case:"user",value:new gl({participantIdentity:n.identity,payload:t,destinationIdentities:s,topic:o})}});yield n.engine.sendDataPacket(a,r)}()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new We({kind:Y.RELIABLE,value:{case:"sipDtmf",value:new pl({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Y.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},i=new We({value:{case:"chatMessage",value:new bo(Object.assign(Object.assign({},n),{timestamp:ue.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(x.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new We({value:{case:"chatMessage",value:new bo(Object.assign(Object.assign({},n),{timestamp:ue.parse(n.timestamp),editTimestamp:ue.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(x.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(n=t?.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((g,p)=>g+p,0);(h=t?.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield u.write(e),c(1,0),yield u.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>m(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return m(this,void 0,void 0,function*(){var t,n;const i=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes},s=new So({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:KA(r.timestamp),totalLength:KA(e?.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Tl({version:e?.version,attachedStreamIds:e?.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Eo.UPDATE:Eo.CREATE})}}),o=e?.destinationIdentities,a=new We({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,Y.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return m(this,void 0,void 0,function*(){for(const g of nv(f,Bh)){yield u.engine.waitForBufferStatusLow(Y.RELIABLE);const p=new Uo({content:g,streamId:i,chunkIndex:KA(c)}),B=new We({destinationIdentities:o,value:{case:"streamChunk",value:p}});yield u.engine.sendDataPacket(B,Y.RELIABLE),c+=1}})},close(){return m(this,void 0,void 0,function*(){const f=new To({streamId:i}),g=new We({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(g,Y.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>m(this,void 0,void 0,function*(){yield h.close()});u.engine.once(I.Closing,d);const h=new Wv(l,r,()=>this.engine.off(I.Closing,d));return h})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=n?.mimeType)!==null&&i!==void 0?i:t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield r.write(a)}return yield r.close(),r.info})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;const o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e?.destinationIdentities,c={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(i=e?.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown"},u=new So({totalLength:KA((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:KA(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Ql({name:c.name})}}),l=new We({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,Y.RELIABLE);let d=0;const h=new je,f=this.engine,g=this.log,p=new WritableStream({write(y){return m(this,void 0,void 0,function*(){const b=yield h.lock();let v=0;try{for(;v<y.byteLength;){const C=y.slice(v,v+Bh);yield f.waitForBufferStatusLow(Y.RELIABLE);const w=new We({destinationIdentities:a,value:{case:"streamChunk",value:new Uo({content:C,streamId:o,chunkIndex:KA(d)})}});yield f.sendDataPacket(w,Y.RELIABLE),d+=1,v+=C.byteLength}}finally{b()}})},close(){return m(this,void 0,void 0,function*(){const y=new To({streamId:o}),b=new We({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(b,Y.RELIABLE)})},abort(y){g.error("Sink error:",y)}});return new Jv(p,c)})}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>m(n,void 0,void 0,function*(){var l,d,h,f;if(ya(s)>ih){u(fe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&NA((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){u(fe.builtIn("UNSUPPORTED_SERVER"));return}const g=crypto.randomUUID();yield this.publishRpcRequest(i,g,r,s,o-2e3);const p=setTimeout(()=>{this.pendingAcks.delete(g),u(fe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(B)},2e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(p)},participantIdentity:i});const B=setTimeout(()=>{this.pendingResponses.delete(g),u(fe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(g,{resolve:(y,b)=>{clearTimeout(B),this.pendingAcks.has(g)&&(console.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(p)),b?u(b):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=new We({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcRequest",value:new ml({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,Y.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,fe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,i;const r=this.trackPublications.get(t.sid);if(r){const s=r.isMuted||((i=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Z(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(GA(i)||dA(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield Je(20)}})}}class nC extends Wt{constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ot.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(k.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new lr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new wl({participantSid:"",trackSids:[this.trackSid]})]});this.emit(k.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Wt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Wt.SubscriptionStatus.Subscribed:Wt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Wt.PermissionStatus.Allowed:Wt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(ua(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ua(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(k.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(k.VisibilityChanged,this.handleVisibilityChange),i.off(k.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(k.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(k.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(k.VisibilityChanged,this.handleVisibilityChange),e.on(k.Ended,this.handleEnded),this.emit(k.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(k.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?k.Muted:k.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(k.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(k.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===U.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ua(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new kl({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=ot.HIGH,this.emit(k.UpdateSettings,e)}}class xr extends mh{static fromParticipantInfo(e,t,n){return new xr(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ur.STANDARD;super(t,n||"",i,r,s,o,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(k.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Z(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(k.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(k.SubscriptionPermissionChanged,t=>{this.emit(x.TrackSubscriptionPermissionChanged,e,t)}),e.on(k.SubscriptionStatusChanged,t=>{this.emit(x.TrackSubscriptionStatusChanged,e,t)}),e.on(k.Subscribed,t=>{this.emit(x.TrackSubscribed,t,e)}),e.on(k.Unsubscribed,t=>{this.emit(x.TrackUnsubscribed,t,e)}),e.on(k.SubscriptionFailed,t=>{this.emit(x.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]:U.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:U.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,i,r,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(x.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,i,r,s-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),Z(o))),this.emit(x.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new qv(e,t,i,r):c=new Xv(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ca(c)&&$t(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,n=new Map;return e.tracks.forEach(i=>{var r,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=U.kindFromProto(i.type);if(!a)return;o=new nC(a,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),n.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===o?.source);c&&o.source!==U.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:Z(c),newTrack:Z(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Z(i))),this.unpublishTrack(i.trackSid,!0))}),n.forEach(i=>{this.emit(x.TrackPublished,i)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case U.Kind.Audio:this.audioTrackPublications.delete(e);break;case U.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(x.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var i;$t(n.track)&&ca(n.track)&&t.push(n.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var z;(function(A){A.Disconnected="disconnected",A.Connecting="connecting",A.Connected="connected",A.Reconnecting="reconnecting",A.SignalReconnecting="signalReconnecting"})(z||(z={}));const iC=4*1e3;class VA extends _t.EventEmitter{constructor(e){var t,n,i,r;if(super(),t=this,this.state=z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=j,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>m(this,void 0,void 0,function*(){var c;if(!j0())throw xt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===z.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(z.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),na(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Qa(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const l=(h,f,g)=>m(this,void 0,void 0,function*(){var p,B;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u?.();try{yield this.attemptConnection(g??s,o,a,y),this.abortController=void 0,h()}catch(b){if(this.regionUrlProvider&&b instanceof re&&b.reason!==W.Cancelled&&b.reason!==W.NotAllowed){let v=null;try{v=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(C){if(C instanceof re&&(C.status===401||C.reason===W.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(C);return}}v&&!(!((B=this.abortController)===null||B===void 0)&&B.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(b.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield l(h,f,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Nd(b)),f(b))}else{let v=mt.UNKNOWN_REASON;b instanceof re&&(v=Nd(b)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),f(b)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new oa((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>m(this,void 0,void 0,function*(){var d,h,f;const g=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let p=g.serverInfo;if(p||(p={version:g.serverVersion,region:g.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(B=>{let[y,b]=B;return"".concat(y,": ").concat(b)}).join(", ")),{room:(d=g.room)===null||d===void 0?void 0:d.name,roomSid:(h=g.room)===null||h===void 0?void 0:h.sid,identity:(f=g.participant)===null||f===void 0?void 0:f.identity}),!p.version)throw new k0("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),g}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>m(this,void 0,void 0,function*(){var u,l;this.state===z.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},wa),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(Q.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new re("could not establish signal connection",W.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof re&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new re("Connection attempt aborted",W.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Xe()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Xe()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(z.Connected),this.emit(Q.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return m(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const g=yield c.disconnectLock.lock();try{if(c.state===z.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===z.Connecting||c.state===z.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new re("Client initiated disconnect",W.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,mt.CLIENT_INITIATED),c.engine=void 0}finally{g()}}()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const s=[],o=wt();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=sa();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(Q.Disconnected,()=>{c?.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{s.includes(u)||s.push(u)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(Q.Reconnecting)},this.handleSignalRestarted=s=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(z.Connected),this.emit(Q.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===pn.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(Q.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(Q.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=U.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(x.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(Q.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(Q.DataReceived,o.payload,s,a,o.topic),s?.emit(x.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(Q.SipDTMFReceived,o,s),s?.emit(x.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a?.trackPublications.get(o.trackId),u=Z0(o,this.transcriptionReceivedTimes);c?.emit(k.TranscriptionReceived,u),a?.emit(x.TranscriptionReceived,u,c),this.emit(Q.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=ev(o);this.emit(Q.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(Q.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Q.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Q.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Q.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Q.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var s,o,a;const c=Ee.getInstance().previousDevices,u=yield Ee.getInstance().getDevices(void 0,!1),l=wt();if(l?.name==="Chrome"&&l.os!=="iOS")for(let h of u){const f=c.find(g=>g.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(Q.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=iv(h),g=this.localParticipant.getTrackPublication(f);if(g&&(!((s=g.track)===null||s===void 0)&&s.isUserProvided))continue;const p=u.filter(y=>y.kind===h),B=this.getActiveDevice(h);if(B===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&p.length>0&&((a=p[0])===null||a===void 0?void 0:a.deviceId)!==B){yield this.switchActiveDevice(h,p[0].deviceId);continue}h==="audioinput"&&!uA()||h==="videoinput"||p.length>0&&!p.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,p[0].deviceId))}this.emit(Q.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(Q.RoomMetadataChanged,s.metadata),o?.activeRecording!==s.activeRecording&&this.emitWhenConnected(Q.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(Q.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(Q.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(Q.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(Q.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(Q.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s?.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>m(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(k.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(k.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(Q.LocalTrackPublished,s,this.localParticipant),GA(s.track)&&(yield s.track.checkForSilence())&&this.emit(Q.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=jd(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(Q.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(k.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(k.Restarted,this.onLocalTrackRestarted),this.emit(Q.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>m(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=jd(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(Q.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(Q.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(Q.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(Q.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(Q.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Sv),e),this.log=Vt((n=this.options.loggerName)!==null&&n!==void 0?n:Ct.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ah),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},nh),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ev),e?.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new je,this.localParticipant=new AC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",lA(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",lA(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",lA(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Xe()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),VA.cleanupRegistry&&VA.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,n,i,r,s){return m(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,fe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,fe.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:r});ya(u)>ih?(a=fe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=u}catch(u){u instanceof fe?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),u),a=fe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new uv(this.options.e2ee),this.e2eeManager.on(aA.ParticipantEncryptionStatusChanged,(t,n)=>{Av(n)&&(this.isE2EEEnabled=t),this.emit(Q.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(aA.EncryptionError,t=>this.emit(Q.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return m(this,void 0,void 0,function*(){return this.state===z.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=i=>{i.sid!==""&&(this.engine.off(I.RoomUpdate,n),e(i.sid))};this.engine.on(I.RoomUpdate,n),this.once(Q.Disconnected,()=>{this.engine.off(I.RoomUpdate,n),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Nv(this.options),this.engine.on(I.ParticipantUpdate,this.handleParticipantUpdates).on(I.RoomUpdate,this.handleRoomUpdate).on(I.SpeakersChanged,this.handleSpeakersChanged).on(I.StreamStateChanged,this.handleStreamStateUpdate).on(I.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(I.SubscriptionError,this.handleSubscriptionError).on(I.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(I.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(I.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(I.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(I.DataPacketReceived,this.handleDataPacket).on(I.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(z.SignalReconnecting)&&this.emit(Q.SignalReconnecting)}).on(I.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(z.Connected)&&this.emit(Q.Reconnected)}).on(I.SignalResumed,()=>{this.bufferedEvents=[],(this.state===z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(I.Restarting,this.handleRestarting).on(I.SignalRestarted,this.handleSignalRestarted).on(I.Offline,()=>{this.setAndEmitConnectionState(z.Reconnecting)&&this.emit(Q.Reconnecting)}).on(I.DCBufferStatusChanged,(e,t)=>{this.emit(Q.DCBufferStatusChanged,e,t)}).on(I.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:i}=n;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(x.LocalTrackSubscribed,t),this.emitWhenConnected(Q.LocalTrackSubscribed,t,this.localParticipant)}).on(I.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(Q.Moved,e.room.name,e.token),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ee.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(na(new URL(e))&&t){this.regionUrlProvider=new Qa(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===z.Disconnected&&(this.regionUrl=n,yield fetch(aa(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(aa(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let n=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new It({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new It({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new It({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new It({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":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new It({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new It({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":i=new It({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new dr({reason:mt.CLIENT_INITIATED,action:Bn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new It({scenario:{case:"subscriberBandwidth",value:KA(t)}});break;case"leave-full-reconnect":i=new It({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let g=!0,p=!1;const B=s?{exact:i}:i;if(n==="audioinput"){p=r.localParticipant.audioTrackPublications.size===0;const y=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=B;const b=Array.from(r.localParticipant.audioTrackPublications.values()).filter(v=>v.source===U.Source.Microphone);try{g=(yield Promise.all(b.map(v=>{var C;return(C=v.audioTrack)===null||C===void 0?void 0:C.setDeviceId(B)}))).every(v=>v===!0)}catch(v){throw r.options.audioCaptureDefaults.deviceId=y,v}}else if(n==="videoinput"){p=r.localParticipant.videoTrackPublications.size===0;const y=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=B;const b=Array.from(r.localParticipant.videoTrackPublications.values()).filter(v=>v.source===U.Source.Camera);try{g=(yield Promise.all(b.map(v=>{var C;return(C=v.videoTrack)===null||C===void 0?void 0:C.setDeviceId(B)}))).every(v=>v===!0)}catch(v){throw r.options.videoCaptureDefaults.deviceId=y,v}}else if(n==="audiooutput"){if(!Aa()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield Ee.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=r.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=r.getActiveDevice(n))!==null&&l!==void 0?l:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((d=r.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(b=>b.setAudioOutput({deviceId:i})))}catch(b){throw r.options.audioOutput.deviceId=y,b}}return(p||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(Q.ActiveDeviceChanged,n,i)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(x.AttributesChanged,this.onLocalAttributesChanged).on(x.TrackMuted,this.onLocalTrackMuted).on(x.TrackUnmuted,this.onLocalTrackUnmuted).on(x.LocalTrackPublished,this.onLocalTrackPublished).on(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(x.MediaDevicesError,this.onMediaDevicesError).on(x.AudioStreamAcquired,this.startAudio).on(x.ChatMessage,this.onLocalChatMessageSent).on(x.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===z.Connecting||this.state===z.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),l()},l=()=>{this.off(Q.Reconnected,u),this.off(Q.Connected,u),this.off(Q.Disconnected,l)};this.once(Q.Reconnected,u),this.once(Q.Connected,u),this.once(Q.Disconnected,l);return}if(this.state===z.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const i=K0(t.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,n,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==z.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(x.AttributesChanged,this.onLocalAttributesChanged).off(x.TrackMuted,this.onLocalTrackMuted).off(x.TrackUnmuted,this.onLocalTrackUnmuted).off(x.LocalTrackPublished,this.onLocalTrackPublished).off(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(x.MediaDevicesError,this.onMediaDevicesError).off(x.AudioStreamAcquired,this.startAudio).off(x.ChatMessage,this.onLocalChatMessageSent).off(x.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),Xe()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(z.Disconnected),this.emit(Q.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(Q.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return m(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Sr(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new jv(s,o,Sr(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new $v(s,o,Sr(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Vd())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Je(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(Q.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let i;return t?i=xr.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new xr(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Q.ParticipantConnected,n),n.on(x.TrackPublished,i=>{this.emitWhenConnected(Q.TrackPublished,i,n)}).on(x.TrackSubscribed,(i,r)=>{i.kind===U.Kind.Audio?(i.on(k.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(k.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===U.Kind.Video&&(i.on(k.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(k.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Q.TrackSubscribed,i,r,n)}).on(x.TrackUnpublished,i=>{this.emit(Q.TrackUnpublished,i,n)}).on(x.TrackUnsubscribed,(i,r)=>{this.emit(Q.TrackUnsubscribed,i,r,n)}).on(x.TrackMuted,i=>{this.emitWhenConnected(Q.TrackMuted,i,n)}).on(x.TrackUnmuted,i=>{this.emitWhenConnected(Q.TrackUnmuted,i,n)}).on(x.ParticipantMetadataChanged,i=>{this.emitWhenConnected(Q.ParticipantMetadataChanged,i,n)}).on(x.ParticipantNameChanged,i=>{this.emitWhenConnected(Q.ParticipantNameChanged,i,n)}).on(x.AttributesChanged,i=>{this.emitWhenConnected(Q.ParticipantAttributesChanged,i,n)}).on(x.ConnectionQualityChanged,i=>{this.emitWhenConnected(Q.ConnectionQualityChanged,i,n)}).on(x.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(Q.ParticipantPermissionsChanged,i,n)}).on(x.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(Q.TrackSubscriptionStatusChanged,i,r,n)}).on(x.TrackSubscriptionFailed,(i,r)=>{this.emit(Q.TrackSubscriptionFailed,i,n,r)}).on(x.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(Q.TrackSubscriptionPermissionChanged,i,r,n)}).on(x.Active,()=>{this.emitWhenConnected(Q.ParticipantActive,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,i)=>(n.push(...i.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&tv(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Te.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,mt.STATE_MISMATCH))):e=0},iC)}clearConnectionReconcile(){this.connectionReconcileInterval&&Te.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(Q.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(this.state===z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===z.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ar({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ue.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new LA({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Q.SignalConnected),this.emit(Q.Connected),this.setAndEmitConnectionState(z.Connected),i.video){const s=new Ia(U.Kind.Video,new mn({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO,name:"video-dummy"}),new Ir(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Md(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(x.LocalTrackPublished,s)}if(i.audio){const s=new Ia(U.Kind.Audio,new mn({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO}),new Fr(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(x.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let o=new LA({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:pn.ACTIVE,tracks:[],joinedAt:ue.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(r.video){const c=Md(160*((n=r.aspectRatios[s%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),u=new mn({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(r.audio){const c=sa(),u=new mn({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:pt.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(e!==Q.ActiveSpeakersChanged&&e!==Q.TranscriptionReceived){const r=vh(n).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}VA.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(A=>{A()});function vh(A){return A.map(e=>{if(e)return Array.isArray(e)?vh(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Et;(function(A){A[A.IDLE=0]="IDLE",A[A.RUNNING=1]="RUNNING",A[A.SKIPPED=2]="SKIPPED",A[A.SUCCESS=3]="SUCCESS",A[A.FAILED=4]="FAILED"})(Et||(Et={}));class gA extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Et.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new VA(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Et.IDLE)throw Error("check is running already");this.setStatus(Et.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!==Et.SKIPPED&&this.setStatus(this.isSuccess()?Et.SUCCESS:Et.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Et.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(Q.Reconnecting,()=>{t=!0}),this.room.once(Q.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(n)return;yield Je(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 rC extends gA{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new Qa(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(n.has(s))continue;n.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield r.write(c);yield r.close();const l=Date.now(),d=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d?.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const _a=1e4;class sC extends gA{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(_a/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(_a/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>m(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d?.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,_a)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class oC extends gA{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Zv();if(yield Gd(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class aC extends gA{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield zv();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,yield new Promise(i=>{n.onplay=()=>{setTimeout(()=>{var r,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(r=u.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(n,0,0);const g=h.getImageData(0,0,c.width,c.height).data;let p=!0;for(let B=0;B<g.length;B+=4)if(g[B]!==0||g[B+1]!==0||g[B+2]!==0){p=!1;break}p?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},n.play()}),n.remove()})}}class cC extends gA{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),o=()=>{n=!0};t.on(Q.SignalReconnecting,o).on(Q.Reconnecting,o).on(Q.Reconnected,()=>{i=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,n){if(!i||t.state!==z.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class uC extends gA{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t;const n=new fa,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,r=!0),c.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class lC extends gA{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(Q.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(dC(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),j.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 dC(A){const e=A.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 hC extends gA{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new fa;const r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===yl.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield i.close()})}}class Q_ extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Et.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!==Et.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};n.on("update",i);const r=yield n.run();return n.off("update",i),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(hC)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(lC)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(uC)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(cC)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(oC)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(aC)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(sC);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(rC)})}}const qe=Symbol.for("@ts-pattern/matcher"),Ch=Symbol.for("@ts-pattern/isVariadic"),Rr="@ts-pattern/anonymous-select-key",xa=A=>!!(A&&typeof A=="object"),Pr=A=>A&&!!A[qe],Qe=(A,e,t)=>{if(Pr(A)){const n=A[qe](),{matched:i,selections:r}=n.match(e);return i&&r&&Object.keys(r).forEach(s=>t(s,r[s])),i}if(xa(A)){if(!xa(e))return!1;if(Array.isArray(A)){if(!Array.isArray(e))return!1;let n=[],i=[],r=[];for(const s of A.keys()){const o=A[s];Pr(o)&&o[Ch]?r.push(o):r.length?i.push(o):n.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<n.length+i.length)return!1;const s=e.slice(0,n.length),o=i.length===0?[]:e.slice(-i.length),a=e.slice(n.length,i.length===0?1/0:-i.length);return n.every((c,u)=>Qe(c,s[u],t))&&i.every((c,u)=>Qe(c,o[u],t))&&(r.length===0||Qe(r[0],a,t))}return A.length===e.length&&A.every((s,o)=>Qe(s,e[o],t))}return Reflect.ownKeys(A).every(n=>{const i=A[n];return(n in e||Pr(r=i)&&r[qe]().matcherType==="optional")&&Qe(i,e[n],t);var r})}return Object.is(e,A)},At=A=>{var e,t,n;return xa(A)?Pr(A)?(e=(t=(n=A[qe]()).getSelectionKeys)==null?void 0:t.call(n))!=null?e:[]:Array.isArray(A)?ci(A,At):ci(Object.values(A),At):[]},ci=(A,e)=>A.reduce((t,n)=>t.concat(e(n)),[]);function fC(...A){if(A.length===1){const[e]=A;return t=>Qe(e,t,()=>{})}if(A.length===2){const[e,t]=A;return Qe(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${A.length}.`)}function Fe(A){return Object.assign(A,{optional:()=>Pa(A),and:e=>ae(A,e),or:e=>wh(A,e),select:e=>e===void 0?ui(A):ui(e,A)})}function Ra(A){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const n=[{value:Object.assign(e,{[Ch]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var i;return(i=n[t++])!=null?i:n.at(-1)}}}}))(A),{optional:()=>Ra(Pa(A)),select:e=>Ra(e===void 0?ui(A):ui(e,A))})}function Pa(A){return Fe({[qe]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return e===void 0?(At(A).forEach(i=>n(i,void 0)),{matched:!0,selections:t}):{matched:Qe(A,e,n),selections:t}},getSelectionKeys:()=>At(A),matcherType:"optional"})})}const gC=(A,e)=>{for(const t of A)if(!e(t))return!1;return!0},pC=(A,e)=>{for(const[t,n]of A.entries())if(!e(n,t))return!1;return!0};function ae(...A){return Fe({[qe]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return{matched:A.every(i=>Qe(i,e,n)),selections:t}},getSelectionKeys:()=>ci(A,At),matcherType:"and"})})}function wh(...A){return Fe({[qe]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return ci(A,At).forEach(i=>n(i,void 0)),{matched:A.some(i=>Qe(i,e,n)),selections:t}},getSelectionKeys:()=>ci(A,At),matcherType:"or"})})}function J(A){return{[qe]:()=>({match:e=>({matched:!!A(e)})})}}function ui(...A){const e=typeof A[0]=="string"?A[0]:void 0,t=A.length===2?A[1]:typeof A[0]=="string"?void 0:A[0];return Fe({[qe]:()=>({match:n=>{let i={[e??Rr]:n};return{matched:t===void 0||Qe(t,n,(r,s)=>{i[r]=s}),selections:i}},getSelectionKeys:()=>[e??Rr].concat(t===void 0?[]:At(t))})})}function Rt(A){return typeof A=="number"}function pA(A){return typeof A=="string"}function mA(A){return typeof A=="bigint"}const yh=Fe(J(function(A){return!0})),mC=yh,BA=A=>Object.assign(Fe(A),{startsWith:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&n.startsWith(t)))));var t},endsWith:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&n.endsWith(t)))));var t},minLength:e=>BA(ae(A,(t=>J(n=>pA(n)&&n.length>=t))(e))),length:e=>BA(ae(A,(t=>J(n=>pA(n)&&n.length===t))(e))),maxLength:e=>BA(ae(A,(t=>J(n=>pA(n)&&n.length<=t))(e))),includes:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&n.includes(t)))));var t},regex:e=>{return BA(ae(A,(t=e,J(n=>pA(n)&&!!n.match(t)))));var t}}),BC=BA(J(pA)),Pt=A=>Object.assign(Fe(A),{between:(e,t)=>Pt(ae(A,((n,i)=>J(r=>Rt(r)&&n<=r&&i>=r))(e,t))),lt:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n<t))(e))),gt:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n>t))(e))),lte:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n<=t))(e))),gte:e=>Pt(ae(A,(t=>J(n=>Rt(n)&&n>=t))(e))),int:()=>Pt(ae(A,J(e=>Rt(e)&&Number.isInteger(e)))),finite:()=>Pt(ae(A,J(e=>Rt(e)&&Number.isFinite(e)))),positive:()=>Pt(ae(A,J(e=>Rt(e)&&e>0))),negative:()=>Pt(ae(A,J(e=>Rt(e)&&e<0)))}),vC=Pt(J(Rt)),vA=A=>Object.assign(Fe(A),{between:(e,t)=>vA(ae(A,((n,i)=>J(r=>mA(r)&&n<=r&&i>=r))(e,t))),lt:e=>vA(ae(A,(t=>J(n=>mA(n)&&n<t))(e))),gt:e=>vA(ae(A,(t=>J(n=>mA(n)&&n>t))(e))),lte:e=>vA(ae(A,(t=>J(n=>mA(n)&&n<=t))(e))),gte:e=>vA(ae(A,(t=>J(n=>mA(n)&&n>=t))(e))),positive:()=>vA(ae(A,J(e=>mA(e)&&e>0))),negative:()=>vA(ae(A,J(e=>mA(e)&&e<0)))}),CC=vA(J(mA)),wC=Fe(J(function(A){return typeof A=="boolean"})),yC=Fe(J(function(A){return typeof A=="symbol"})),bC=Fe(J(function(A){return A==null})),EC=Fe(J(function(A){return A!=null}));var SC={__proto__:null,matcher:qe,optional:Pa,array:function(...A){return Ra({[qe]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(A.length===0)return{matched:!0};const t=A[0];let n={};if(e.length===0)return At(t).forEach(r=>{n[r]=[]}),{matched:!0,selections:n};const i=(r,s)=>{n[r]=(n[r]||[]).concat([s])};return{matched:e.every(r=>Qe(t,r,i)),selections:n}},getSelectionKeys:()=>A.length===0?[]:At(A[0])})})},set:function(...A){return Fe({[qe]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(A.length===0)return{matched:!0};const n=(r,s)=>{t[r]=(t[r]||[]).concat([s])},i=A[0];return{matched:gC(e,r=>Qe(i,r,n)),selections:t}},getSelectionKeys:()=>A.length===0?[]:At(A[0])})})},map:function(...A){return Fe({[qe]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const n=(o,a)=>{t[o]=(t[o]||[]).concat([a])};if(A.length===0)return{matched:!0};var i;if(A.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(i=A[0])==null?void 0:i.toString()}`);const[r,s]=A;return{matched:pC(e,(o,a)=>{const c=Qe(r,a,n),u=Qe(s,o,n);return c&&u}),selections:t}},getSelectionKeys:()=>A.length===0?[]:[...At(A[0]),...At(A[1])]})})},intersection:ae,union:wh,not:function(A){return Fe({[qe]:()=>({match:e=>({matched:!Qe(A,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:J,select:ui,any:yh,_:mC,string:BC,number:vC,bigint:CC,boolean:wC,symbol:yC,nullish:bC,nonNullable:EC,instanceOf:function(A){return Fe(J(function(e){return t=>t instanceof e}(A)))},shape:function(A){return Fe(J(fC(A)))}};class UC extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const Da={matched:!1,value:void 0};function li(A){return new TC(A,Da)}let TC=class Iu{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],n=[e[0]];let i;e.length===3&&typeof e[1]=="function"?i=e[1]:e.length>2&&n.push(...e.slice(1,e.length-1));let r=!1,s={};const o=(c,u)=>{r=!0,s[c]=u},a=!n.some(c=>Qe(c,this.input,o))||i&&!i(this.input)?Da:{matched:!0,value:t(r?Rr in s?s[Rr]:s:this.input,this.input)};return new Iu(this.input,a)}when(e,t){if(this.state.matched)return this;const n=!!e(this.input);return new Iu(this.input,n?{matched:!0,value:t(this.input,this.input)}:Da)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=QC){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function QC(A){throw new UC(A)}const FC=/\{[^{}]+\}/g;function kC(){return Math.random().toString(36).slice(2,11)}function IC(A){let{baseUrl:e="",Request:t=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:r,headers:s,...o}={...A};e=Uh(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=n,Request:f=t,headers:g,params:p={},parseAs:B="json",querySerializer:y,bodySerializer:b=r??xC,body:v,...C}=l||{};d&&(e=Uh(d));let w=typeof i=="function"?i:Sh(i);y&&(w=typeof y=="function"?y:Sh({...typeof i=="object"?i:{},...y}));const S=v===void 0?void 0:b(v),F=S===void 0||S instanceof FormData?{}:{"Content-Type":"application/json"},_={redirect:"follow",...o,...C,body:S,headers:PC(F,s,g,p.header)};let D,O,M=new t(RC(u,{baseUrl:e,params:p,querySerializer:w}),_);for(const G in C)G in M||(M[G]=C[G]);if(a.length){D=kC(),O=Object.freeze({baseUrl:e,fetch:h,parseAs:B,querySerializer:w,bodySerializer:b});for(const G of a)if(G&&typeof G=="object"&&typeof G.onRequest=="function"){const q=await G.onRequest({request:M,schemaPath:u,params:p,options:O,id:D});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");M=q}}}let K=await h(M);if(a.length)for(let G=a.length-1;G>=0;G--){const q=a[G];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const et=await q.onResponse({request:M,response:K,schemaPath:u,params:p,options:O,id:D});if(et){if(!(et instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");K=et}}}if(K.status===204||K.headers.get("Content-Length")==="0")return K.ok?{data:{},response:K}:{error:{},response:K};if(K.ok)return B==="stream"?{data:K.body,response:K}:{data:await K[B](),response:K};let Pe=await K.text();try{Pe=JSON.parse(Pe)}catch{}return{error:Pe,response:K}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function Dr(A,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${A}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function bh(A,e,t){if(!e||typeof e!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)n.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=n.join(",");switch(t.style){case"form":return`${A}=${s}`;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${A}[${s}]`:s;n.push(Dr(o,e[s],t))}const r=n.join(i);return t.style==="label"||t.style==="matrix"?`${i}${r}`:r}function Eh(A,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const r={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(r);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return`${A}=${s}`}}const n={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const r of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?r:encodeURIComponent(r)):i.push(Dr(A,r,t));return t.style==="label"||t.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Sh(A){return function(t){const n=[];if(t&&typeof t=="object")for(const i in t){const r=t[i];if(r!=null){if(Array.isArray(r)){if(r.length===0)continue;n.push(Eh(i,r,{style:"form",explode:!0,...A?.array,allowReserved:A?.allowReserved||!1}));continue}if(typeof r=="object"){n.push(bh(i,r,{style:"deepObject",explode:!0,...A?.object,allowReserved:A?.allowReserved||!1}));continue}n.push(Dr(i,r,A))}}return n.join("&")}}function _C(A,e){let t=A;for(const n of A.match(FC)??[]){let i=n.substring(1,n.length-1),r=!1,s="simple";if(i.endsWith("*")&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const o=e[i];if(Array.isArray(o)){t=t.replace(n,Eh(i,o,{style:s,explode:r}));continue}if(typeof o=="object"){t=t.replace(n,bh(i,o,{style:s,explode:r}));continue}if(s==="matrix"){t=t.replace(n,`;${Dr(i,o)}`);continue}t=t.replace(n,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function xC(A){return A instanceof FormData?A:JSON.stringify(A)}function RC(A,e){let t=`${e.baseUrl}${A}`;e.params?.path&&(t=_C(t,e.params.path));let n=e.querySerializer(e.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(t+=`?${n}`),t}function PC(...A){const e=new Headers;for(const t of A){if(!t||typeof t!="object")continue;const n=t instanceof Headers?t.entries():Object.entries(t);for(const[i,r]of n)if(r===null)e.delete(i);else if(Array.isArray(r))for(const s of r)e.append(i,s);else r!==void 0&&e.set(i,r)}return e}function Uh(A){return A.endsWith("/")?A.substring(0,A.length-1):A}class Th{constructor(e){this.client=IC({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}async getAuthUrl(e){return await this.client.GET("/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/logout")}async getCurrentUser(){return await this.client.GET("/me")}async createPresignedUploadUrl(e){return await this.client.POST("/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/onboardees")}async getOnboardeeWhitelistedDomains(e){return await this.client.GET("/onboardees/{id}/whitelisted-domains",{params:{path:{id:e}}})}async listPlans(){return await this.client.GET("/plans")}async createPlan(e){return await this.client.POST("/plans",{body:e})}async getPlan(e){return await this.client.GET("/plans/{id}",{params:{path:{id:e}}})}async replacePlan(e,t){return await this.client.PUT("/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/plans/{id}",{params:{path:{id:e}},body:t})}async listSessions(e){return await this.client.GET("/sessions",{params:{query:e?{token:e}:{}}})}async createSession(e){return await this.client.POST("/sessions",{body:e})}async getSession(e){return await this.client.GET("/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,t){return await this.client.GET("/sessions/{id}/start-session",{params:{path:{id:e},query:t?{token:t}:{}}})}async getSessionRecording(e){return await this.client.GET("/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/sessions/{id}/product-url",{params:{path:{id:e}}})}async getJoinToken(e,{skipIntro:t}={}){return await this.client.GET("/join-token",{params:{query:{token:e,...t&&{skip_intro:"true"}}}})}getClient(){return this.client}}const DC="https://app.coragents.ai/api";var H;(function(A){A.READY="ready",A.ERROR="error",A.PAUSED="paused",A.LOADING="loading",A.THINKING="thinking",A.RESEARCHING="researching",A.AGENT_SPEAKING="agent_speaking",A.USER_SPEAKING="user_speaking",A.AWAITING_USER_INPUT="awaiting_user_input"})(H||(H={}));class LC{constructor({sessionId:e,apiBaseUrl:t}){this.currentState=H.READY,this.livekitState="speaking",this.assistantAudioContext=null,this.userAudioContext=null,this._assistantAudioTimer=null,this._userAudioTimer=null,this.sessionId=e,this.apiBaseUrl=t||DC,this.client=new Th({baseUrl:this.apiBaseUrl}),this.emitter=new Rm}emit(e,t){this.emitter.emit(e,t)}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setupRoomEventListeners(){this.room&&(this.room.on(Q.LocalTrackUnpublished,e=>{e.source===U.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(Q.Disconnected,()=>{this.disconnect()}),this.room.on(Q.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(Q.TrackSubscribed,(e,t,n)=>{if(e.kind==="audio"&&e.attach(),e.source===U.Source.Microphone&&n.identity.includes("agent-")){const i=e.mediaStream;if(!i){console.error("No media stream available for assistant track");return}const r=new AudioContext,s=r.createAnalyser();r.createMediaStreamSource(i).connect(s),s.fftSize=2048;const a=new Uint8Array(s.frequencyBinCount);this.analyzeAudio(s,a,"ASSISTANT"),this.assistantAudioContext=r}}),this.room.on(Q.ParticipantAttributesChanged,e=>{if(!e["lk.agent.state"]||this.currentState===H.RESEARCHING||this.currentState===H.PAUSED)return;const t=e["lk.agent.state"],n=li(t).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).with("thinking",()=>H.THINKING).otherwise(()=>{});n&&(this.setState(n),this.livekitState=t)}),this.room.on(Q.DataReceived,async e=>{try{const t=JSON.parse(new TextDecoder().decode(e)),n=t.status||t.request;li(n).with("using_tool",()=>{this.currentState=H.RESEARCHING,this.emitter.emit("stateChanged",H.RESEARCHING)}).with("using_tool_ended",()=>{this.currentState=H.AGENT_SPEAKING,this.emitter.emit("stateChanged",H.AGENT_SPEAKING)}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML")}).with("fill",()=>{this.emitter.emit("fill",t.value)}).otherwise(()=>{console.warn("Unknown data received:",t)})}catch(t){console.error("Error parsing data:",t)}}),this.room.localParticipant.registerRpcMethod("screen_capture",async e=>(this.emitter.emit("screenCaptureRequested"),new Promise(t=>{this.emitter.once("screenCaptureComplete",async n=>{if(n==="error"){t("error");return}try{await this.room.localParticipant.sendFile(new File([n],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),t("ok")}catch{t("error")}})}))))}async connect(){if(!this.sessionId){console.error("No session ID found"),this.emitter.emit("error",new Error("No session ID provided"));return}try{await this.requestMicrophone(),this.room=new VA({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=await this.client.getJoinToken(this.sessionId,{skipIntro:!0});if(await this.room.connect(e.data.url,e.data.token),this.microphoneStream){const t=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(t,{name:"microphone",source:U.Source.Microphone})}return{url:e.data.url,token:e.data.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",e instanceof Error?e:new Error(String(e))),e}}async disconnect(){this.room&&(this.room.disconnect(!0),this.room.removeAllListeners(),this.room=void 0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(e=>e.stop()),this._userAudioTimer&&(window.clearTimeout(this._userAudioTimer),this._userAudioTimer=null),this._assistantAudioTimer&&(window.clearTimeout(this._assistantAudioTimer),this._assistantAudioTimer=null),await this.userAudioContext?.close().catch(()=>{}),this.userAudioContext=null,await this.assistantAudioContext?.close().catch(()=>{}),this.assistantAudioContext=null,this.setState(H.READY),this.emitter.emit("disconnected")}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",e))}getCurrentState(){return this.currentState}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const n=t.createAnalyser(),i=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,i.connect(r),r.connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){if(!this.room){console.warn("[obi] shareScreen called while not connected");return}this.emitter.emit("preScreenShare");try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}pauseRecording(){this.room&&(this.setState(H.PAUSED),this.room.localParticipant.getTrackPublications().forEach(e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach(t=>t.enabled=!1)}),this.microphoneStream?.getTracks().forEach(e=>e.enabled=!1),this.screenStream?.track?.mute())}resumeRecording(){if(!this.room)return;const e=li(this.livekitState).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).otherwise(()=>H.THINKING);this.setState(e),this.room.localParticipant.getTrackPublications().forEach(t=>{t.handleUnmuted(),t.track?.mediaStream?.getTracks().forEach(n=>n.enabled=!0)}),this.microphoneStream?.getTracks().forEach(t=>t.enabled=!0),this.screenStream?.track?.unmute()}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,n){if(n==="USER"&&this.currentState===H.USER_SPEAKING||n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING){e.getByteFrequencyData(t);const i=t.reduce((o,a)=>o+a,0)/t.length,r=Math.max(.01,Math.min(1,i/128));let s;n==="USER"&&this.currentState===H.USER_SPEAKING?s="USER":n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING&&(s="ASSISTANT"),s&&this.emitter.emit("volume",{speaker:s,spectrum:Array.from(t),volume:r})}n==="USER"?this._userAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200):this._assistantAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},n=JSON.stringify(t),r=new TextEncoder().encode(n);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",t instanceof Error?t:new Error(String(t)))}}async reconnect(e,t,n){try{if(!e||!t)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",new Error("Missing room URL or token for reconnection")),!1;if(await this.requestMicrophone(),this.room=new VA({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,t),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:U.Source.Microphone})}return this.setState(n),n===H.PAUSED&&this.pauseRecording(),!0}catch(i){return console.error("Failed to reconnect to room:",i),this.disconnect(),this.emitter.emit("error",i instanceof Error?i:new Error(String(i))),!1}}}/**
|
|
43
43
|
* @license
|
|
44
44
|
* Copyright 2019 Google LLC
|
|
45
45
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -107,21 +107,21 @@ a=extmap-allow-mixed`)!==-1){const r=i.sdp.split(`
|
|
|
107
107
|
content: "" !important;
|
|
108
108
|
display: none !important;
|
|
109
109
|
}`,RU=function(A){PU(A,".".concat(Lc).concat(_U).concat(Dg,`
|
|
110
|
-
.`).concat(Oc).concat(xU).concat(Dg))},PU=function(A,e){var t=A.ownerDocument;if(t){var n=t.createElement("style");n.textContent=e,A.appendChild(n)}},DU=function(A,e){var t,n=e.createElement("base");n.href=e.baseURI;var i=A.getElementsByTagName("head").item(0);i?.insertBefore(n,(t=i?.firstChild)!==null&&t!==void 0?t:null)},Hc=function(){function A(){}return A.getOrigin=function(e){var t=A._link;return t?(t.href=e,t.href=t.href,t.protocol+t.hostname+t.port):"about:blank"},A.isSameOrigin=function(e){return A.getOrigin(e)===A._origin},A.setContext=function(e){A._link=e.document.createElement("a"),A._origin=A.getOrigin(e.location.href)},A._origin="about:blank",A}(),LU=function(){function A(e,t){this.context=e,this._options=t,this._cache={}}return A.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)||(Nc(e)||NU(e))&&(this._cache[e]=this.loadImage(e)).catch(function(){}),t},A.prototype.match=function(e){return this._cache[e]},A.prototype.loadImage=function(e){return Me(this,void 0,void 0,function(){var t,n,i,r,s,o=this;return Le(this,function(a){switch(a.label){case 0:return typeof this._options.customIsSameOrigin!="function"?[3,2]:[4,this._options.customIsSameOrigin(e,Hc.isSameOrigin)];case 1:return n=a.sent(),[3,3];case 2:n=Hc.isSameOrigin(e),a.label=3;case 3:return t=n,i=!Mc(e)&&this._options.useCORS===!0&&_e.SUPPORT_CORS_IMAGES&&!t,r=!Mc(e)&&!t&&!Nc(e)&&typeof this._options.proxy=="string"&&_e.SUPPORT_CORS_XHR&&!i,!t&&this._options.allowTaint===!1&&!Mc(e)&&!Nc(e)&&!r&&!i?[2]:(s=e,r?[4,this.proxy(s)]:[3,5]);case 4:s=a.sent(),a.label=5;case 5:return this.context.logger.debug("Added image ".concat(e.substring(0,256))),[4,new Promise(function(c,u){var l=new Image;l.onload=function(){return c(l)},l.onerror=u,(KU(s)||i)&&(l.crossOrigin="anonymous"),l.src=s,l.complete===!0&&setTimeout(function(){return c(l)},500),o._options.imageTimeout>0&&setTimeout(function(){return u("Timed out (".concat(o._options.imageTimeout,"ms) loading image"))},o._options.imageTimeout)})];case 6:return[2,a.sent()]}})})},A.prototype.has=function(e){return typeof this._cache[e]<"u"},A.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},A.prototype.proxy=function(e){var t=this,n=this._options.proxy;if(!n)throw new Error("No proxy defined");var i=e.substring(0,256);return new Promise(function(r,s){var o=_e.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(a.status===200)if(o==="text")r(a.response);else{var l=new FileReader;l.addEventListener("load",function(){return r(l.result)},!1),l.addEventListener("error",function(d){return s(d)},!1),l.readAsDataURL(a.response)}else s("Failed to proxy resource ".concat(i," with status code ").concat(a.status))},a.onerror=s;var c=n.indexOf("?")>-1?"&":"?";if(a.open("GET","".concat(n).concat(c,"url=").concat(encodeURIComponent(e),"&responseType=").concat(o)),o!=="text"&&a instanceof XMLHttpRequest&&(a.responseType=o),t._options.imageTimeout){var u=t._options.imageTimeout;a.timeout=u,a.ontimeout=function(){return s("Timed out (".concat(u,"ms) proxying ").concat(i))}}a.send()})},A}(),OU=/^data:image\/svg\+xml/i,HU=/^data:image\/.*;base64,/i,MU=/^data:image\/.*/i,NU=function(A){return _e.SUPPORT_SVG_DRAWING||!GU(A)},Mc=function(A){return MU.test(A)},KU=function(A){return HU.test(A)},Nc=function(A){return A.substr(0,4)==="blob"},GU=function(A){return A.substr(-3).toLowerCase()==="svg"||OU.test(A)},R=function(){function A(e,t){this.type=0,this.x=e,this.y=t}return A.prototype.add=function(e,t){return new A(this.x+e,this.y+t)},A}(),Pn=function(A,e,t){return new R(A.x+(e.x-A.x)*t,A.y+(e.y-A.y)*t)},xs=function(){function A(e,t,n,i){this.type=1,this.start=e,this.startControl=t,this.endControl=n,this.end=i}return A.prototype.subdivide=function(e,t){var n=Pn(this.start,this.startControl,e),i=Pn(this.startControl,this.endControl,e),r=Pn(this.endControl,this.end,e),s=Pn(n,i,e),o=Pn(i,r,e),a=Pn(s,o,e);return t?new A(this.start,n,s,a):new A(a,o,r,this.end)},A.prototype.add=function(e,t){return new A(this.start.add(e,t),this.startControl.add(e,t),this.endControl.add(e,t),this.end.add(e,t))},A.prototype.reverse=function(){return new A(this.end,this.endControl,this.startControl,this.start)},A}(),ut=function(A){return A.type===1},VU=function(){function A(e){var t=e.styles,n=e.bounds,i=Ui(t.borderTopLeftRadius,n.width,n.height),r=i[0],s=i[1],o=Ui(t.borderTopRightRadius,n.width,n.height),a=o[0],c=o[1],u=Ui(t.borderBottomRightRadius,n.width,n.height),l=u[0],d=u[1],h=Ui(t.borderBottomLeftRadius,n.width,n.height),f=h[0],g=h[1],p=[];p.push((r+a)/n.width),p.push((f+l)/n.width),p.push((s+g)/n.height),p.push((c+d)/n.height);var B=Math.max.apply(Math,p);B>1&&(r/=B,s/=B,a/=B,c/=B,l/=B,d/=B,f/=B,g/=B);var y=n.width-a,b=n.height-d,v=n.width-l,C=n.height-g,w=t.borderTopWidth,S=t.borderRightWidth,F=t.borderBottomWidth,_=t.borderLeftWidth,D=ne(t.paddingTop,e.bounds.width),O=ne(t.paddingRight,e.bounds.width),M=ne(t.paddingBottom,e.bounds.width),K=ne(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||s>0?le(n.left+_/3,n.top+w/3,r-_/3,s-w/3,te.TOP_LEFT):new R(n.left+_/3,n.top+w/3),this.topRightBorderDoubleOuterBox=r>0||s>0?le(n.left+y,n.top+w/3,a-S/3,c-w/3,te.TOP_RIGHT):new R(n.left+n.width-S/3,n.top+w/3),this.bottomRightBorderDoubleOuterBox=l>0||d>0?le(n.left+v,n.top+b,l-S/3,d-F/3,te.BOTTOM_RIGHT):new R(n.left+n.width-S/3,n.top+n.height-F/3),this.bottomLeftBorderDoubleOuterBox=f>0||g>0?le(n.left+_/3,n.top+C,f-_/3,g-F/3,te.BOTTOM_LEFT):new R(n.left+_/3,n.top+n.height-F/3),this.topLeftBorderDoubleInnerBox=r>0||s>0?le(n.left+_*2/3,n.top+w*2/3,r-_*2/3,s-w*2/3,te.TOP_LEFT):new R(n.left+_*2/3,n.top+w*2/3),this.topRightBorderDoubleInnerBox=r>0||s>0?le(n.left+y,n.top+w*2/3,a-S*2/3,c-w*2/3,te.TOP_RIGHT):new R(n.left+n.width-S*2/3,n.top+w*2/3),this.bottomRightBorderDoubleInnerBox=l>0||d>0?le(n.left+v,n.top+b,l-S*2/3,d-F*2/3,te.BOTTOM_RIGHT):new R(n.left+n.width-S*2/3,n.top+n.height-F*2/3),this.bottomLeftBorderDoubleInnerBox=f>0||g>0?le(n.left+_*2/3,n.top+C,f-_*2/3,g-F*2/3,te.BOTTOM_LEFT):new R(n.left+_*2/3,n.top+n.height-F*2/3),this.topLeftBorderStroke=r>0||s>0?le(n.left+_/2,n.top+w/2,r-_/2,s-w/2,te.TOP_LEFT):new R(n.left+_/2,n.top+w/2),this.topRightBorderStroke=r>0||s>0?le(n.left+y,n.top+w/2,a-S/2,c-w/2,te.TOP_RIGHT):new R(n.left+n.width-S/2,n.top+w/2),this.bottomRightBorderStroke=l>0||d>0?le(n.left+v,n.top+b,l-S/2,d-F/2,te.BOTTOM_RIGHT):new R(n.left+n.width-S/2,n.top+n.height-F/2),this.bottomLeftBorderStroke=f>0||g>0?le(n.left+_/2,n.top+C,f-_/2,g-F/2,te.BOTTOM_LEFT):new R(n.left+_/2,n.top+n.height-F/2),this.topLeftBorderBox=r>0||s>0?le(n.left,n.top,r,s,te.TOP_LEFT):new R(n.left,n.top),this.topRightBorderBox=a>0||c>0?le(n.left+y,n.top,a,c,te.TOP_RIGHT):new R(n.left+n.width,n.top),this.bottomRightBorderBox=l>0||d>0?le(n.left+v,n.top+b,l,d,te.BOTTOM_RIGHT):new R(n.left+n.width,n.top+n.height),this.bottomLeftBorderBox=f>0||g>0?le(n.left,n.top+C,f,g,te.BOTTOM_LEFT):new R(n.left,n.top+n.height),this.topLeftPaddingBox=r>0||s>0?le(n.left+_,n.top+w,Math.max(0,r-_),Math.max(0,s-w),te.TOP_LEFT):new R(n.left+_,n.top+w),this.topRightPaddingBox=a>0||c>0?le(n.left+Math.min(y,n.width-S),n.top+w,y>n.width+S?0:Math.max(0,a-S),Math.max(0,c-w),te.TOP_RIGHT):new R(n.left+n.width-S,n.top+w),this.bottomRightPaddingBox=l>0||d>0?le(n.left+Math.min(v,n.width-_),n.top+Math.min(b,n.height-F),Math.max(0,l-S),Math.max(0,d-F),te.BOTTOM_RIGHT):new R(n.left+n.width-S,n.top+n.height-F),this.bottomLeftPaddingBox=f>0||g>0?le(n.left+_,n.top+Math.min(C,n.height-F),Math.max(0,f-_),Math.max(0,g-F),te.BOTTOM_LEFT):new R(n.left+_,n.top+n.height-F),this.topLeftContentBox=r>0||s>0?le(n.left+_+K,n.top+w+D,Math.max(0,r-(_+K)),Math.max(0,s-(w+D)),te.TOP_LEFT):new R(n.left+_+K,n.top+w+D),this.topRightContentBox=a>0||c>0?le(n.left+Math.min(y,n.width+_+K),n.top+w+D,y>n.width+_+K?0:a-_+K,c-(w+D),te.TOP_RIGHT):new R(n.left+n.width-(S+O),n.top+w+D),this.bottomRightContentBox=l>0||d>0?le(n.left+Math.min(v,n.width-(_+K)),n.top+Math.min(b,n.height+w+D),Math.max(0,l-(S+O)),d-(F+M),te.BOTTOM_RIGHT):new R(n.left+n.width-(S+O),n.top+n.height-(F+M)),this.bottomLeftContentBox=f>0||g>0?le(n.left+_+K,n.top+C,Math.max(0,f-(_+K)),g-(F+M),te.BOTTOM_LEFT):new R(n.left+_+K,n.top+n.height-(F+M))}return A}(),te;(function(A){A[A.TOP_LEFT=0]="TOP_LEFT",A[A.TOP_RIGHT=1]="TOP_RIGHT",A[A.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",A[A.BOTTOM_LEFT=3]="BOTTOM_LEFT"})(te||(te={}));var le=function(A,e,t,n,i){var r=4*((Math.sqrt(2)-1)/3),s=t*r,o=n*r,a=A+t,c=e+n;switch(i){case te.TOP_LEFT:return new xs(new R(A,c),new R(A,c-o),new R(a-s,e),new R(a,e));case te.TOP_RIGHT:return new xs(new R(A,e),new R(A+s,e),new R(a,c-o),new R(a,c));case te.BOTTOM_RIGHT:return new xs(new R(a,e),new R(a,e+o),new R(A+s,c),new R(A,c));case te.BOTTOM_LEFT:default:return new xs(new R(a,c),new R(a-s,c),new R(A,e+o),new R(A,e))}},Rs=function(A){return[A.topLeftBorderBox,A.topRightBorderBox,A.bottomRightBorderBox,A.bottomLeftBorderBox]},jU=function(A){return[A.topLeftContentBox,A.topRightContentBox,A.bottomRightContentBox,A.bottomLeftContentBox]},Ps=function(A){return[A.topLeftPaddingBox,A.topRightPaddingBox,A.bottomRightPaddingBox,A.bottomLeftPaddingBox]},$U=function(){function A(e,t,n){this.offsetX=e,this.offsetY=t,this.matrix=n,this.type=0,this.target=6}return A}(),Ds=function(){function A(e,t){this.path=e,this.target=t,this.type=1}return A}(),WU=function(){function A(e){this.opacity=e,this.type=2,this.target=6}return A}(),JU=function(A){return A.type===0},Lg=function(A){return A.type===1},XU=function(A){return A.type===2},Og=function(A,e){return A.length===e.length?A.some(function(t,n){return t===e[n]}):!1},qU=function(A,e,t,n,i){return A.map(function(r,s){switch(s){case 0:return r.add(e,t);case 1:return r.add(e+n,t);case 2:return r.add(e+n,t+i);case 3:return r.add(e,t+i)}return r})},Hg=function(){function A(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]}return A}(),Mg=function(){function A(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new VU(this.container),this.container.styles.opacity<1&&this.effects.push(new WU(this.container.styles.opacity)),this.container.styles.transform!==null){var n=this.container.bounds.left+this.container.styles.transformOrigin[0].number,i=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new $U(n,i,r))}if(this.container.styles.overflowX!==0){var s=Rs(this.curves),o=Ps(this.curves);Og(s,o)?this.effects.push(new Ds(s,6)):(this.effects.push(new Ds(s,2)),this.effects.push(new Ds(o,4)))}}return A.prototype.getEffects=function(e){for(var t=[2,3].indexOf(this.container.styles.position)===-1,n=this.parent,i=this.effects.slice(0);n;){var r=n.effects.filter(function(a){return!Lg(a)});if(t||n.container.styles.position!==0||!n.parent){if(t=[2,3].indexOf(n.container.styles.position)===-1,n.container.styles.overflowX!==0){var s=Rs(n.curves),o=Ps(n.curves);Og(s,o)||i.unshift(new Ds(o,6))}i.unshift.apply(i,r)}else i.unshift.apply(i,r);n=n.parent}return i.filter(function(a){return be(a.target,e)})},A}(),Kc=function(A,e,t,n){A.container.elements.forEach(function(i){var r=be(i.flags,4),s=be(i.flags,2),o=new Mg(i,A);be(i.styles.display,2048)&&n.push(o);var a=be(i.flags,8)?[]:n;if(r||s){var c=r||i.styles.isPositioned()?t:e,u=new Hg(o);if(i.styles.isPositioned()||i.styles.opacity<1||i.styles.isTransformed()){var l=i.styles.zIndex.order;if(l<0){var d=0;c.negativeZIndex.some(function(f,g){return l>f.element.container.styles.zIndex.order?(d=g,!1):d>0}),c.negativeZIndex.splice(d,0,u)}else if(l>0){var h=0;c.positiveZIndex.some(function(f,g){return l>=f.element.container.styles.zIndex.order?(h=g+1,!1):h>0}),c.positiveZIndex.splice(h,0,u)}else c.zeroOrAutoZIndexOrTransformedOrOpacity.push(u)}else i.styles.isFloating()?c.nonPositionedFloats.push(u):c.nonPositionedInlineLevel.push(u);Kc(o,u,r?u:t,a)}else i.styles.isInlineLevel()?e.inlineLevel.push(o):e.nonInlineLevel.push(o),Kc(o,e,t,a);be(i.flags,8)&&Ng(i,a)})},Ng=function(A,e){for(var t=A instanceof kc?A.start:1,n=A instanceof kc?A.reversed:!1,i=0;i<e.length;i++){var r=e[i];r.container instanceof hg&&typeof r.container.value=="number"&&r.container.value!==0&&(t=r.container.value),r.listValue=_i(t,r.container.styles.listStyleType,!0),t+=n?-1:1}},YU=function(A){var e=new Mg(A,null),t=new Hg(e),n=[];return Kc(e,t,t,n),Ng(e.container,n),t},Kg=function(A,e){switch(e){case 0:return lt(A.topLeftBorderBox,A.topLeftPaddingBox,A.topRightBorderBox,A.topRightPaddingBox);case 1:return lt(A.topRightBorderBox,A.topRightPaddingBox,A.bottomRightBorderBox,A.bottomRightPaddingBox);case 2:return lt(A.bottomRightBorderBox,A.bottomRightPaddingBox,A.bottomLeftBorderBox,A.bottomLeftPaddingBox);case 3:default:return lt(A.bottomLeftBorderBox,A.bottomLeftPaddingBox,A.topLeftBorderBox,A.topLeftPaddingBox)}},zU=function(A,e){switch(e){case 0:return lt(A.topLeftBorderBox,A.topLeftBorderDoubleOuterBox,A.topRightBorderBox,A.topRightBorderDoubleOuterBox);case 1:return lt(A.topRightBorderBox,A.topRightBorderDoubleOuterBox,A.bottomRightBorderBox,A.bottomRightBorderDoubleOuterBox);case 2:return lt(A.bottomRightBorderBox,A.bottomRightBorderDoubleOuterBox,A.bottomLeftBorderBox,A.bottomLeftBorderDoubleOuterBox);case 3:default:return lt(A.bottomLeftBorderBox,A.bottomLeftBorderDoubleOuterBox,A.topLeftBorderBox,A.topLeftBorderDoubleOuterBox)}},ZU=function(A,e){switch(e){case 0:return lt(A.topLeftBorderDoubleInnerBox,A.topLeftPaddingBox,A.topRightBorderDoubleInnerBox,A.topRightPaddingBox);case 1:return lt(A.topRightBorderDoubleInnerBox,A.topRightPaddingBox,A.bottomRightBorderDoubleInnerBox,A.bottomRightPaddingBox);case 2:return lt(A.bottomRightBorderDoubleInnerBox,A.bottomRightPaddingBox,A.bottomLeftBorderDoubleInnerBox,A.bottomLeftPaddingBox);case 3:default:return lt(A.bottomLeftBorderDoubleInnerBox,A.bottomLeftPaddingBox,A.topLeftBorderDoubleInnerBox,A.topLeftPaddingBox)}},eT=function(A,e){switch(e){case 0:return Ls(A.topLeftBorderStroke,A.topRightBorderStroke);case 1:return Ls(A.topRightBorderStroke,A.bottomRightBorderStroke);case 2:return Ls(A.bottomRightBorderStroke,A.bottomLeftBorderStroke);case 3:default:return Ls(A.bottomLeftBorderStroke,A.topLeftBorderStroke)}},Ls=function(A,e){var t=[];return ut(A)?t.push(A.subdivide(.5,!1)):t.push(A),ut(e)?t.push(e.subdivide(.5,!0)):t.push(e),t},lt=function(A,e,t,n){var i=[];return ut(A)?i.push(A.subdivide(.5,!1)):i.push(A),ut(t)?i.push(t.subdivide(.5,!0)):i.push(t),ut(n)?i.push(n.subdivide(.5,!0).reverse()):i.push(n),ut(e)?i.push(e.subdivide(.5,!1).reverse()):i.push(e),i},Gg=function(A){var e=A.bounds,t=A.styles;return e.add(t.borderLeftWidth,t.borderTopWidth,-(t.borderRightWidth+t.borderLeftWidth),-(t.borderTopWidth+t.borderBottomWidth))},Os=function(A){var e=A.styles,t=A.bounds,n=ne(e.paddingLeft,t.width),i=ne(e.paddingRight,t.width),r=ne(e.paddingTop,t.width),s=ne(e.paddingBottom,t.width);return t.add(n+e.borderLeftWidth,r+e.borderTopWidth,-(e.borderRightWidth+e.borderLeftWidth+n+i),-(e.borderTopWidth+e.borderBottomWidth+r+s))},tT=function(A,e){return A===0?e.bounds:A===2?Os(e):Gg(e)},AT=function(A,e){return A===0?e.bounds:A===2?Os(e):Gg(e)},Gc=function(A,e,t){var n=tT(Ln(A.styles.backgroundOrigin,e),A),i=AT(Ln(A.styles.backgroundClip,e),A),r=nT(Ln(A.styles.backgroundSize,e),t,n),s=r[0],o=r[1],a=Ui(Ln(A.styles.backgroundPosition,e),n.width-s,n.height-o),c=iT(Ln(A.styles.backgroundRepeat,e),a,r,n,i),u=Math.round(n.left+a[0]),l=Math.round(n.top+a[1]);return s=Math.max(1,s),o=Math.max(1,o),[c,u,l,s,o]},Dn=function(A){return $(A)&&A.value===In.AUTO},Hs=function(A){return typeof A=="number"},nT=function(A,e,t){var n=e[0],i=e[1],r=e[2],s=A[0],o=A[1];if(!s)return[0,0];if(ce(s)&&o&&ce(o))return[ne(s,t.width),ne(o,t.height)];var a=Hs(r);if($(s)&&(s.value===In.CONTAIN||s.value===In.COVER)){if(Hs(r)){var c=t.width/t.height;return c<r!=(s.value===In.COVER)?[t.width,t.width/r]:[t.height*r,t.height]}return[t.width,t.height]}var u=Hs(n),l=Hs(i),d=u||l;if(Dn(s)&&(!o||Dn(o))){if(u&&l)return[n,i];if(!a&&!d)return[t.width,t.height];if(d&&a){var h=u?n:i*r,f=l?i:n/r;return[h,f]}var g=u?n:t.width,p=l?i:t.height;return[g,p]}if(a){var B=0,y=0;return ce(s)?B=ne(s,t.width):ce(o)&&(y=ne(o,t.height)),Dn(s)?B=y*r:(!o||Dn(o))&&(y=B/r),[B,y]}var b=null,v=null;if(ce(s)?b=ne(s,t.width):o&&ce(o)&&(v=ne(o,t.height)),b!==null&&(!o||Dn(o))&&(v=u&&l?b/n*i:t.height),v!==null&&Dn(s)&&(b=u&&l?v/i*n:t.width),b!==null&&v!==null)return[b,v];throw new Error("Unable to calculate background-size for element")},Ln=function(A,e){var t=A[e];return typeof t>"u"?A[0]:t},iT=function(A,e,t,n,i){var r=e[0],s=e[1],o=t[0],a=t[1];switch(A){case 2:return[new R(Math.round(n.left),Math.round(n.top+s)),new R(Math.round(n.left+n.width),Math.round(n.top+s)),new R(Math.round(n.left+n.width),Math.round(a+n.top+s)),new R(Math.round(n.left),Math.round(a+n.top+s))];case 3:return[new R(Math.round(n.left+r),Math.round(n.top)),new R(Math.round(n.left+r+o),Math.round(n.top)),new R(Math.round(n.left+r+o),Math.round(n.height+n.top)),new R(Math.round(n.left+r),Math.round(n.height+n.top))];case 1:return[new R(Math.round(n.left+r),Math.round(n.top+s)),new R(Math.round(n.left+r+o),Math.round(n.top+s)),new R(Math.round(n.left+r+o),Math.round(n.top+s+a)),new R(Math.round(n.left+r),Math.round(n.top+s+a))];default:return[new R(Math.round(i.left),Math.round(i.top)),new R(Math.round(i.left+i.width),Math.round(i.top)),new R(Math.round(i.left+i.width),Math.round(i.height+i.top)),new R(Math.round(i.left),Math.round(i.height+i.top))]}},rT="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",Vg="Hidden Text",sT=function(){function A(e){this._data={},this._document=e}return A.prototype.parseMetrics=function(e,t){var n=this._document.createElement("div"),i=this._document.createElement("img"),r=this._document.createElement("span"),s=this._document.body;n.style.visibility="hidden",n.style.fontFamily=e,n.style.fontSize=t,n.style.margin="0",n.style.padding="0",n.style.whiteSpace="nowrap",s.appendChild(n),i.src=rT,i.width=1,i.height=1,i.style.margin="0",i.style.padding="0",i.style.verticalAlign="baseline",r.style.fontFamily=e,r.style.fontSize=t,r.style.margin="0",r.style.padding="0",r.appendChild(this._document.createTextNode(Vg)),n.appendChild(r),n.appendChild(i);var o=i.offsetTop-r.offsetTop+2;n.removeChild(r),n.appendChild(this._document.createTextNode(Vg)),n.style.lineHeight="normal",i.style.verticalAlign="super";var a=i.offsetTop-n.offsetTop+2;return s.removeChild(n),{baseline:o,middle:a}},A.prototype.getMetrics=function(e,t){var n="".concat(e," ").concat(t);return typeof this._data[n]>"u"&&(this._data[n]=this.parseMetrics(e,t)),this._data[n]},A}(),jg=function(){function A(e,t){this.context=e,this.options=t}return A}(),oT=1e4,aT=function(A){St(e,A);function e(t,n){var i=A.call(this,t,n)||this;return i._activeEffects=[],i.canvas=n.canvas?n.canvas:document.createElement("canvas"),i.ctx=i.canvas.getContext("2d"),n.canvas||(i.canvas.width=Math.floor(n.width*n.scale),i.canvas.height=Math.floor(n.height*n.scale),i.canvas.style.width="".concat(n.width,"px"),i.canvas.style.height="".concat(n.height,"px")),i.fontMetrics=new sT(document),i.ctx.scale(i.options.scale,i.options.scale),i.ctx.translate(-n.x,-n.y),i.ctx.textBaseline="bottom",i._activeEffects=[],i.context.logger.debug("Canvas renderer initialized (".concat(n.width,"x").concat(n.height,") with scale ").concat(n.scale)),i}return e.prototype.applyEffects=function(t){for(var n=this;this._activeEffects.length;)this.popEffect();t.forEach(function(i){return n.applyEffect(i)})},e.prototype.applyEffect=function(t){this.ctx.save(),XU(t)&&(this.ctx.globalAlpha=t.opacity),JU(t)&&(this.ctx.translate(t.offsetX,t.offsetY),this.ctx.transform(t.matrix[0],t.matrix[1],t.matrix[2],t.matrix[3],t.matrix[4],t.matrix[5]),this.ctx.translate(-t.offsetX,-t.offsetY)),Lg(t)&&(this.path(t.path),this.ctx.clip()),this._activeEffects.push(t)},e.prototype.popEffect=function(){this._activeEffects.pop(),this.ctx.restore()},e.prototype.renderStack=function(t){return Me(this,void 0,void 0,function(){var n;return Le(this,function(i){switch(i.label){case 0:return n=t.element.container.styles,n.isVisible()?[4,this.renderStackContent(t)]:[3,2];case 1:i.sent(),i.label=2;case 2:return[2]}})})},e.prototype.renderNode=function(t){return Me(this,void 0,void 0,function(){return Le(this,function(n){switch(n.label){case 0:if(be(t.container.flags,16))debugger;return t.container.styles.isVisible()?[4,this.renderNodeBackgroundAndBorders(t)]:[3,3];case 1:return n.sent(),[4,this.renderNodeContent(t)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.renderTextWithLetterSpacing=function(t,n,i){var r=this;if(n===0)navigator.userAgent.indexOf("Firefox")===-1?(this.ctx.textBaseline="ideographic",this.ctx.fillText(t.text,t.bounds.left,t.bounds.top+t.bounds.height)):this.ctx.fillText(t.text,t.bounds.left,t.bounds.top+i);else{var s=Fc(t.text);s.reduce(function(o,a){return r.ctx.fillText(a,o,t.bounds.top+i),o+r.ctx.measureText(a).width},t.bounds.left)}},e.prototype.createFontStyle=function(t){var n=t.fontVariant.filter(function(s){return s==="normal"||s==="small-caps"}).join(""),i=hT(t.fontFamily).join(", "),r=bA(t.fontSize)?"".concat(t.fontSize.number).concat(t.fontSize.unit):"".concat(t.fontSize.number,"px");return[[t.fontStyle,n,t.fontWeight,r,i].join(" "),i,r]},e.prototype.renderTextNode=function(t,n){return Me(this,void 0,void 0,function(){var i,r,s=this;return Le(this,function(o){return i=this.createFontStyle(n)[0],this.ctx.font=i,this.ctx.direction=n.direction===1?"rtl":"ltr",this.ctx.textAlign="left",this.ctx.textBaseline="alphabetic",r=n.paintOrder,t.textBounds.forEach(function(a){r.forEach(function(c){switch(c){case 0:s.ctx.fillStyle=Ue(n.color),s.renderTextWithLetterSpacing(a,n.letterSpacing,n.fontSize.number);var u=n.textShadow;if(u.length&&a.text.trim().length&&(u.slice(0).reverse().forEach(function(d){s.ctx.shadowColor=Ue(d.color),s.ctx.shadowOffsetX=d.offsetX.number*s.options.scale,s.ctx.shadowOffsetY=d.offsetY.number*s.options.scale,s.ctx.shadowBlur=d.blur.number,s.renderTextWithLetterSpacing(a,n.letterSpacing,n.fontSize.number)}),s.ctx.shadowColor="",s.ctx.shadowOffsetX=0,s.ctx.shadowOffsetY=0,s.ctx.shadowBlur=0),n.textDecorationLine.length){s.ctx.fillStyle=Ue(n.textDecorationColor||n.color);var l=1;n.textDecorationLine.forEach(function(d){switch(d){case 1:s.ctx.fillRect(a.bounds.left,a.bounds.top+a.bounds.height-l,a.bounds.width,l);break;case 2:s.ctx.fillRect(a.bounds.left,a.bounds.top,a.bounds.width,l);break;case 3:s.ctx.fillRect(a.bounds.left,a.bounds.top+(a.bounds.height/2-l/2),a.bounds.width,l);break}})}break;case 1:n.webkitTextStrokeWidth&&a.text.trim().length&&(s.ctx.strokeStyle=Ue(n.webkitTextStrokeColor),s.ctx.lineWidth=n.webkitTextStrokeWidth,s.ctx.lineJoin=window.chrome?"miter":"round",s.ctx.strokeText(a.text,a.bounds.left,a.bounds.top+a.bounds.height)),s.ctx.strokeStyle="",s.ctx.lineWidth=0,s.ctx.lineJoin="miter";break}})}),[2]})})},e.prototype.renderReplacedElement=function(t,n,i){var r=i.naturalWidth||t.intrinsicWidth,s=i.naturalHeight||t.intrinsicHeight;if(i&&r>0&&s>0){var o=Os(t),a=Ps(n);this.path(a),this.ctx.save(),this.ctx.clip();var c=0,u=0,l=r,d=s,h=o.left,f=o.top,g=o.width,p=o.height,B=t.styles.objectFit,y=g/p,b=l/d;if(B===2)b>y?(p=g/b,f+=(o.height-p)/2):(g=p*b,h+=(o.width-g)/2);else if(B===4)b>y?(l=d*y,c+=(r-l)/2):(d=l/y,u+=(s-d)/2);else if(B===8)l>g?(c+=(l-g)/2,l=g):(h+=(g-l)/2,g=l),d>p?(u+=(d-p)/2,d=p):(f+=(p-d)/2,p=d);else if(B===16){var v=b>y?g:p*b,C=l>g?l:g;v<C?b>y?(p=g/b,f+=(o.height-p)/2):(g=p*b,h+=(o.width-g)/2):(l>g?(c+=(l-g)/2,l=g):(h+=(g-l)/2,g=l),d>p?(u+=(d-p)/2,d=p):(f+=(p-d)/2,p=d))}this.ctx.drawImage(i,c,u,l,d,h,f,g,p),this.ctx.restore()}},e.prototype.renderNodeContent=function(t){return Me(this,void 0,void 0,function(){var n,i,r,s,o,a,b,b,c,u,l,d,C,h,f,g,w,p,B,y,b,v,C,w;return Le(this,function(S){switch(S.label){case 0:this.applyEffects(t.getEffects(4)),n=t.container,i=t.curves,r=n.styles,s=0,o=n.textNodes,S.label=1;case 1:return s<o.length?(a=o[s],[4,this.renderTextNode(a,r)]):[3,4];case 2:S.sent(),S.label=3;case 3:return s++,[3,1];case 4:if(!(n instanceof ug))return[3,8];S.label=5;case 5:return S.trys.push([5,7,,8]),[4,this.context.cache.match(n.src)];case 6:return b=S.sent(),this.renderReplacedElement(n,i,b),[3,8];case 7:return S.sent(),this.context.logger.error("Error loading image ".concat(n.src)),[3,8];case 8:if(n instanceof lg&&this.renderReplacedElement(n,i,n.canvas),!(n instanceof dg))return[3,12];S.label=9;case 9:return S.trys.push([9,11,,12]),[4,this.context.cache.match(n.svg)];case 10:return b=S.sent(),this.renderReplacedElement(n,i,b),[3,12];case 11:return S.sent(),this.context.logger.error("Error loading svg ".concat(n.svg.substring(0,255))),[3,12];case 12:return n instanceof mg&&n.tree?(c=new e(this.context,{scale:this.options.scale,backgroundColor:n.backgroundColor,x:0,y:0,width:n.width,height:n.height}),[4,c.render(n.tree)]):[3,14];case 13:u=S.sent(),n.width&&n.height&&this.ctx.drawImage(u,0,0,n.width,n.height,n.bounds.left,n.bounds.top,n.bounds.width,n.bounds.height),S.label=14;case 14:if(n instanceof Ic&&(l=Math.min(n.bounds.width,n.bounds.height),n.type===Ts?n.checked&&(this.ctx.save(),this.path([new R(n.bounds.left+l*.39363,n.bounds.top+l*.79),new R(n.bounds.left+l*.16,n.bounds.top+l*.5549),new R(n.bounds.left+l*.27347,n.bounds.top+l*.44071),new R(n.bounds.left+l*.39694,n.bounds.top+l*.5649),new R(n.bounds.left+l*.72983,n.bounds.top+l*.23),new R(n.bounds.left+l*.84,n.bounds.top+l*.34085),new R(n.bounds.left+l*.39363,n.bounds.top+l*.79)]),this.ctx.fillStyle=Ue(fg),this.ctx.fill(),this.ctx.restore()):n.type===Qs&&n.checked&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(n.bounds.left+l/2,n.bounds.top+l/2,l/4,0,Math.PI*2,!0),this.ctx.fillStyle=Ue(fg),this.ctx.fill(),this.ctx.restore())),cT(n)&&n.value.length){switch(d=this.createFontStyle(r),C=d[0],h=d[1],f=d[2],g=this.fontMetrics.getMetrics(h,f).baseline,this.ctx.font=C,this.ctx.fillStyle=Ue(r.color),this.ctx.textBaseline="alphabetic",this.ctx.textAlign=lT(n.styles.textAlign),w=Os(n),p=0,n.styles.textAlign){case 1:p+=w.width/2;break;case 2:p+=w.width;break}B=w.add(p,0,0,-w.height/2+1),this.ctx.save(),this.path([new R(w.left,w.top),new R(w.left+w.width,w.top),new R(w.left+w.width,w.top+w.height),new R(w.left,w.top+w.height)]),this.ctx.clip(),this.renderTextWithLetterSpacing(new ki(n.value,B),r.letterSpacing,g),this.ctx.restore(),this.ctx.textBaseline="alphabetic",this.ctx.textAlign="left"}if(!be(n.styles.display,2048))return[3,20];if(n.styles.listStyleImage===null)return[3,19];if(y=n.styles.listStyleImage,y.type!==0)return[3,18];b=void 0,v=y.url,S.label=15;case 15:return S.trys.push([15,17,,18]),[4,this.context.cache.match(v)];case 16:return b=S.sent(),this.ctx.drawImage(b,n.bounds.left-(b.width+10),n.bounds.top),[3,18];case 17:return S.sent(),this.context.logger.error("Error loading list-style-image ".concat(v)),[3,18];case 18:return[3,20];case 19:t.listValue&&n.styles.listStyleType!==-1&&(C=this.createFontStyle(r)[0],this.ctx.font=C,this.ctx.fillStyle=Ue(r.color),this.ctx.textBaseline="middle",this.ctx.textAlign="right",w=new Jt(n.bounds.left,n.bounds.top+ne(n.styles.paddingTop,n.bounds.width),n.bounds.width,jf(r.lineHeight,r.fontSize.number)/2+1),this.renderTextWithLetterSpacing(new ki(t.listValue,w),r.letterSpacing,jf(r.lineHeight,r.fontSize.number)/2+2),this.ctx.textBaseline="bottom",this.ctx.textAlign="left"),S.label=20;case 20:return[2]}})})},e.prototype.renderStackContent=function(t){return Me(this,void 0,void 0,function(){var n,i,B,r,s,B,o,a,B,c,u,B,l,d,B,h,f,B,g,p,B;return Le(this,function(y){switch(y.label){case 0:if(be(t.element.container.flags,16))debugger;return[4,this.renderNodeBackgroundAndBorders(t.element)];case 1:y.sent(),n=0,i=t.negativeZIndex,y.label=2;case 2:return n<i.length?(B=i[n],[4,this.renderStack(B)]):[3,5];case 3:y.sent(),y.label=4;case 4:return n++,[3,2];case 5:return[4,this.renderNodeContent(t.element)];case 6:y.sent(),r=0,s=t.nonInlineLevel,y.label=7;case 7:return r<s.length?(B=s[r],[4,this.renderNode(B)]):[3,10];case 8:y.sent(),y.label=9;case 9:return r++,[3,7];case 10:o=0,a=t.nonPositionedFloats,y.label=11;case 11:return o<a.length?(B=a[o],[4,this.renderStack(B)]):[3,14];case 12:y.sent(),y.label=13;case 13:return o++,[3,11];case 14:c=0,u=t.nonPositionedInlineLevel,y.label=15;case 15:return c<u.length?(B=u[c],[4,this.renderStack(B)]):[3,18];case 16:y.sent(),y.label=17;case 17:return c++,[3,15];case 18:l=0,d=t.inlineLevel,y.label=19;case 19:return l<d.length?(B=d[l],[4,this.renderNode(B)]):[3,22];case 20:y.sent(),y.label=21;case 21:return l++,[3,19];case 22:h=0,f=t.zeroOrAutoZIndexOrTransformedOrOpacity,y.label=23;case 23:return h<f.length?(B=f[h],[4,this.renderStack(B)]):[3,26];case 24:y.sent(),y.label=25;case 25:return h++,[3,23];case 26:g=0,p=t.positiveZIndex,y.label=27;case 27:return g<p.length?(B=p[g],[4,this.renderStack(B)]):[3,30];case 28:y.sent(),y.label=29;case 29:return g++,[3,27];case 30:return[2]}})})},e.prototype.mask=function(t){this.ctx.beginPath(),this.ctx.moveTo(0,0),this.ctx.lineTo(this.canvas.width,0),this.ctx.lineTo(this.canvas.width,this.canvas.height),this.ctx.lineTo(0,this.canvas.height),this.ctx.lineTo(0,0),this.formatPath(t.slice(0).reverse()),this.ctx.closePath()},e.prototype.path=function(t){this.ctx.beginPath(),this.formatPath(t),this.ctx.closePath()},e.prototype.formatPath=function(t){var n=this;t.forEach(function(i,r){var s=ut(i)?i.start:i;r===0?n.ctx.moveTo(s.x,s.y):n.ctx.lineTo(s.x,s.y),ut(i)&&n.ctx.bezierCurveTo(i.startControl.x,i.startControl.y,i.endControl.x,i.endControl.y,i.end.x,i.end.y)})},e.prototype.renderRepeat=function(t,n,i,r){this.path(t),this.ctx.fillStyle=n,this.ctx.translate(i,r),this.ctx.fill(),this.ctx.translate(-i,-r)},e.prototype.resizeImage=function(t,n,i){var r,s=(r=this.canvas.ownerDocument)!==null&&r!==void 0?r:document,o=s.createElement("canvas");o.width=Math.max(1,n),o.height=Math.max(1,i);var a=o.getContext("2d");return a.drawImage(t,0,0,t.width,t.height,0,0,n,i),o},e.prototype.renderBackgroundImage=function(t){return Me(this,void 0,void 0,function(){var n,i,r,s,o,a;return Le(this,function(c){switch(c.label){case 0:n=t.styles.backgroundImage.length-1,i=function(u){var l,d,h,f,g,M,He,De,G,q,D,p,M,He,De,G,q,B,y,b,v,C,w,S,F,_,D,O,M,K,Pe,G,q,et,He,De,AA,ft,Ge,nA,Ft,Ve,Jn,gt;return Le(this,function(Xn){switch(Xn.label){case 0:if(u.type!==0)return[3,5];l=void 0,d=u.url,Xn.label=1;case 1:return Xn.trys.push([1,3,,4]),[4,r.context.cache.match(d)];case 2:return l=Xn.sent(),[3,4];case 3:return Xn.sent(),r.context.logger.error("Error loading background-image ".concat(d)),[3,4];case 4:return l&&(h=isNaN(l.width)||l.width===0?1:l.width,f=isNaN(l.height)||l.height===0?1:l.height,g=Gc(t,n,[h,f,h/f]),M=g[0],He=g[1],De=g[2],G=g[3],q=g[4],D=r.ctx.createPattern(r.resizeImage(l,G,q),"repeat"),r.renderRepeat(M,D,He,De)),[3,6];case 5:jb(u)?(p=Gc(t,n,[null,null,null]),M=p[0],He=p[1],De=p[2],G=p[3],q=p[4],B=Mb(u.angle,G,q),y=B[0],b=B[1],v=B[2],C=B[3],w=B[4],S=document.createElement("canvas"),S.width=G,S.height=q,F=S.getContext("2d"),_=F.createLinearGradient(b,C,v,w),Rf(u.stops,y||1).forEach(function(zi){return _.addColorStop(zi.stop,Ue(zi.color))}),F.fillStyle=_,F.fillRect(0,0,G,q),G>0&&q>0&&(D=r.ctx.createPattern(S,"repeat"),r.renderRepeat(M,D,He,De))):$b(u)&&(O=Gc(t,n,[null,null,null]),M=O[0],K=O[1],Pe=O[2],G=O[3],q=O[4],et=u.position.length===0?[uc]:u.position,He=ne(et[0],G),De=ne(et[et.length-1],q),AA=Nb(u,He,De,G,q),ft=AA[0],Ge=AA[1],ft>0&&Ge>0&&(nA=r.ctx.createRadialGradient(K+He,Pe+De,0,K+He,Pe+De,ft),Rf(u.stops,ft*2).forEach(function(zi){return nA.addColorStop(zi.stop,Ue(zi.color))}),r.path(M),r.ctx.fillStyle=nA,ft!==Ge?(Ft=t.bounds.left+.5*t.bounds.width,Ve=t.bounds.top+.5*t.bounds.height,Jn=Ge/ft,gt=1/Jn,r.ctx.save(),r.ctx.translate(Ft,Ve),r.ctx.transform(1,0,0,Jn,0,0),r.ctx.translate(-Ft,-Ve),r.ctx.fillRect(K,gt*(Pe-Ve)+Ve,G,q*gt),r.ctx.restore()):r.ctx.fill())),Xn.label=6;case 6:return n--,[2]}})},r=this,s=0,o=t.styles.backgroundImage.slice(0).reverse(),c.label=1;case 1:return s<o.length?(a=o[s],[5,i(a)]):[3,4];case 2:c.sent(),c.label=3;case 3:return s++,[3,1];case 4:return[2]}})})},e.prototype.renderSolidBorder=function(t,n,i){return Me(this,void 0,void 0,function(){return Le(this,function(r){return this.path(Kg(i,n)),this.ctx.fillStyle=Ue(t),this.ctx.fill(),[2]})})},e.prototype.renderDoubleBorder=function(t,n,i,r){return Me(this,void 0,void 0,function(){var s,o;return Le(this,function(a){switch(a.label){case 0:return n<3?[4,this.renderSolidBorder(t,i,r)]:[3,2];case 1:return a.sent(),[2];case 2:return s=zU(r,i),this.path(s),this.ctx.fillStyle=Ue(t),this.ctx.fill(),o=ZU(r,i),this.path(o),this.ctx.fill(),[2]}})})},e.prototype.renderNodeBackgroundAndBorders=function(t){return Me(this,void 0,void 0,function(){var n,i,r,s,o,a,c,u,l=this;return Le(this,function(d){switch(d.label){case 0:return this.applyEffects(t.getEffects(2)),n=t.container.styles,i=!UA(n.backgroundColor)||n.backgroundImage.length,r=[{style:n.borderTopStyle,color:n.borderTopColor,width:n.borderTopWidth},{style:n.borderRightStyle,color:n.borderRightColor,width:n.borderRightWidth},{style:n.borderBottomStyle,color:n.borderBottomColor,width:n.borderBottomWidth},{style:n.borderLeftStyle,color:n.borderLeftColor,width:n.borderLeftWidth}],s=uT(Ln(n.backgroundClip,0),t.curves),i||n.boxShadow.length?(this.ctx.save(),this.path(s),this.ctx.clip(),UA(n.backgroundColor)||(this.ctx.fillStyle=Ue(n.backgroundColor),this.ctx.fill()),[4,this.renderBackgroundImage(t.container)]):[3,2];case 1:d.sent(),this.ctx.restore(),n.boxShadow.slice(0).reverse().forEach(function(h){l.ctx.save();var f=Rs(t.curves),g=h.inset?0:oT,p=qU(f,-g+(h.inset?1:-1)*h.spread.number,(h.inset?1:-1)*h.spread.number,h.spread.number*(h.inset?-2:2),h.spread.number*(h.inset?-2:2));h.inset?(l.path(f),l.ctx.clip(),l.mask(p)):(l.mask(f),l.ctx.clip(),l.path(p)),l.ctx.shadowOffsetX=h.offsetX.number+g,l.ctx.shadowOffsetY=h.offsetY.number,l.ctx.shadowColor=Ue(h.color),l.ctx.shadowBlur=h.blur.number,l.ctx.fillStyle=h.inset?Ue(h.color):"rgba(0,0,0,1)",l.ctx.fill(),l.ctx.restore()}),d.label=2;case 2:o=0,a=0,c=r,d.label=3;case 3:return a<c.length?(u=c[a],u.style!==0&&!UA(u.color)&&u.width>0?u.style!==2?[3,5]:[4,this.renderDashedDottedBorder(u.color,u.width,o,t.curves,2)]:[3,11]):[3,13];case 4:return d.sent(),[3,11];case 5:return u.style!==3?[3,7]:[4,this.renderDashedDottedBorder(u.color,u.width,o,t.curves,3)];case 6:return d.sent(),[3,11];case 7:return u.style!==4?[3,9]:[4,this.renderDoubleBorder(u.color,u.width,o,t.curves)];case 8:return d.sent(),[3,11];case 9:return[4,this.renderSolidBorder(u.color,o,t.curves)];case 10:d.sent(),d.label=11;case 11:o++,d.label=12;case 12:return a++,[3,3];case 13:return[2]}})})},e.prototype.renderDashedDottedBorder=function(t,n,i,r,s){return Me(this,void 0,void 0,function(){var o,a,c,u,l,d,h,f,g,p,B,y,b,v,C,w,C,w;return Le(this,function(S){return this.ctx.save(),o=eT(r,i),a=Kg(r,i),s===2&&(this.path(a),this.ctx.clip()),ut(a[0])?(c=a[0].start.x,u=a[0].start.y):(c=a[0].x,u=a[0].y),ut(a[1])?(l=a[1].end.x,d=a[1].end.y):(l=a[1].x,d=a[1].y),i===0||i===2?h=Math.abs(c-l):h=Math.abs(u-d),this.ctx.beginPath(),s===3?this.formatPath(o):this.formatPath(a.slice(0,2)),f=n<3?n*3:n*2,g=n<3?n*2:n,s===3&&(f=n,g=n),p=!0,h<=f*2?p=!1:h<=f*2+g?(B=h/(2*f+g),f*=B,g*=B):(y=Math.floor((h+g)/(f+g)),b=(h-y*f)/(y-1),v=(h-(y+1)*f)/y,g=v<=0||Math.abs(g-b)<Math.abs(g-v)?b:v),p&&(s===3?this.ctx.setLineDash([0,f+g]):this.ctx.setLineDash([f,g])),s===3?(this.ctx.lineCap="round",this.ctx.lineWidth=n):this.ctx.lineWidth=n*2+1.1,this.ctx.strokeStyle=Ue(t),this.ctx.stroke(),this.ctx.setLineDash([]),s===2&&(ut(a[0])&&(C=a[3],w=a[0],this.ctx.beginPath(),this.formatPath([new R(C.end.x,C.end.y),new R(w.start.x,w.start.y)]),this.ctx.stroke()),ut(a[1])&&(C=a[1],w=a[2],this.ctx.beginPath(),this.formatPath([new R(C.end.x,C.end.y),new R(w.start.x,w.start.y)]),this.ctx.stroke())),this.ctx.restore(),[2]})})},e.prototype.render=function(t){return Me(this,void 0,void 0,function(){var n;return Le(this,function(i){switch(i.label){case 0:return this.options.backgroundColor&&(this.ctx.fillStyle=Ue(this.options.backgroundColor),this.ctx.fillRect(this.options.x,this.options.y,this.options.width,this.options.height)),n=YU(t),[4,this.renderStack(n)];case 1:return i.sent(),this.applyEffects([]),[2,this.canvas]}})})},e}(jg),cT=function(A){return A instanceof pg||A instanceof gg?!0:A instanceof Ic&&A.type!==Qs&&A.type!==Ts},uT=function(A,e){switch(A){case 0:return Rs(e);case 2:return jU(e);case 1:default:return Ps(e)}},lT=function(A){switch(A){case 1:return"center";case 2:return"right";case 0:default:return"left"}},dT=["-apple-system","system-ui"],hT=function(A){return/iPhone OS 15_(0|1)/.test(window.navigator.userAgent)?A.filter(function(e){return dT.indexOf(e)===-1}):A},fT=function(A){St(e,A);function e(t,n){var i=A.call(this,t,n)||this;return i.canvas=n.canvas?n.canvas:document.createElement("canvas"),i.ctx=i.canvas.getContext("2d"),i.options=n,i.canvas.width=Math.floor(n.width*n.scale),i.canvas.height=Math.floor(n.height*n.scale),i.canvas.style.width="".concat(n.width,"px"),i.canvas.style.height="".concat(n.height,"px"),i.ctx.scale(i.options.scale,i.options.scale),i.ctx.translate(-n.x,-n.y),i.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized (".concat(n.width,"x").concat(n.height," at ").concat(n.x,",").concat(n.y,") with scale ").concat(n.scale)),i}return e.prototype.render=function(t){return Me(this,void 0,void 0,function(){var n,i;return Le(this,function(r){switch(r.label){case 0:return n=Qc(this.options.width*this.options.scale,this.options.height*this.options.scale,this.options.scale,this.options.scale,t),[4,gT(n)];case 1:return i=r.sent(),this.options.backgroundColor&&(this.ctx.fillStyle=Ue(this.options.backgroundColor),this.ctx.fillRect(0,0,this.options.width*this.options.scale,this.options.height*this.options.scale)),this.ctx.drawImage(i,-this.options.x*this.options.scale,-this.options.y*this.options.scale),[2,this.canvas]}})})},e}(jg),gT=function(A){return new Promise(function(e,t){var n=new Image;n.onload=function(){e(n)},n.onerror=t,n.src="data:image/svg+xml;charset=utf-8,".concat(encodeURIComponent(new XMLSerializer().serializeToString(A)))})},pT=function(){function A(e){var t=e.id,n=e.enabled;this.id=t,this.enabled=n,this.start=Date.now()}return A.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&(typeof window<"u"&&window.console&&typeof console.debug=="function"?console.debug.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1)):this.info.apply(this,e))},A.prototype.getTime=function(){return Date.now()-this.start},A.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&typeof window<"u"&&window.console&&typeof console.info=="function"&&console.info.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1))},A.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&(typeof window<"u"&&window.console&&typeof console.warn=="function"?console.warn.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1)):this.info.apply(this,e))},A.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&(typeof window<"u"&&window.console&&typeof console.error=="function"?console.error.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1)):this.info.apply(this,e))},A.instances={},A}(),mT=function(){function A(e,t){var n;this.windowBounds=t,this.instanceName="#".concat(A.instanceCount++),this.logger=new pT({id:this.instanceName,enabled:e.logging}),this.cache=(n=e.cache)!==null&&n!==void 0?n:new LU(this,e)}return A.instanceCount=1,A}(),BT=function(A,e){return e===void 0&&(e={}),vT(A,e)};typeof window<"u"&&Hc.setContext(window);var vT=function(A,e){return Me(void 0,void 0,void 0,function(){var t,n,i,r,s,o,a,c,u,l,d,h,f,g,p,B,y,b,v,C,S,w,S,F,_,D,O,M,K,Pe,G,q,et,He,De,AA,ft,Ge,nA,Ft;return Le(this,function(Ve){switch(Ve.label){case 0:if(!A||typeof A!="object")return[2,Promise.reject("Invalid element provided as first argument")];if(t=A.ownerDocument,!t)throw new Error("Element is not attached to a Document");if(n=t.defaultView,!n)throw new Error("Document is not attached to a Window");return i={allowTaint:(F=e.allowTaint)!==null&&F!==void 0?F:!1,imageTimeout:(_=e.imageTimeout)!==null&&_!==void 0?_:15e3,proxy:e.proxy,useCORS:(D=e.useCORS)!==null&&D!==void 0?D:!1,customIsSameOrigin:e.customIsSameOrigin},r=Ga({logging:(O=e.logging)!==null&&O!==void 0?O:!0,cache:e.cache},i),s={windowWidth:(M=e.windowWidth)!==null&&M!==void 0?M:n.innerWidth,windowHeight:(K=e.windowHeight)!==null&&K!==void 0?K:n.innerHeight,scrollX:(Pe=e.scrollX)!==null&&Pe!==void 0?Pe:n.pageXOffset,scrollY:(G=e.scrollY)!==null&&G!==void 0?G:n.pageYOffset},o=new Jt(s.scrollX,s.scrollY,s.windowWidth,s.windowHeight),a=new mT(r,o),c=(q=e.foreignObjectRendering)!==null&&q!==void 0?q:!1,u={allowTaint:(et=e.allowTaint)!==null&&et!==void 0?et:!1,onclone:e.onclone,ignoreElements:e.ignoreElements,inlineImages:c,copyStyles:c},a.logger.debug("Starting document clone with size ".concat(o.width,"x").concat(o.height," scrolled to ").concat(-o.left,",").concat(-o.top)),l=new Pg(a,A,u),d=l.clonedReferenceElement,d?[4,l.toIFrame(t,o)]:[2,Promise.reject("Unable to find element in cloned iframe")];case 1:return h=Ve.sent(),f=xc(d)||vU(d)?tw(d.ownerDocument):Kr(a,d),g=f.width,p=f.height,B=f.left,y=f.top,b=CT(a,d,e.backgroundColor),v={canvas:e.canvas,backgroundColor:b,scale:(De=(He=e.scale)!==null&&He!==void 0?He:n.devicePixelRatio)!==null&&De!==void 0?De:1,x:((AA=e.x)!==null&&AA!==void 0?AA:0)+B,y:((ft=e.y)!==null&&ft!==void 0?ft:0)+y,width:(Ge=e.width)!==null&&Ge!==void 0?Ge:Math.ceil(g),height:(nA=e.height)!==null&&nA!==void 0?nA:Math.ceil(p)},c?(a.logger.debug("Document cloned, using foreign object rendering"),S=new fT(a,v),[4,S.render(d)]):[3,3];case 2:return C=Ve.sent(),[3,5];case 3:return a.logger.debug("Document cloned, element located at ".concat(B,",").concat(y," with size ").concat(g,"x").concat(p," using computed rendering")),a.logger.debug("Starting DOM parsing"),w=vg(a,d),b===w.styles.backgroundColor&&(w.styles.backgroundColor=Ht.TRANSPARENT),a.logger.debug("Starting renderer for element at ".concat(v.x,",").concat(v.y," with size ").concat(v.width,"x").concat(v.height)),S=new aT(a,v),[4,S.render(w)];case 4:C=Ve.sent(),Ve.label=5;case 5:return(!((Ft=e.removeContainer)!==null&&Ft!==void 0)||Ft)&&(Pg.destroy(h)||a.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore")),a.logger.debug("Finished rendering"),[2,C]}})})},CT=function(A,e,t){var n=e.ownerDocument,i=n.documentElement?kn(A,getComputedStyle(n.documentElement).backgroundColor):Ht.TRANSPARENT,r=n.body?kn(A,getComputedStyle(n.body).backgroundColor):Ht.TRANSPARENT,s=typeof t=="string"?kn(A,t):t===null?Ht.TRANSPARENT:4294967295;return e===n.documentElement?UA(i)?UA(r)?s:r:i:s};class wT{constructor(e){this.namespace=e}getItem(e){return localStorage.getItem(`${this.namespace}.${e}`)}setItem(e,t){localStorage.setItem(`${this.namespace}.${e}`,t)}removeItem(e){localStorage.removeItem(`${this.namespace}.${e}`)}clear(){for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);t&&t.startsWith(`${this.namespace}.`)&&localStorage.removeItem(t)}}}const Vc={SESSION_DATA:"session_data"},jc=new wT("io.obi.widget"),X=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,zA="9.23.0",Ae=globalThis;function Ms(){return Ns(Ae),Ae}function Ns(A){const e=A.__SENTRY__=A.__SENTRY__||{};return e.version=e.version||zA,e[zA]=e[zA]||{}}function Ks(A,e,t=Ae){const n=t.__SENTRY__=t.__SENTRY__||{},i=n[zA]=n[zA]||{};return i[A]||(i[A]=e())}const $g=Object.prototype.toString;function $c(A){switch($g.call(A)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return IA(A,Error)}}function On(A,e){return $g.call(A)===`[object ${e}]`}function Wg(A){return On(A,"ErrorEvent")}function Jg(A){return On(A,"DOMError")}function yT(A){return On(A,"DOMException")}function Yt(A){return On(A,"String")}function Wc(A){return typeof A=="object"&&A!==null&&"__sentry_template_string__"in A&&"__sentry_template_values__"in A}function Jc(A){return A===null||Wc(A)||typeof A!="object"&&typeof A!="function"}function Ri(A){return On(A,"Object")}function Gs(A){return typeof Event<"u"&&IA(A,Event)}function bT(A){return typeof Element<"u"&&IA(A,Element)}function ET(A){return On(A,"RegExp")}function Vs(A){return!!(A?.then&&typeof A.then=="function")}function ST(A){return Ri(A)&&"nativeEvent"in A&&"preventDefault"in A&&"stopPropagation"in A}function IA(A,e){try{return A instanceof e}catch{return!1}}function Xg(A){return!!(typeof A=="object"&&A!==null&&(A.__isVue||A._isVue))}function UT(A){return typeof Request<"u"&&IA(A,Request)}const Xc=Ae,TT=80;function qg(A,e={}){if(!A)return"<unknown>";try{let t=A;const n=5,i=[];let r=0,s=0;const o=" > ",a=o.length;let c;const u=Array.isArray(e)?e:e.keyAttrs,l=!Array.isArray(e)&&e.maxStringLength||TT;for(;t&&r++<n&&(c=QT(t,u),!(c==="html"||r>1&&s+i.length*a+c.length>=l));)i.push(c),s+=c.length,t=t.parentNode;return i.reverse().join(o)}catch{return"<unknown>"}}function QT(A,e){const t=A,n=[];if(!t?.tagName)return"";if(Xc.HTMLElement&&t instanceof HTMLElement&&t.dataset){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}n.push(t.tagName.toLowerCase());const i=e?.length?e.filter(s=>t.getAttribute(s)).map(s=>[s,t.getAttribute(s)]):null;if(i?.length)i.forEach(s=>{n.push(`[${s[0]}="${s[1]}"]`)});else{t.id&&n.push(`#${t.id}`);const s=t.className;if(s&&Yt(s)){const o=s.split(/\s+/);for(const a of o)n.push(`.${a}`)}}const r=["aria-label","type","name","title","alt"];for(const s of r){const o=t.getAttribute(s);o&&n.push(`[${s}="${o}"]`)}return n.join("")}function Yg(){try{return Xc.document.location.href}catch{return""}}function FT(A){if(!Xc.HTMLElement)return null;let e=A;const t=5;for(let n=0;n<t;n++){if(!e)return null;if(e instanceof HTMLElement){if(e.dataset.sentryComponent)return e.dataset.sentryComponent;if(e.dataset.sentryElement)return e.dataset.sentryElement}e=e.parentNode}return null}const kT="Sentry Logger ",qc=["debug","info","warn","error","log","assert","trace"],js={};function $s(A){if(!("console"in Ae))return A();const e=Ae.console,t={},n=Object.keys(js);n.forEach(i=>{const r=js[i];t[i]=e[i],e[i]=r});try{return A()}finally{n.forEach(i=>{e[i]=t[i]})}}function IT(){let A=!1;const e={enable:()=>{A=!0},disable:()=>{A=!1},isEnabled:()=>A};return X?qc.forEach(t=>{e[t]=(...n)=>{A&&$s(()=>{Ae.console[t](`${kT}[${t}]:`,...n)})}}):qc.forEach(t=>{e[t]=()=>{}}),e}const N=Ks("logger",IT);function Ws(A,e=0){return typeof A!="string"||e===0||A.length<=e?A:`${A.slice(0,e)}...`}function zg(A,e){if(!Array.isArray(A))return"";const t=[];for(let n=0;n<A.length;n++){const i=A[n];try{Xg(i)?t.push("[VueViewModel]"):t.push(String(i))}catch{t.push("[value cannot be serialized]")}}return t.join(e)}function _T(A,e,t=!1){return Yt(A)?ET(e)?e.test(A):Yt(e)?t?A===e:A.includes(e):!1:!1}function Js(A,e=[],t=!1){return e.some(n=>_T(A,n,t))}function it(A,e,t){if(!(e in A))return;const n=A[e];if(typeof n!="function")return;const i=t(n);typeof i=="function"&&Zg(i,n);try{A[e]=i}catch{X&&N.log(`Failed to replace method "${e}" in object`,A)}}function ZA(A,e,t){try{Object.defineProperty(A,e,{value:t,writable:!0,configurable:!0})}catch{X&&N.log(`Failed to add non-enumerable property "${e}" to object`,A)}}function Zg(A,e){try{const t=e.prototype||{};A.prototype=e.prototype=t,ZA(A,"__sentry_original__",e)}catch{}}function Yc(A){return A.__sentry_original__}function ep(A){if($c(A))return{message:A.message,name:A.name,stack:A.stack,...Ap(A)};if(Gs(A)){const e={type:A.type,target:tp(A.target),currentTarget:tp(A.currentTarget),...Ap(A)};return typeof CustomEvent<"u"&&IA(A,CustomEvent)&&(e.detail=A.detail),e}else return A}function tp(A){try{return bT(A)?qg(A):Object.prototype.toString.call(A)}catch{return"<unknown>"}}function Ap(A){if(typeof A=="object"&&A!==null){const e={};for(const t in A)Object.prototype.hasOwnProperty.call(A,t)&&(e[t]=A[t]);return e}else return{}}function xT(A,e=40){const t=Object.keys(ep(A));t.sort();const n=t[0];if(!n)return"[object has no keys]";if(n.length>=e)return Ws(n,e);for(let i=t.length;i>0;i--){const r=t.slice(0,i).join(", ");if(!(r.length>e))return i===t.length?r:Ws(r,e)}return""}function RT(){const A=Ae;return A.crypto||A.msCrypto}function dt(A=RT()){let e=()=>Math.random()*16;try{if(A?.randomUUID)return A.randomUUID().replace(/-/g,"");A?.getRandomValues&&(e=()=>{const t=new Uint8Array(1);return A.getRandomValues(t),t[0]})}catch{}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,t=>(t^(e()&15)>>t/4).toString(16))}function np(A){return A.exception?.values?.[0]}function en(A){const{message:e,event_id:t}=A;if(e)return e;const n=np(A);return n?n.type&&n.value?`${n.type}: ${n.value}`:n.type||n.value||t||"<unknown>":t||"<unknown>"}function zc(A,e,t){const n=A.exception=A.exception||{},i=n.values=n.values||[],r=i[0]=i[0]||{};r.value||(r.value=e||""),r.type||(r.type=t||"Error")}function Hn(A,e){const t=np(A);if(!t)return;const n={type:"generic",handled:!0},i=t.mechanism;if(t.mechanism={...n,...i,...e},e&&"data"in e){const r={...i?.data,...e.data};t.mechanism.data=r}}function ip(A){if(PT(A))return!0;try{ZA(A,"__sentry_captured__",!0)}catch{}return!1}function PT(A){try{return A.__sentry_captured__}catch{}}const rp=1e3;function Pi(){return Date.now()/rp}function DT(){const{performance:A}=Ae;if(!A?.now)return Pi;const e=Date.now()-A.now(),t=A.timeOrigin==null?e:A.timeOrigin;return()=>(t+A.now())/rp}const zt=DT();function LT(A){const e=zt(),t={sid:dt(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>HT(t)};return A&&Mn(t,A),t}function Mn(A,e={}){if(e.user&&(!A.ipAddress&&e.user.ip_address&&(A.ipAddress=e.user.ip_address),!A.did&&!e.did&&(A.did=e.user.id||e.user.email||e.user.username)),A.timestamp=e.timestamp||zt(),e.abnormal_mechanism&&(A.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(A.ignoreDuration=e.ignoreDuration),e.sid&&(A.sid=e.sid.length===32?e.sid:dt()),e.init!==void 0&&(A.init=e.init),!A.did&&e.did&&(A.did=`${e.did}`),typeof e.started=="number"&&(A.started=e.started),A.ignoreDuration)A.duration=void 0;else if(typeof e.duration=="number")A.duration=e.duration;else{const t=A.timestamp-A.started;A.duration=t>=0?t:0}e.release&&(A.release=e.release),e.environment&&(A.environment=e.environment),!A.ipAddress&&e.ipAddress&&(A.ipAddress=e.ipAddress),!A.userAgent&&e.userAgent&&(A.userAgent=e.userAgent),typeof e.errors=="number"&&(A.errors=e.errors),e.status&&(A.status=e.status)}function OT(A,e){let t={};e?t={status:e}:A.status==="ok"&&(t={status:"exited"}),Mn(A,t)}function HT(A){return{sid:`${A.sid}`,init:A.init,started:new Date(A.started*1e3).toISOString(),timestamp:new Date(A.timestamp*1e3).toISOString(),status:A.status,errors:A.errors,did:typeof A.did=="number"||typeof A.did=="string"?`${A.did}`:void 0,duration:A.duration,abnormal_mechanism:A.abnormal_mechanism,attrs:{release:A.release,environment:A.environment,ip_address:A.ipAddress,user_agent:A.userAgent}}}function Di(A,e,t=2){if(!e||typeof e!="object"||t<=0)return e;if(A&&Object.keys(e).length===0)return A;const n={...A};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=Di(n[i],e[i],t-1));return n}const Zc="_sentrySpan";function sp(A,e){e?ZA(A,Zc,e):delete A[Zc]}function op(A){return A[Zc]}function ap(){return dt()}function cp(){return dt().substring(16)}const MT=100;class Tt{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:ap(),sampleRand:Math.random()}}clone(){const e=new Tt;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,sp(e,op(this)),e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Mn(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this._tags={...this._tags,[e]:t},this._notifyScopeListeners(),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return t===null?delete this._contexts[e]:this._contexts[e]=t,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;const t=typeof e=="function"?e(this):e,n=t instanceof Tt?t.getScopeData():Ri(t)?e:void 0,{tags:i,extra:r,user:s,contexts:o,level:a,fingerprint:c=[],propagationContext:u}=n||{};return this._tags={...this._tags,...i},this._extra={...this._extra,...r},this._contexts={...this._contexts,...o},s&&Object.keys(s).length&&(this._user=s),a&&(this._level=a),c.length&&(this._fingerprint=c),u&&(this._propagationContext=u),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,sp(this,void 0),this._attachments=[],this.setPropagationContext({traceId:ap(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(e,t){const n=typeof t=="number"?t:MT;if(n<=0)return this;const i={timestamp:Pi(),...e,message:e.message?Ws(e.message,2048):e.message};return this._breadcrumbs.push(i),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client?.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:op(this)}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=Di(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,t){const n=t?.event_id||dt();if(!this._client)return N.warn("No client configured on scope - will not capture exception!"),n;const i=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:i,...t,event_id:n},this),n}captureMessage(e,t,n){const i=n?.event_id||dt();if(!this._client)return N.warn("No client configured on scope - will not capture message!"),i;const r=new Error(e);return this._client.captureMessage(e,t,{originalException:e,syntheticException:r,...n,event_id:i},this),i}captureEvent(e,t){const n=t?.event_id||dt();return this._client?(this._client.captureEvent(e,{...t,event_id:n},this),n):(N.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}function NT(){return Ks("defaultCurrentScope",()=>new Tt)}function KT(){return Ks("defaultIsolationScope",()=>new Tt)}class GT{constructor(e,t){let n;e?n=e:n=new Tt;let i;t?i=t:i=new Tt,this._stack=[{scope:n}],this._isolationScope=i}withScope(e){const t=this._pushScope();let n;try{n=e(t)}catch(i){throw this._popScope(),i}return Vs(n)?n.then(i=>(this._popScope(),i),i=>{throw this._popScope(),i}):(this._popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}function Nn(){const A=Ms(),e=Ns(A);return e.stack=e.stack||new GT(NT(),KT())}function VT(A){return Nn().withScope(A)}function jT(A,e){const t=Nn();return t.withScope(()=>(t.getStackTop().scope=A,e(A)))}function up(A){return Nn().withScope(()=>A(Nn().getIsolationScope()))}function $T(){return{withIsolationScope:up,withScope:VT,withSetScope:jT,withSetIsolationScope:(A,e)=>up(e),getCurrentScope:()=>Nn().getScope(),getIsolationScope:()=>Nn().getIsolationScope()}}function eu(A){const e=Ns(A);return e.acs?e.acs:$T()}function Kn(){const A=Ms();return eu(A).getCurrentScope()}function Li(){const A=Ms();return eu(A).getIsolationScope()}function WT(){return Ks("globalScope",()=>new Tt)}function lp(...A){const e=Ms(),t=eu(e);if(A.length===2){const[n,i]=A;return n?t.withSetScope(n,i):t.withScope(i)}return t.withScope(A[0])}function Ne(){return Kn().getClient()}function JT(A){const e=A.getPropagationContext(),{traceId:t,parentSpanId:n,propagationSpanId:i}=e,r={trace_id:t,span_id:i||cp()};return n&&(r.parent_span_id=n),r}const XT="sentry.source",qT="sentry.sample_rate",YT="sentry.previous_trace_sample_rate",zT="sentry.op",ZT="sentry.origin",dp="sentry.profile_id",hp="sentry.exclusive_time",eQ=0,tQ=1,AQ="_sentryScope",nQ="_sentryIsolationScope";function fp(A){return{scope:A[AQ],isolationScope:A[nQ]}}function iQ(A){if(typeof A=="boolean")return Number(A);const e=typeof A=="string"?parseFloat(A):A;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}const rQ="sentry-",sQ=/^sentry-/;function oQ(A){const e=aQ(A);if(!e)return;const t=Object.entries(e).reduce((n,[i,r])=>{if(i.match(sQ)){const s=i.slice(rQ.length);n[s]=r}return n},{});if(Object.keys(t).length>0)return t}function aQ(A){if(!(!A||!Yt(A)&&!Array.isArray(A)))return Array.isArray(A)?A.reduce((e,t)=>{const n=gp(t);return Object.entries(n).forEach(([i,r])=>{e[i]=r}),e},{}):gp(A)}function gp(A){return A.split(",").map(e=>e.split("=").map(t=>{try{return decodeURIComponent(t.trim())}catch{return}})).reduce((e,[t,n])=>(t&&n&&(e[t]=n),e),{})}const pp=1;let mp=!1;function cQ(A){const{spanId:e,traceId:t,isRemote:n}=A.spanContext(),i=n?e:tu(A).parent_span_id,r=fp(A).scope,s=n?r?.getPropagationContext().propagationSpanId||cp():e;return{parent_span_id:i,span_id:s,trace_id:t}}function uQ(A){if(A&&A.length>0)return A.map(({context:{spanId:e,traceId:t,traceFlags:n,...i},attributes:r})=>({span_id:e,trace_id:t,sampled:n===pp,attributes:r,...i}))}function Bp(A){return typeof A=="number"?vp(A):Array.isArray(A)?A[0]+A[1]/1e9:A instanceof Date?vp(A.getTime()):zt()}function vp(A){return A>9999999999?A/1e3:A}function tu(A){if(dQ(A))return A.getSpanJSON();const{spanId:e,traceId:t}=A.spanContext();if(lQ(A)){const{attributes:n,startTime:i,name:r,endTime:s,status:o,links:a}=A,c="parentSpanId"in A?A.parentSpanId:"parentSpanContext"in A?A.parentSpanContext?.spanId:void 0;return{span_id:e,trace_id:t,data:n,description:r,parent_span_id:c,start_timestamp:Bp(i),timestamp:Bp(s)||void 0,status:fQ(o),op:n[zT],origin:n[ZT],links:uQ(a)}}return{span_id:e,trace_id:t,start_timestamp:0,data:{}}}function lQ(A){const e=A;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function dQ(A){return typeof A.getSpanJSON=="function"}function hQ(A){const{traceFlags:e}=A.spanContext();return e===pp}function fQ(A){if(!(!A||A.code===eQ))return A.code===tQ?"ok":A.message||"unknown_error"}const gQ="_sentryRootSpan";function Cp(A){return A[gQ]||A}function wp(){mp||($s(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")}),mp=!0)}const yp=50,tn="?",bp=/\(error: (.*)\)/,Ep=/captureMessage|captureException/;function pQ(...A){const e=A.sort((t,n)=>t[0]-n[0]).map(t=>t[1]);return(t,n=0,i=0)=>{const r=[],s=t.split(`
|
|
111
|
-
`);for(let o=n;o<s.length;o++){const a=s[o];if(a.length>1024)continue;const c=bp.test(a)?a.replace(bp,"$1"):a;if(!c.match(/\S*Error: /)){for(const u of e){const l=u(c);if(l){r.push(l);break}}if(r.length>=yp+i)break}}return
|
|
110
|
+
.`).concat(Oc).concat(xU).concat(Dg))},PU=function(A,e){var t=A.ownerDocument;if(t){var n=t.createElement("style");n.textContent=e,A.appendChild(n)}},DU=function(A,e){var t,n=e.createElement("base");n.href=e.baseURI;var i=A.getElementsByTagName("head").item(0);i?.insertBefore(n,(t=i?.firstChild)!==null&&t!==void 0?t:null)},Hc=function(){function A(){}return A.getOrigin=function(e){var t=A._link;return t?(t.href=e,t.href=t.href,t.protocol+t.hostname+t.port):"about:blank"},A.isSameOrigin=function(e){return A.getOrigin(e)===A._origin},A.setContext=function(e){A._link=e.document.createElement("a"),A._origin=A.getOrigin(e.location.href)},A._origin="about:blank",A}(),LU=function(){function A(e,t){this.context=e,this._options=t,this._cache={}}return A.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)||(Nc(e)||NU(e))&&(this._cache[e]=this.loadImage(e)).catch(function(){}),t},A.prototype.match=function(e){return this._cache[e]},A.prototype.loadImage=function(e){return Me(this,void 0,void 0,function(){var t,n,i,r,s,o=this;return Le(this,function(a){switch(a.label){case 0:return typeof this._options.customIsSameOrigin!="function"?[3,2]:[4,this._options.customIsSameOrigin(e,Hc.isSameOrigin)];case 1:return n=a.sent(),[3,3];case 2:n=Hc.isSameOrigin(e),a.label=3;case 3:return t=n,i=!Mc(e)&&this._options.useCORS===!0&&_e.SUPPORT_CORS_IMAGES&&!t,r=!Mc(e)&&!t&&!Nc(e)&&typeof this._options.proxy=="string"&&_e.SUPPORT_CORS_XHR&&!i,!t&&this._options.allowTaint===!1&&!Mc(e)&&!Nc(e)&&!r&&!i?[2]:(s=e,r?[4,this.proxy(s)]:[3,5]);case 4:s=a.sent(),a.label=5;case 5:return this.context.logger.debug("Added image ".concat(e.substring(0,256))),[4,new Promise(function(c,u){var l=new Image;l.onload=function(){return c(l)},l.onerror=u,(KU(s)||i)&&(l.crossOrigin="anonymous"),l.src=s,l.complete===!0&&setTimeout(function(){return c(l)},500),o._options.imageTimeout>0&&setTimeout(function(){return u("Timed out (".concat(o._options.imageTimeout,"ms) loading image"))},o._options.imageTimeout)})];case 6:return[2,a.sent()]}})})},A.prototype.has=function(e){return typeof this._cache[e]<"u"},A.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},A.prototype.proxy=function(e){var t=this,n=this._options.proxy;if(!n)throw new Error("No proxy defined");var i=e.substring(0,256);return new Promise(function(r,s){var o=_e.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(a.status===200)if(o==="text")r(a.response);else{var l=new FileReader;l.addEventListener("load",function(){return r(l.result)},!1),l.addEventListener("error",function(d){return s(d)},!1),l.readAsDataURL(a.response)}else s("Failed to proxy resource ".concat(i," with status code ").concat(a.status))},a.onerror=s;var c=n.indexOf("?")>-1?"&":"?";if(a.open("GET","".concat(n).concat(c,"url=").concat(encodeURIComponent(e),"&responseType=").concat(o)),o!=="text"&&a instanceof XMLHttpRequest&&(a.responseType=o),t._options.imageTimeout){var u=t._options.imageTimeout;a.timeout=u,a.ontimeout=function(){return s("Timed out (".concat(u,"ms) proxying ").concat(i))}}a.send()})},A}(),OU=/^data:image\/svg\+xml/i,HU=/^data:image\/.*;base64,/i,MU=/^data:image\/.*/i,NU=function(A){return _e.SUPPORT_SVG_DRAWING||!GU(A)},Mc=function(A){return MU.test(A)},KU=function(A){return HU.test(A)},Nc=function(A){return A.substr(0,4)==="blob"},GU=function(A){return A.substr(-3).toLowerCase()==="svg"||OU.test(A)},R=function(){function A(e,t){this.type=0,this.x=e,this.y=t}return A.prototype.add=function(e,t){return new A(this.x+e,this.y+t)},A}(),Pn=function(A,e,t){return new R(A.x+(e.x-A.x)*t,A.y+(e.y-A.y)*t)},xs=function(){function A(e,t,n,i){this.type=1,this.start=e,this.startControl=t,this.endControl=n,this.end=i}return A.prototype.subdivide=function(e,t){var n=Pn(this.start,this.startControl,e),i=Pn(this.startControl,this.endControl,e),r=Pn(this.endControl,this.end,e),s=Pn(n,i,e),o=Pn(i,r,e),a=Pn(s,o,e);return t?new A(this.start,n,s,a):new A(a,o,r,this.end)},A.prototype.add=function(e,t){return new A(this.start.add(e,t),this.startControl.add(e,t),this.endControl.add(e,t),this.end.add(e,t))},A.prototype.reverse=function(){return new A(this.end,this.endControl,this.startControl,this.start)},A}(),ut=function(A){return A.type===1},VU=function(){function A(e){var t=e.styles,n=e.bounds,i=Ui(t.borderTopLeftRadius,n.width,n.height),r=i[0],s=i[1],o=Ui(t.borderTopRightRadius,n.width,n.height),a=o[0],c=o[1],u=Ui(t.borderBottomRightRadius,n.width,n.height),l=u[0],d=u[1],h=Ui(t.borderBottomLeftRadius,n.width,n.height),f=h[0],g=h[1],p=[];p.push((r+a)/n.width),p.push((f+l)/n.width),p.push((s+g)/n.height),p.push((c+d)/n.height);var B=Math.max.apply(Math,p);B>1&&(r/=B,s/=B,a/=B,c/=B,l/=B,d/=B,f/=B,g/=B);var y=n.width-a,b=n.height-d,v=n.width-l,C=n.height-g,w=t.borderTopWidth,S=t.borderRightWidth,F=t.borderBottomWidth,_=t.borderLeftWidth,D=ne(t.paddingTop,e.bounds.width),O=ne(t.paddingRight,e.bounds.width),M=ne(t.paddingBottom,e.bounds.width),K=ne(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||s>0?le(n.left+_/3,n.top+w/3,r-_/3,s-w/3,te.TOP_LEFT):new R(n.left+_/3,n.top+w/3),this.topRightBorderDoubleOuterBox=r>0||s>0?le(n.left+y,n.top+w/3,a-S/3,c-w/3,te.TOP_RIGHT):new R(n.left+n.width-S/3,n.top+w/3),this.bottomRightBorderDoubleOuterBox=l>0||d>0?le(n.left+v,n.top+b,l-S/3,d-F/3,te.BOTTOM_RIGHT):new R(n.left+n.width-S/3,n.top+n.height-F/3),this.bottomLeftBorderDoubleOuterBox=f>0||g>0?le(n.left+_/3,n.top+C,f-_/3,g-F/3,te.BOTTOM_LEFT):new R(n.left+_/3,n.top+n.height-F/3),this.topLeftBorderDoubleInnerBox=r>0||s>0?le(n.left+_*2/3,n.top+w*2/3,r-_*2/3,s-w*2/3,te.TOP_LEFT):new R(n.left+_*2/3,n.top+w*2/3),this.topRightBorderDoubleInnerBox=r>0||s>0?le(n.left+y,n.top+w*2/3,a-S*2/3,c-w*2/3,te.TOP_RIGHT):new R(n.left+n.width-S*2/3,n.top+w*2/3),this.bottomRightBorderDoubleInnerBox=l>0||d>0?le(n.left+v,n.top+b,l-S*2/3,d-F*2/3,te.BOTTOM_RIGHT):new R(n.left+n.width-S*2/3,n.top+n.height-F*2/3),this.bottomLeftBorderDoubleInnerBox=f>0||g>0?le(n.left+_*2/3,n.top+C,f-_*2/3,g-F*2/3,te.BOTTOM_LEFT):new R(n.left+_*2/3,n.top+n.height-F*2/3),this.topLeftBorderStroke=r>0||s>0?le(n.left+_/2,n.top+w/2,r-_/2,s-w/2,te.TOP_LEFT):new R(n.left+_/2,n.top+w/2),this.topRightBorderStroke=r>0||s>0?le(n.left+y,n.top+w/2,a-S/2,c-w/2,te.TOP_RIGHT):new R(n.left+n.width-S/2,n.top+w/2),this.bottomRightBorderStroke=l>0||d>0?le(n.left+v,n.top+b,l-S/2,d-F/2,te.BOTTOM_RIGHT):new R(n.left+n.width-S/2,n.top+n.height-F/2),this.bottomLeftBorderStroke=f>0||g>0?le(n.left+_/2,n.top+C,f-_/2,g-F/2,te.BOTTOM_LEFT):new R(n.left+_/2,n.top+n.height-F/2),this.topLeftBorderBox=r>0||s>0?le(n.left,n.top,r,s,te.TOP_LEFT):new R(n.left,n.top),this.topRightBorderBox=a>0||c>0?le(n.left+y,n.top,a,c,te.TOP_RIGHT):new R(n.left+n.width,n.top),this.bottomRightBorderBox=l>0||d>0?le(n.left+v,n.top+b,l,d,te.BOTTOM_RIGHT):new R(n.left+n.width,n.top+n.height),this.bottomLeftBorderBox=f>0||g>0?le(n.left,n.top+C,f,g,te.BOTTOM_LEFT):new R(n.left,n.top+n.height),this.topLeftPaddingBox=r>0||s>0?le(n.left+_,n.top+w,Math.max(0,r-_),Math.max(0,s-w),te.TOP_LEFT):new R(n.left+_,n.top+w),this.topRightPaddingBox=a>0||c>0?le(n.left+Math.min(y,n.width-S),n.top+w,y>n.width+S?0:Math.max(0,a-S),Math.max(0,c-w),te.TOP_RIGHT):new R(n.left+n.width-S,n.top+w),this.bottomRightPaddingBox=l>0||d>0?le(n.left+Math.min(v,n.width-_),n.top+Math.min(b,n.height-F),Math.max(0,l-S),Math.max(0,d-F),te.BOTTOM_RIGHT):new R(n.left+n.width-S,n.top+n.height-F),this.bottomLeftPaddingBox=f>0||g>0?le(n.left+_,n.top+Math.min(C,n.height-F),Math.max(0,f-_),Math.max(0,g-F),te.BOTTOM_LEFT):new R(n.left+_,n.top+n.height-F),this.topLeftContentBox=r>0||s>0?le(n.left+_+K,n.top+w+D,Math.max(0,r-(_+K)),Math.max(0,s-(w+D)),te.TOP_LEFT):new R(n.left+_+K,n.top+w+D),this.topRightContentBox=a>0||c>0?le(n.left+Math.min(y,n.width+_+K),n.top+w+D,y>n.width+_+K?0:a-_+K,c-(w+D),te.TOP_RIGHT):new R(n.left+n.width-(S+O),n.top+w+D),this.bottomRightContentBox=l>0||d>0?le(n.left+Math.min(v,n.width-(_+K)),n.top+Math.min(b,n.height+w+D),Math.max(0,l-(S+O)),d-(F+M),te.BOTTOM_RIGHT):new R(n.left+n.width-(S+O),n.top+n.height-(F+M)),this.bottomLeftContentBox=f>0||g>0?le(n.left+_+K,n.top+C,Math.max(0,f-(_+K)),g-(F+M),te.BOTTOM_LEFT):new R(n.left+_+K,n.top+n.height-(F+M))}return A}(),te;(function(A){A[A.TOP_LEFT=0]="TOP_LEFT",A[A.TOP_RIGHT=1]="TOP_RIGHT",A[A.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",A[A.BOTTOM_LEFT=3]="BOTTOM_LEFT"})(te||(te={}));var le=function(A,e,t,n,i){var r=4*((Math.sqrt(2)-1)/3),s=t*r,o=n*r,a=A+t,c=e+n;switch(i){case te.TOP_LEFT:return new xs(new R(A,c),new R(A,c-o),new R(a-s,e),new R(a,e));case te.TOP_RIGHT:return new xs(new R(A,e),new R(A+s,e),new R(a,c-o),new R(a,c));case te.BOTTOM_RIGHT:return new xs(new R(a,e),new R(a,e+o),new R(A+s,c),new R(A,c));case te.BOTTOM_LEFT:default:return new xs(new R(a,c),new R(a-s,c),new R(A,e+o),new R(A,e))}},Rs=function(A){return[A.topLeftBorderBox,A.topRightBorderBox,A.bottomRightBorderBox,A.bottomLeftBorderBox]},jU=function(A){return[A.topLeftContentBox,A.topRightContentBox,A.bottomRightContentBox,A.bottomLeftContentBox]},Ps=function(A){return[A.topLeftPaddingBox,A.topRightPaddingBox,A.bottomRightPaddingBox,A.bottomLeftPaddingBox]},$U=function(){function A(e,t,n){this.offsetX=e,this.offsetY=t,this.matrix=n,this.type=0,this.target=6}return A}(),Ds=function(){function A(e,t){this.path=e,this.target=t,this.type=1}return A}(),WU=function(){function A(e){this.opacity=e,this.type=2,this.target=6}return A}(),JU=function(A){return A.type===0},Lg=function(A){return A.type===1},XU=function(A){return A.type===2},Og=function(A,e){return A.length===e.length?A.some(function(t,n){return t===e[n]}):!1},qU=function(A,e,t,n,i){return A.map(function(r,s){switch(s){case 0:return r.add(e,t);case 1:return r.add(e+n,t);case 2:return r.add(e+n,t+i);case 3:return r.add(e,t+i)}return r})},Hg=function(){function A(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]}return A}(),Mg=function(){function A(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new VU(this.container),this.container.styles.opacity<1&&this.effects.push(new WU(this.container.styles.opacity)),this.container.styles.transform!==null){var n=this.container.bounds.left+this.container.styles.transformOrigin[0].number,i=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new $U(n,i,r))}if(this.container.styles.overflowX!==0){var s=Rs(this.curves),o=Ps(this.curves);Og(s,o)?this.effects.push(new Ds(s,6)):(this.effects.push(new Ds(s,2)),this.effects.push(new Ds(o,4)))}}return A.prototype.getEffects=function(e){for(var t=[2,3].indexOf(this.container.styles.position)===-1,n=this.parent,i=this.effects.slice(0);n;){var r=n.effects.filter(function(a){return!Lg(a)});if(t||n.container.styles.position!==0||!n.parent){if(t=[2,3].indexOf(n.container.styles.position)===-1,n.container.styles.overflowX!==0){var s=Rs(n.curves),o=Ps(n.curves);Og(s,o)||i.unshift(new Ds(o,6))}i.unshift.apply(i,r)}else i.unshift.apply(i,r);n=n.parent}return i.filter(function(a){return be(a.target,e)})},A}(),Kc=function(A,e,t,n){A.container.elements.forEach(function(i){var r=be(i.flags,4),s=be(i.flags,2),o=new Mg(i,A);be(i.styles.display,2048)&&n.push(o);var a=be(i.flags,8)?[]:n;if(r||s){var c=r||i.styles.isPositioned()?t:e,u=new Hg(o);if(i.styles.isPositioned()||i.styles.opacity<1||i.styles.isTransformed()){var l=i.styles.zIndex.order;if(l<0){var d=0;c.negativeZIndex.some(function(f,g){return l>f.element.container.styles.zIndex.order?(d=g,!1):d>0}),c.negativeZIndex.splice(d,0,u)}else if(l>0){var h=0;c.positiveZIndex.some(function(f,g){return l>=f.element.container.styles.zIndex.order?(h=g+1,!1):h>0}),c.positiveZIndex.splice(h,0,u)}else c.zeroOrAutoZIndexOrTransformedOrOpacity.push(u)}else i.styles.isFloating()?c.nonPositionedFloats.push(u):c.nonPositionedInlineLevel.push(u);Kc(o,u,r?u:t,a)}else i.styles.isInlineLevel()?e.inlineLevel.push(o):e.nonInlineLevel.push(o),Kc(o,e,t,a);be(i.flags,8)&&Ng(i,a)})},Ng=function(A,e){for(var t=A instanceof kc?A.start:1,n=A instanceof kc?A.reversed:!1,i=0;i<e.length;i++){var r=e[i];r.container instanceof hg&&typeof r.container.value=="number"&&r.container.value!==0&&(t=r.container.value),r.listValue=_i(t,r.container.styles.listStyleType,!0),t+=n?-1:1}},YU=function(A){var e=new Mg(A,null),t=new Hg(e),n=[];return Kc(e,t,t,n),Ng(e.container,n),t},Kg=function(A,e){switch(e){case 0:return lt(A.topLeftBorderBox,A.topLeftPaddingBox,A.topRightBorderBox,A.topRightPaddingBox);case 1:return lt(A.topRightBorderBox,A.topRightPaddingBox,A.bottomRightBorderBox,A.bottomRightPaddingBox);case 2:return lt(A.bottomRightBorderBox,A.bottomRightPaddingBox,A.bottomLeftBorderBox,A.bottomLeftPaddingBox);case 3:default:return lt(A.bottomLeftBorderBox,A.bottomLeftPaddingBox,A.topLeftBorderBox,A.topLeftPaddingBox)}},zU=function(A,e){switch(e){case 0:return lt(A.topLeftBorderBox,A.topLeftBorderDoubleOuterBox,A.topRightBorderBox,A.topRightBorderDoubleOuterBox);case 1:return lt(A.topRightBorderBox,A.topRightBorderDoubleOuterBox,A.bottomRightBorderBox,A.bottomRightBorderDoubleOuterBox);case 2:return lt(A.bottomRightBorderBox,A.bottomRightBorderDoubleOuterBox,A.bottomLeftBorderBox,A.bottomLeftBorderDoubleOuterBox);case 3:default:return lt(A.bottomLeftBorderBox,A.bottomLeftBorderDoubleOuterBox,A.topLeftBorderBox,A.topLeftBorderDoubleOuterBox)}},ZU=function(A,e){switch(e){case 0:return lt(A.topLeftBorderDoubleInnerBox,A.topLeftPaddingBox,A.topRightBorderDoubleInnerBox,A.topRightPaddingBox);case 1:return lt(A.topRightBorderDoubleInnerBox,A.topRightPaddingBox,A.bottomRightBorderDoubleInnerBox,A.bottomRightPaddingBox);case 2:return lt(A.bottomRightBorderDoubleInnerBox,A.bottomRightPaddingBox,A.bottomLeftBorderDoubleInnerBox,A.bottomLeftPaddingBox);case 3:default:return lt(A.bottomLeftBorderDoubleInnerBox,A.bottomLeftPaddingBox,A.topLeftBorderDoubleInnerBox,A.topLeftPaddingBox)}},eT=function(A,e){switch(e){case 0:return Ls(A.topLeftBorderStroke,A.topRightBorderStroke);case 1:return Ls(A.topRightBorderStroke,A.bottomRightBorderStroke);case 2:return Ls(A.bottomRightBorderStroke,A.bottomLeftBorderStroke);case 3:default:return Ls(A.bottomLeftBorderStroke,A.topLeftBorderStroke)}},Ls=function(A,e){var t=[];return ut(A)?t.push(A.subdivide(.5,!1)):t.push(A),ut(e)?t.push(e.subdivide(.5,!0)):t.push(e),t},lt=function(A,e,t,n){var i=[];return ut(A)?i.push(A.subdivide(.5,!1)):i.push(A),ut(t)?i.push(t.subdivide(.5,!0)):i.push(t),ut(n)?i.push(n.subdivide(.5,!0).reverse()):i.push(n),ut(e)?i.push(e.subdivide(.5,!1).reverse()):i.push(e),i},Gg=function(A){var e=A.bounds,t=A.styles;return e.add(t.borderLeftWidth,t.borderTopWidth,-(t.borderRightWidth+t.borderLeftWidth),-(t.borderTopWidth+t.borderBottomWidth))},Os=function(A){var e=A.styles,t=A.bounds,n=ne(e.paddingLeft,t.width),i=ne(e.paddingRight,t.width),r=ne(e.paddingTop,t.width),s=ne(e.paddingBottom,t.width);return t.add(n+e.borderLeftWidth,r+e.borderTopWidth,-(e.borderRightWidth+e.borderLeftWidth+n+i),-(e.borderTopWidth+e.borderBottomWidth+r+s))},tT=function(A,e){return A===0?e.bounds:A===2?Os(e):Gg(e)},AT=function(A,e){return A===0?e.bounds:A===2?Os(e):Gg(e)},Gc=function(A,e,t){var n=tT(Ln(A.styles.backgroundOrigin,e),A),i=AT(Ln(A.styles.backgroundClip,e),A),r=nT(Ln(A.styles.backgroundSize,e),t,n),s=r[0],o=r[1],a=Ui(Ln(A.styles.backgroundPosition,e),n.width-s,n.height-o),c=iT(Ln(A.styles.backgroundRepeat,e),a,r,n,i),u=Math.round(n.left+a[0]),l=Math.round(n.top+a[1]);return s=Math.max(1,s),o=Math.max(1,o),[c,u,l,s,o]},Dn=function(A){return $(A)&&A.value===In.AUTO},Hs=function(A){return typeof A=="number"},nT=function(A,e,t){var n=e[0],i=e[1],r=e[2],s=A[0],o=A[1];if(!s)return[0,0];if(ce(s)&&o&&ce(o))return[ne(s,t.width),ne(o,t.height)];var a=Hs(r);if($(s)&&(s.value===In.CONTAIN||s.value===In.COVER)){if(Hs(r)){var c=t.width/t.height;return c<r!=(s.value===In.COVER)?[t.width,t.width/r]:[t.height*r,t.height]}return[t.width,t.height]}var u=Hs(n),l=Hs(i),d=u||l;if(Dn(s)&&(!o||Dn(o))){if(u&&l)return[n,i];if(!a&&!d)return[t.width,t.height];if(d&&a){var h=u?n:i*r,f=l?i:n/r;return[h,f]}var g=u?n:t.width,p=l?i:t.height;return[g,p]}if(a){var B=0,y=0;return ce(s)?B=ne(s,t.width):ce(o)&&(y=ne(o,t.height)),Dn(s)?B=y*r:(!o||Dn(o))&&(y=B/r),[B,y]}var b=null,v=null;if(ce(s)?b=ne(s,t.width):o&&ce(o)&&(v=ne(o,t.height)),b!==null&&(!o||Dn(o))&&(v=u&&l?b/n*i:t.height),v!==null&&Dn(s)&&(b=u&&l?v/i*n:t.width),b!==null&&v!==null)return[b,v];throw new Error("Unable to calculate background-size for element")},Ln=function(A,e){var t=A[e];return typeof t>"u"?A[0]:t},iT=function(A,e,t,n,i){var r=e[0],s=e[1],o=t[0],a=t[1];switch(A){case 2:return[new R(Math.round(n.left),Math.round(n.top+s)),new R(Math.round(n.left+n.width),Math.round(n.top+s)),new R(Math.round(n.left+n.width),Math.round(a+n.top+s)),new R(Math.round(n.left),Math.round(a+n.top+s))];case 3:return[new R(Math.round(n.left+r),Math.round(n.top)),new R(Math.round(n.left+r+o),Math.round(n.top)),new R(Math.round(n.left+r+o),Math.round(n.height+n.top)),new R(Math.round(n.left+r),Math.round(n.height+n.top))];case 1:return[new R(Math.round(n.left+r),Math.round(n.top+s)),new R(Math.round(n.left+r+o),Math.round(n.top+s)),new R(Math.round(n.left+r+o),Math.round(n.top+s+a)),new R(Math.round(n.left+r),Math.round(n.top+s+a))];default:return[new R(Math.round(i.left),Math.round(i.top)),new R(Math.round(i.left+i.width),Math.round(i.top)),new R(Math.round(i.left+i.width),Math.round(i.height+i.top)),new R(Math.round(i.left),Math.round(i.height+i.top))]}},rT="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",Vg="Hidden Text",sT=function(){function A(e){this._data={},this._document=e}return A.prototype.parseMetrics=function(e,t){var n=this._document.createElement("div"),i=this._document.createElement("img"),r=this._document.createElement("span"),s=this._document.body;n.style.visibility="hidden",n.style.fontFamily=e,n.style.fontSize=t,n.style.margin="0",n.style.padding="0",n.style.whiteSpace="nowrap",s.appendChild(n),i.src=rT,i.width=1,i.height=1,i.style.margin="0",i.style.padding="0",i.style.verticalAlign="baseline",r.style.fontFamily=e,r.style.fontSize=t,r.style.margin="0",r.style.padding="0",r.appendChild(this._document.createTextNode(Vg)),n.appendChild(r),n.appendChild(i);var o=i.offsetTop-r.offsetTop+2;n.removeChild(r),n.appendChild(this._document.createTextNode(Vg)),n.style.lineHeight="normal",i.style.verticalAlign="super";var a=i.offsetTop-n.offsetTop+2;return s.removeChild(n),{baseline:o,middle:a}},A.prototype.getMetrics=function(e,t){var n="".concat(e," ").concat(t);return typeof this._data[n]>"u"&&(this._data[n]=this.parseMetrics(e,t)),this._data[n]},A}(),jg=function(){function A(e,t){this.context=e,this.options=t}return A}(),oT=1e4,aT=function(A){St(e,A);function e(t,n){var i=A.call(this,t,n)||this;return i._activeEffects=[],i.canvas=n.canvas?n.canvas:document.createElement("canvas"),i.ctx=i.canvas.getContext("2d"),n.canvas||(i.canvas.width=Math.floor(n.width*n.scale),i.canvas.height=Math.floor(n.height*n.scale),i.canvas.style.width="".concat(n.width,"px"),i.canvas.style.height="".concat(n.height,"px")),i.fontMetrics=new sT(document),i.ctx.scale(i.options.scale,i.options.scale),i.ctx.translate(-n.x,-n.y),i.ctx.textBaseline="bottom",i._activeEffects=[],i.context.logger.debug("Canvas renderer initialized (".concat(n.width,"x").concat(n.height,") with scale ").concat(n.scale)),i}return e.prototype.applyEffects=function(t){for(var n=this;this._activeEffects.length;)this.popEffect();t.forEach(function(i){return n.applyEffect(i)})},e.prototype.applyEffect=function(t){this.ctx.save(),XU(t)&&(this.ctx.globalAlpha=t.opacity),JU(t)&&(this.ctx.translate(t.offsetX,t.offsetY),this.ctx.transform(t.matrix[0],t.matrix[1],t.matrix[2],t.matrix[3],t.matrix[4],t.matrix[5]),this.ctx.translate(-t.offsetX,-t.offsetY)),Lg(t)&&(this.path(t.path),this.ctx.clip()),this._activeEffects.push(t)},e.prototype.popEffect=function(){this._activeEffects.pop(),this.ctx.restore()},e.prototype.renderStack=function(t){return Me(this,void 0,void 0,function(){var n;return Le(this,function(i){switch(i.label){case 0:return n=t.element.container.styles,n.isVisible()?[4,this.renderStackContent(t)]:[3,2];case 1:i.sent(),i.label=2;case 2:return[2]}})})},e.prototype.renderNode=function(t){return Me(this,void 0,void 0,function(){return Le(this,function(n){switch(n.label){case 0:if(be(t.container.flags,16))debugger;return t.container.styles.isVisible()?[4,this.renderNodeBackgroundAndBorders(t)]:[3,3];case 1:return n.sent(),[4,this.renderNodeContent(t)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.renderTextWithLetterSpacing=function(t,n,i){var r=this;if(n===0)navigator.userAgent.indexOf("Firefox")===-1?(this.ctx.textBaseline="ideographic",this.ctx.fillText(t.text,t.bounds.left,t.bounds.top+t.bounds.height)):this.ctx.fillText(t.text,t.bounds.left,t.bounds.top+i);else{var s=Fc(t.text);s.reduce(function(o,a){return r.ctx.fillText(a,o,t.bounds.top+i),o+r.ctx.measureText(a).width},t.bounds.left)}},e.prototype.createFontStyle=function(t){var n=t.fontVariant.filter(function(s){return s==="normal"||s==="small-caps"}).join(""),i=hT(t.fontFamily).join(", "),r=bA(t.fontSize)?"".concat(t.fontSize.number).concat(t.fontSize.unit):"".concat(t.fontSize.number,"px");return[[t.fontStyle,n,t.fontWeight,r,i].join(" "),i,r]},e.prototype.renderTextNode=function(t,n){return Me(this,void 0,void 0,function(){var i,r,s=this;return Le(this,function(o){return i=this.createFontStyle(n)[0],this.ctx.font=i,this.ctx.direction=n.direction===1?"rtl":"ltr",this.ctx.textAlign="left",this.ctx.textBaseline="alphabetic",r=n.paintOrder,t.textBounds.forEach(function(a){r.forEach(function(c){switch(c){case 0:s.ctx.fillStyle=Ue(n.color),s.renderTextWithLetterSpacing(a,n.letterSpacing,n.fontSize.number);var u=n.textShadow;if(u.length&&a.text.trim().length&&(u.slice(0).reverse().forEach(function(d){s.ctx.shadowColor=Ue(d.color),s.ctx.shadowOffsetX=d.offsetX.number*s.options.scale,s.ctx.shadowOffsetY=d.offsetY.number*s.options.scale,s.ctx.shadowBlur=d.blur.number,s.renderTextWithLetterSpacing(a,n.letterSpacing,n.fontSize.number)}),s.ctx.shadowColor="",s.ctx.shadowOffsetX=0,s.ctx.shadowOffsetY=0,s.ctx.shadowBlur=0),n.textDecorationLine.length){s.ctx.fillStyle=Ue(n.textDecorationColor||n.color);var l=1;n.textDecorationLine.forEach(function(d){switch(d){case 1:s.ctx.fillRect(a.bounds.left,a.bounds.top+a.bounds.height-l,a.bounds.width,l);break;case 2:s.ctx.fillRect(a.bounds.left,a.bounds.top,a.bounds.width,l);break;case 3:s.ctx.fillRect(a.bounds.left,a.bounds.top+(a.bounds.height/2-l/2),a.bounds.width,l);break}})}break;case 1:n.webkitTextStrokeWidth&&a.text.trim().length&&(s.ctx.strokeStyle=Ue(n.webkitTextStrokeColor),s.ctx.lineWidth=n.webkitTextStrokeWidth,s.ctx.lineJoin=window.chrome?"miter":"round",s.ctx.strokeText(a.text,a.bounds.left,a.bounds.top+a.bounds.height)),s.ctx.strokeStyle="",s.ctx.lineWidth=0,s.ctx.lineJoin="miter";break}})}),[2]})})},e.prototype.renderReplacedElement=function(t,n,i){var r=i.naturalWidth||t.intrinsicWidth,s=i.naturalHeight||t.intrinsicHeight;if(i&&r>0&&s>0){var o=Os(t),a=Ps(n);this.path(a),this.ctx.save(),this.ctx.clip();var c=0,u=0,l=r,d=s,h=o.left,f=o.top,g=o.width,p=o.height,B=t.styles.objectFit,y=g/p,b=l/d;if(B===2)b>y?(p=g/b,f+=(o.height-p)/2):(g=p*b,h+=(o.width-g)/2);else if(B===4)b>y?(l=d*y,c+=(r-l)/2):(d=l/y,u+=(s-d)/2);else if(B===8)l>g?(c+=(l-g)/2,l=g):(h+=(g-l)/2,g=l),d>p?(u+=(d-p)/2,d=p):(f+=(p-d)/2,p=d);else if(B===16){var v=b>y?g:p*b,C=l>g?l:g;v<C?b>y?(p=g/b,f+=(o.height-p)/2):(g=p*b,h+=(o.width-g)/2):(l>g?(c+=(l-g)/2,l=g):(h+=(g-l)/2,g=l),d>p?(u+=(d-p)/2,d=p):(f+=(p-d)/2,p=d))}this.ctx.drawImage(i,c,u,l,d,h,f,g,p),this.ctx.restore()}},e.prototype.renderNodeContent=function(t){return Me(this,void 0,void 0,function(){var n,i,r,s,o,a,b,b,c,u,l,d,C,h,f,g,w,p,B,y,b,v,C,w;return Le(this,function(S){switch(S.label){case 0:this.applyEffects(t.getEffects(4)),n=t.container,i=t.curves,r=n.styles,s=0,o=n.textNodes,S.label=1;case 1:return s<o.length?(a=o[s],[4,this.renderTextNode(a,r)]):[3,4];case 2:S.sent(),S.label=3;case 3:return s++,[3,1];case 4:if(!(n instanceof ug))return[3,8];S.label=5;case 5:return S.trys.push([5,7,,8]),[4,this.context.cache.match(n.src)];case 6:return b=S.sent(),this.renderReplacedElement(n,i,b),[3,8];case 7:return S.sent(),this.context.logger.error("Error loading image ".concat(n.src)),[3,8];case 8:if(n instanceof lg&&this.renderReplacedElement(n,i,n.canvas),!(n instanceof dg))return[3,12];S.label=9;case 9:return S.trys.push([9,11,,12]),[4,this.context.cache.match(n.svg)];case 10:return b=S.sent(),this.renderReplacedElement(n,i,b),[3,12];case 11:return S.sent(),this.context.logger.error("Error loading svg ".concat(n.svg.substring(0,255))),[3,12];case 12:return n instanceof mg&&n.tree?(c=new e(this.context,{scale:this.options.scale,backgroundColor:n.backgroundColor,x:0,y:0,width:n.width,height:n.height}),[4,c.render(n.tree)]):[3,14];case 13:u=S.sent(),n.width&&n.height&&this.ctx.drawImage(u,0,0,n.width,n.height,n.bounds.left,n.bounds.top,n.bounds.width,n.bounds.height),S.label=14;case 14:if(n instanceof Ic&&(l=Math.min(n.bounds.width,n.bounds.height),n.type===Ts?n.checked&&(this.ctx.save(),this.path([new R(n.bounds.left+l*.39363,n.bounds.top+l*.79),new R(n.bounds.left+l*.16,n.bounds.top+l*.5549),new R(n.bounds.left+l*.27347,n.bounds.top+l*.44071),new R(n.bounds.left+l*.39694,n.bounds.top+l*.5649),new R(n.bounds.left+l*.72983,n.bounds.top+l*.23),new R(n.bounds.left+l*.84,n.bounds.top+l*.34085),new R(n.bounds.left+l*.39363,n.bounds.top+l*.79)]),this.ctx.fillStyle=Ue(fg),this.ctx.fill(),this.ctx.restore()):n.type===Qs&&n.checked&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(n.bounds.left+l/2,n.bounds.top+l/2,l/4,0,Math.PI*2,!0),this.ctx.fillStyle=Ue(fg),this.ctx.fill(),this.ctx.restore())),cT(n)&&n.value.length){switch(d=this.createFontStyle(r),C=d[0],h=d[1],f=d[2],g=this.fontMetrics.getMetrics(h,f).baseline,this.ctx.font=C,this.ctx.fillStyle=Ue(r.color),this.ctx.textBaseline="alphabetic",this.ctx.textAlign=lT(n.styles.textAlign),w=Os(n),p=0,n.styles.textAlign){case 1:p+=w.width/2;break;case 2:p+=w.width;break}B=w.add(p,0,0,-w.height/2+1),this.ctx.save(),this.path([new R(w.left,w.top),new R(w.left+w.width,w.top),new R(w.left+w.width,w.top+w.height),new R(w.left,w.top+w.height)]),this.ctx.clip(),this.renderTextWithLetterSpacing(new ki(n.value,B),r.letterSpacing,g),this.ctx.restore(),this.ctx.textBaseline="alphabetic",this.ctx.textAlign="left"}if(!be(n.styles.display,2048))return[3,20];if(n.styles.listStyleImage===null)return[3,19];if(y=n.styles.listStyleImage,y.type!==0)return[3,18];b=void 0,v=y.url,S.label=15;case 15:return S.trys.push([15,17,,18]),[4,this.context.cache.match(v)];case 16:return b=S.sent(),this.ctx.drawImage(b,n.bounds.left-(b.width+10),n.bounds.top),[3,18];case 17:return S.sent(),this.context.logger.error("Error loading list-style-image ".concat(v)),[3,18];case 18:return[3,20];case 19:t.listValue&&n.styles.listStyleType!==-1&&(C=this.createFontStyle(r)[0],this.ctx.font=C,this.ctx.fillStyle=Ue(r.color),this.ctx.textBaseline="middle",this.ctx.textAlign="right",w=new Jt(n.bounds.left,n.bounds.top+ne(n.styles.paddingTop,n.bounds.width),n.bounds.width,jf(r.lineHeight,r.fontSize.number)/2+1),this.renderTextWithLetterSpacing(new ki(t.listValue,w),r.letterSpacing,jf(r.lineHeight,r.fontSize.number)/2+2),this.ctx.textBaseline="bottom",this.ctx.textAlign="left"),S.label=20;case 20:return[2]}})})},e.prototype.renderStackContent=function(t){return Me(this,void 0,void 0,function(){var n,i,B,r,s,B,o,a,B,c,u,B,l,d,B,h,f,B,g,p,B;return Le(this,function(y){switch(y.label){case 0:if(be(t.element.container.flags,16))debugger;return[4,this.renderNodeBackgroundAndBorders(t.element)];case 1:y.sent(),n=0,i=t.negativeZIndex,y.label=2;case 2:return n<i.length?(B=i[n],[4,this.renderStack(B)]):[3,5];case 3:y.sent(),y.label=4;case 4:return n++,[3,2];case 5:return[4,this.renderNodeContent(t.element)];case 6:y.sent(),r=0,s=t.nonInlineLevel,y.label=7;case 7:return r<s.length?(B=s[r],[4,this.renderNode(B)]):[3,10];case 8:y.sent(),y.label=9;case 9:return r++,[3,7];case 10:o=0,a=t.nonPositionedFloats,y.label=11;case 11:return o<a.length?(B=a[o],[4,this.renderStack(B)]):[3,14];case 12:y.sent(),y.label=13;case 13:return o++,[3,11];case 14:c=0,u=t.nonPositionedInlineLevel,y.label=15;case 15:return c<u.length?(B=u[c],[4,this.renderStack(B)]):[3,18];case 16:y.sent(),y.label=17;case 17:return c++,[3,15];case 18:l=0,d=t.inlineLevel,y.label=19;case 19:return l<d.length?(B=d[l],[4,this.renderNode(B)]):[3,22];case 20:y.sent(),y.label=21;case 21:return l++,[3,19];case 22:h=0,f=t.zeroOrAutoZIndexOrTransformedOrOpacity,y.label=23;case 23:return h<f.length?(B=f[h],[4,this.renderStack(B)]):[3,26];case 24:y.sent(),y.label=25;case 25:return h++,[3,23];case 26:g=0,p=t.positiveZIndex,y.label=27;case 27:return g<p.length?(B=p[g],[4,this.renderStack(B)]):[3,30];case 28:y.sent(),y.label=29;case 29:return g++,[3,27];case 30:return[2]}})})},e.prototype.mask=function(t){this.ctx.beginPath(),this.ctx.moveTo(0,0),this.ctx.lineTo(this.canvas.width,0),this.ctx.lineTo(this.canvas.width,this.canvas.height),this.ctx.lineTo(0,this.canvas.height),this.ctx.lineTo(0,0),this.formatPath(t.slice(0).reverse()),this.ctx.closePath()},e.prototype.path=function(t){this.ctx.beginPath(),this.formatPath(t),this.ctx.closePath()},e.prototype.formatPath=function(t){var n=this;t.forEach(function(i,r){var s=ut(i)?i.start:i;r===0?n.ctx.moveTo(s.x,s.y):n.ctx.lineTo(s.x,s.y),ut(i)&&n.ctx.bezierCurveTo(i.startControl.x,i.startControl.y,i.endControl.x,i.endControl.y,i.end.x,i.end.y)})},e.prototype.renderRepeat=function(t,n,i,r){this.path(t),this.ctx.fillStyle=n,this.ctx.translate(i,r),this.ctx.fill(),this.ctx.translate(-i,-r)},e.prototype.resizeImage=function(t,n,i){var r,s=(r=this.canvas.ownerDocument)!==null&&r!==void 0?r:document,o=s.createElement("canvas");o.width=Math.max(1,n),o.height=Math.max(1,i);var a=o.getContext("2d");return a.drawImage(t,0,0,t.width,t.height,0,0,n,i),o},e.prototype.renderBackgroundImage=function(t){return Me(this,void 0,void 0,function(){var n,i,r,s,o,a;return Le(this,function(c){switch(c.label){case 0:n=t.styles.backgroundImage.length-1,i=function(u){var l,d,h,f,g,M,He,De,G,q,D,p,M,He,De,G,q,B,y,b,v,C,w,S,F,_,D,O,M,K,Pe,G,q,et,He,De,AA,ft,Ge,nA,Ft,Ve,Jn,gt;return Le(this,function(Xn){switch(Xn.label){case 0:if(u.type!==0)return[3,5];l=void 0,d=u.url,Xn.label=1;case 1:return Xn.trys.push([1,3,,4]),[4,r.context.cache.match(d)];case 2:return l=Xn.sent(),[3,4];case 3:return Xn.sent(),r.context.logger.error("Error loading background-image ".concat(d)),[3,4];case 4:return l&&(h=isNaN(l.width)||l.width===0?1:l.width,f=isNaN(l.height)||l.height===0?1:l.height,g=Gc(t,n,[h,f,h/f]),M=g[0],He=g[1],De=g[2],G=g[3],q=g[4],D=r.ctx.createPattern(r.resizeImage(l,G,q),"repeat"),r.renderRepeat(M,D,He,De)),[3,6];case 5:jb(u)?(p=Gc(t,n,[null,null,null]),M=p[0],He=p[1],De=p[2],G=p[3],q=p[4],B=Mb(u.angle,G,q),y=B[0],b=B[1],v=B[2],C=B[3],w=B[4],S=document.createElement("canvas"),S.width=G,S.height=q,F=S.getContext("2d"),_=F.createLinearGradient(b,C,v,w),Rf(u.stops,y||1).forEach(function(zi){return _.addColorStop(zi.stop,Ue(zi.color))}),F.fillStyle=_,F.fillRect(0,0,G,q),G>0&&q>0&&(D=r.ctx.createPattern(S,"repeat"),r.renderRepeat(M,D,He,De))):$b(u)&&(O=Gc(t,n,[null,null,null]),M=O[0],K=O[1],Pe=O[2],G=O[3],q=O[4],et=u.position.length===0?[uc]:u.position,He=ne(et[0],G),De=ne(et[et.length-1],q),AA=Nb(u,He,De,G,q),ft=AA[0],Ge=AA[1],ft>0&&Ge>0&&(nA=r.ctx.createRadialGradient(K+He,Pe+De,0,K+He,Pe+De,ft),Rf(u.stops,ft*2).forEach(function(zi){return nA.addColorStop(zi.stop,Ue(zi.color))}),r.path(M),r.ctx.fillStyle=nA,ft!==Ge?(Ft=t.bounds.left+.5*t.bounds.width,Ve=t.bounds.top+.5*t.bounds.height,Jn=Ge/ft,gt=1/Jn,r.ctx.save(),r.ctx.translate(Ft,Ve),r.ctx.transform(1,0,0,Jn,0,0),r.ctx.translate(-Ft,-Ve),r.ctx.fillRect(K,gt*(Pe-Ve)+Ve,G,q*gt),r.ctx.restore()):r.ctx.fill())),Xn.label=6;case 6:return n--,[2]}})},r=this,s=0,o=t.styles.backgroundImage.slice(0).reverse(),c.label=1;case 1:return s<o.length?(a=o[s],[5,i(a)]):[3,4];case 2:c.sent(),c.label=3;case 3:return s++,[3,1];case 4:return[2]}})})},e.prototype.renderSolidBorder=function(t,n,i){return Me(this,void 0,void 0,function(){return Le(this,function(r){return this.path(Kg(i,n)),this.ctx.fillStyle=Ue(t),this.ctx.fill(),[2]})})},e.prototype.renderDoubleBorder=function(t,n,i,r){return Me(this,void 0,void 0,function(){var s,o;return Le(this,function(a){switch(a.label){case 0:return n<3?[4,this.renderSolidBorder(t,i,r)]:[3,2];case 1:return a.sent(),[2];case 2:return s=zU(r,i),this.path(s),this.ctx.fillStyle=Ue(t),this.ctx.fill(),o=ZU(r,i),this.path(o),this.ctx.fill(),[2]}})})},e.prototype.renderNodeBackgroundAndBorders=function(t){return Me(this,void 0,void 0,function(){var n,i,r,s,o,a,c,u,l=this;return Le(this,function(d){switch(d.label){case 0:return this.applyEffects(t.getEffects(2)),n=t.container.styles,i=!UA(n.backgroundColor)||n.backgroundImage.length,r=[{style:n.borderTopStyle,color:n.borderTopColor,width:n.borderTopWidth},{style:n.borderRightStyle,color:n.borderRightColor,width:n.borderRightWidth},{style:n.borderBottomStyle,color:n.borderBottomColor,width:n.borderBottomWidth},{style:n.borderLeftStyle,color:n.borderLeftColor,width:n.borderLeftWidth}],s=uT(Ln(n.backgroundClip,0),t.curves),i||n.boxShadow.length?(this.ctx.save(),this.path(s),this.ctx.clip(),UA(n.backgroundColor)||(this.ctx.fillStyle=Ue(n.backgroundColor),this.ctx.fill()),[4,this.renderBackgroundImage(t.container)]):[3,2];case 1:d.sent(),this.ctx.restore(),n.boxShadow.slice(0).reverse().forEach(function(h){l.ctx.save();var f=Rs(t.curves),g=h.inset?0:oT,p=qU(f,-g+(h.inset?1:-1)*h.spread.number,(h.inset?1:-1)*h.spread.number,h.spread.number*(h.inset?-2:2),h.spread.number*(h.inset?-2:2));h.inset?(l.path(f),l.ctx.clip(),l.mask(p)):(l.mask(f),l.ctx.clip(),l.path(p)),l.ctx.shadowOffsetX=h.offsetX.number+g,l.ctx.shadowOffsetY=h.offsetY.number,l.ctx.shadowColor=Ue(h.color),l.ctx.shadowBlur=h.blur.number,l.ctx.fillStyle=h.inset?Ue(h.color):"rgba(0,0,0,1)",l.ctx.fill(),l.ctx.restore()}),d.label=2;case 2:o=0,a=0,c=r,d.label=3;case 3:return a<c.length?(u=c[a],u.style!==0&&!UA(u.color)&&u.width>0?u.style!==2?[3,5]:[4,this.renderDashedDottedBorder(u.color,u.width,o,t.curves,2)]:[3,11]):[3,13];case 4:return d.sent(),[3,11];case 5:return u.style!==3?[3,7]:[4,this.renderDashedDottedBorder(u.color,u.width,o,t.curves,3)];case 6:return d.sent(),[3,11];case 7:return u.style!==4?[3,9]:[4,this.renderDoubleBorder(u.color,u.width,o,t.curves)];case 8:return d.sent(),[3,11];case 9:return[4,this.renderSolidBorder(u.color,o,t.curves)];case 10:d.sent(),d.label=11;case 11:o++,d.label=12;case 12:return a++,[3,3];case 13:return[2]}})})},e.prototype.renderDashedDottedBorder=function(t,n,i,r,s){return Me(this,void 0,void 0,function(){var o,a,c,u,l,d,h,f,g,p,B,y,b,v,C,w,C,w;return Le(this,function(S){return this.ctx.save(),o=eT(r,i),a=Kg(r,i),s===2&&(this.path(a),this.ctx.clip()),ut(a[0])?(c=a[0].start.x,u=a[0].start.y):(c=a[0].x,u=a[0].y),ut(a[1])?(l=a[1].end.x,d=a[1].end.y):(l=a[1].x,d=a[1].y),i===0||i===2?h=Math.abs(c-l):h=Math.abs(u-d),this.ctx.beginPath(),s===3?this.formatPath(o):this.formatPath(a.slice(0,2)),f=n<3?n*3:n*2,g=n<3?n*2:n,s===3&&(f=n,g=n),p=!0,h<=f*2?p=!1:h<=f*2+g?(B=h/(2*f+g),f*=B,g*=B):(y=Math.floor((h+g)/(f+g)),b=(h-y*f)/(y-1),v=(h-(y+1)*f)/y,g=v<=0||Math.abs(g-b)<Math.abs(g-v)?b:v),p&&(s===3?this.ctx.setLineDash([0,f+g]):this.ctx.setLineDash([f,g])),s===3?(this.ctx.lineCap="round",this.ctx.lineWidth=n):this.ctx.lineWidth=n*2+1.1,this.ctx.strokeStyle=Ue(t),this.ctx.stroke(),this.ctx.setLineDash([]),s===2&&(ut(a[0])&&(C=a[3],w=a[0],this.ctx.beginPath(),this.formatPath([new R(C.end.x,C.end.y),new R(w.start.x,w.start.y)]),this.ctx.stroke()),ut(a[1])&&(C=a[1],w=a[2],this.ctx.beginPath(),this.formatPath([new R(C.end.x,C.end.y),new R(w.start.x,w.start.y)]),this.ctx.stroke())),this.ctx.restore(),[2]})})},e.prototype.render=function(t){return Me(this,void 0,void 0,function(){var n;return Le(this,function(i){switch(i.label){case 0:return this.options.backgroundColor&&(this.ctx.fillStyle=Ue(this.options.backgroundColor),this.ctx.fillRect(this.options.x,this.options.y,this.options.width,this.options.height)),n=YU(t),[4,this.renderStack(n)];case 1:return i.sent(),this.applyEffects([]),[2,this.canvas]}})})},e}(jg),cT=function(A){return A instanceof pg||A instanceof gg?!0:A instanceof Ic&&A.type!==Qs&&A.type!==Ts},uT=function(A,e){switch(A){case 0:return Rs(e);case 2:return jU(e);case 1:default:return Ps(e)}},lT=function(A){switch(A){case 1:return"center";case 2:return"right";case 0:default:return"left"}},dT=["-apple-system","system-ui"],hT=function(A){return/iPhone OS 15_(0|1)/.test(window.navigator.userAgent)?A.filter(function(e){return dT.indexOf(e)===-1}):A},fT=function(A){St(e,A);function e(t,n){var i=A.call(this,t,n)||this;return i.canvas=n.canvas?n.canvas:document.createElement("canvas"),i.ctx=i.canvas.getContext("2d"),i.options=n,i.canvas.width=Math.floor(n.width*n.scale),i.canvas.height=Math.floor(n.height*n.scale),i.canvas.style.width="".concat(n.width,"px"),i.canvas.style.height="".concat(n.height,"px"),i.ctx.scale(i.options.scale,i.options.scale),i.ctx.translate(-n.x,-n.y),i.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized (".concat(n.width,"x").concat(n.height," at ").concat(n.x,",").concat(n.y,") with scale ").concat(n.scale)),i}return e.prototype.render=function(t){return Me(this,void 0,void 0,function(){var n,i;return Le(this,function(r){switch(r.label){case 0:return n=Qc(this.options.width*this.options.scale,this.options.height*this.options.scale,this.options.scale,this.options.scale,t),[4,gT(n)];case 1:return i=r.sent(),this.options.backgroundColor&&(this.ctx.fillStyle=Ue(this.options.backgroundColor),this.ctx.fillRect(0,0,this.options.width*this.options.scale,this.options.height*this.options.scale)),this.ctx.drawImage(i,-this.options.x*this.options.scale,-this.options.y*this.options.scale),[2,this.canvas]}})})},e}(jg),gT=function(A){return new Promise(function(e,t){var n=new Image;n.onload=function(){e(n)},n.onerror=t,n.src="data:image/svg+xml;charset=utf-8,".concat(encodeURIComponent(new XMLSerializer().serializeToString(A)))})},pT=function(){function A(e){var t=e.id,n=e.enabled;this.id=t,this.enabled=n,this.start=Date.now()}return A.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&(typeof window<"u"&&window.console&&typeof console.debug=="function"?console.debug.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1)):this.info.apply(this,e))},A.prototype.getTime=function(){return Date.now()-this.start},A.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&typeof window<"u"&&window.console&&typeof console.info=="function"&&console.info.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1))},A.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&(typeof window<"u"&&window.console&&typeof console.warn=="function"?console.warn.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1)):this.info.apply(this,e))},A.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.enabled&&(typeof window<"u"&&window.console&&typeof console.error=="function"?console.error.apply(console,Nr([this.id,"".concat(this.getTime(),"ms")],e,!1)):this.info.apply(this,e))},A.instances={},A}(),mT=function(){function A(e,t){var n;this.windowBounds=t,this.instanceName="#".concat(A.instanceCount++),this.logger=new pT({id:this.instanceName,enabled:e.logging}),this.cache=(n=e.cache)!==null&&n!==void 0?n:new LU(this,e)}return A.instanceCount=1,A}(),BT=function(A,e){return e===void 0&&(e={}),vT(A,e)};typeof window<"u"&&Hc.setContext(window);var vT=function(A,e){return Me(void 0,void 0,void 0,function(){var t,n,i,r,s,o,a,c,u,l,d,h,f,g,p,B,y,b,v,C,S,w,S,F,_,D,O,M,K,Pe,G,q,et,He,De,AA,ft,Ge,nA,Ft;return Le(this,function(Ve){switch(Ve.label){case 0:if(!A||typeof A!="object")return[2,Promise.reject("Invalid element provided as first argument")];if(t=A.ownerDocument,!t)throw new Error("Element is not attached to a Document");if(n=t.defaultView,!n)throw new Error("Document is not attached to a Window");return i={allowTaint:(F=e.allowTaint)!==null&&F!==void 0?F:!1,imageTimeout:(_=e.imageTimeout)!==null&&_!==void 0?_:15e3,proxy:e.proxy,useCORS:(D=e.useCORS)!==null&&D!==void 0?D:!1,customIsSameOrigin:e.customIsSameOrigin},r=Ga({logging:(O=e.logging)!==null&&O!==void 0?O:!0,cache:e.cache},i),s={windowWidth:(M=e.windowWidth)!==null&&M!==void 0?M:n.innerWidth,windowHeight:(K=e.windowHeight)!==null&&K!==void 0?K:n.innerHeight,scrollX:(Pe=e.scrollX)!==null&&Pe!==void 0?Pe:n.pageXOffset,scrollY:(G=e.scrollY)!==null&&G!==void 0?G:n.pageYOffset},o=new Jt(s.scrollX,s.scrollY,s.windowWidth,s.windowHeight),a=new mT(r,o),c=(q=e.foreignObjectRendering)!==null&&q!==void 0?q:!1,u={allowTaint:(et=e.allowTaint)!==null&&et!==void 0?et:!1,onclone:e.onclone,ignoreElements:e.ignoreElements,inlineImages:c,copyStyles:c},a.logger.debug("Starting document clone with size ".concat(o.width,"x").concat(o.height," scrolled to ").concat(-o.left,",").concat(-o.top)),l=new Pg(a,A,u),d=l.clonedReferenceElement,d?[4,l.toIFrame(t,o)]:[2,Promise.reject("Unable to find element in cloned iframe")];case 1:return h=Ve.sent(),f=xc(d)||vU(d)?tw(d.ownerDocument):Kr(a,d),g=f.width,p=f.height,B=f.left,y=f.top,b=CT(a,d,e.backgroundColor),v={canvas:e.canvas,backgroundColor:b,scale:(De=(He=e.scale)!==null&&He!==void 0?He:n.devicePixelRatio)!==null&&De!==void 0?De:1,x:((AA=e.x)!==null&&AA!==void 0?AA:0)+B,y:((ft=e.y)!==null&&ft!==void 0?ft:0)+y,width:(Ge=e.width)!==null&&Ge!==void 0?Ge:Math.ceil(g),height:(nA=e.height)!==null&&nA!==void 0?nA:Math.ceil(p)},c?(a.logger.debug("Document cloned, using foreign object rendering"),S=new fT(a,v),[4,S.render(d)]):[3,3];case 2:return C=Ve.sent(),[3,5];case 3:return a.logger.debug("Document cloned, element located at ".concat(B,",").concat(y," with size ").concat(g,"x").concat(p," using computed rendering")),a.logger.debug("Starting DOM parsing"),w=vg(a,d),b===w.styles.backgroundColor&&(w.styles.backgroundColor=Ht.TRANSPARENT),a.logger.debug("Starting renderer for element at ".concat(v.x,",").concat(v.y," with size ").concat(v.width,"x").concat(v.height)),S=new aT(a,v),[4,S.render(w)];case 4:C=Ve.sent(),Ve.label=5;case 5:return(!((Ft=e.removeContainer)!==null&&Ft!==void 0)||Ft)&&(Pg.destroy(h)||a.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore")),a.logger.debug("Finished rendering"),[2,C]}})})},CT=function(A,e,t){var n=e.ownerDocument,i=n.documentElement?kn(A,getComputedStyle(n.documentElement).backgroundColor):Ht.TRANSPARENT,r=n.body?kn(A,getComputedStyle(n.body).backgroundColor):Ht.TRANSPARENT,s=typeof t=="string"?kn(A,t):t===null?Ht.TRANSPARENT:4294967295;return e===n.documentElement?UA(i)?UA(r)?s:r:i:s};const X=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,zA="9.23.0",Ae=globalThis;function Ms(){return Ns(Ae),Ae}function Ns(A){const e=A.__SENTRY__=A.__SENTRY__||{};return e.version=e.version||zA,e[zA]=e[zA]||{}}function Ks(A,e,t=Ae){const n=t.__SENTRY__=t.__SENTRY__||{},i=n[zA]=n[zA]||{};return i[A]||(i[A]=e())}const $g=Object.prototype.toString;function Vc(A){switch($g.call(A)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return IA(A,Error)}}function On(A,e){return $g.call(A)===`[object ${e}]`}function Wg(A){return On(A,"ErrorEvent")}function Jg(A){return On(A,"DOMError")}function wT(A){return On(A,"DOMException")}function Yt(A){return On(A,"String")}function jc(A){return typeof A=="object"&&A!==null&&"__sentry_template_string__"in A&&"__sentry_template_values__"in A}function $c(A){return A===null||jc(A)||typeof A!="object"&&typeof A!="function"}function Ri(A){return On(A,"Object")}function Gs(A){return typeof Event<"u"&&IA(A,Event)}function yT(A){return typeof Element<"u"&&IA(A,Element)}function bT(A){return On(A,"RegExp")}function Vs(A){return!!(A?.then&&typeof A.then=="function")}function ET(A){return Ri(A)&&"nativeEvent"in A&&"preventDefault"in A&&"stopPropagation"in A}function IA(A,e){try{return A instanceof e}catch{return!1}}function Xg(A){return!!(typeof A=="object"&&A!==null&&(A.__isVue||A._isVue))}function ST(A){return typeof Request<"u"&&IA(A,Request)}const Wc=Ae,UT=80;function qg(A,e={}){if(!A)return"<unknown>";try{let t=A;const n=5,i=[];let r=0,s=0;const o=" > ",a=o.length;let c;const u=Array.isArray(e)?e:e.keyAttrs,l=!Array.isArray(e)&&e.maxStringLength||UT;for(;t&&r++<n&&(c=TT(t,u),!(c==="html"||r>1&&s+i.length*a+c.length>=l));)i.push(c),s+=c.length,t=t.parentNode;return i.reverse().join(o)}catch{return"<unknown>"}}function TT(A,e){const t=A,n=[];if(!t?.tagName)return"";if(Wc.HTMLElement&&t instanceof HTMLElement&&t.dataset){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}n.push(t.tagName.toLowerCase());const i=e?.length?e.filter(s=>t.getAttribute(s)).map(s=>[s,t.getAttribute(s)]):null;if(i?.length)i.forEach(s=>{n.push(`[${s[0]}="${s[1]}"]`)});else{t.id&&n.push(`#${t.id}`);const s=t.className;if(s&&Yt(s)){const o=s.split(/\s+/);for(const a of o)n.push(`.${a}`)}}const r=["aria-label","type","name","title","alt"];for(const s of r){const o=t.getAttribute(s);o&&n.push(`[${s}="${o}"]`)}return n.join("")}function Yg(){try{return Wc.document.location.href}catch{return""}}function QT(A){if(!Wc.HTMLElement)return null;let e=A;const t=5;for(let n=0;n<t;n++){if(!e)return null;if(e instanceof HTMLElement){if(e.dataset.sentryComponent)return e.dataset.sentryComponent;if(e.dataset.sentryElement)return e.dataset.sentryElement}e=e.parentNode}return null}const FT="Sentry Logger ",Jc=["debug","info","warn","error","log","assert","trace"],js={};function $s(A){if(!("console"in Ae))return A();const e=Ae.console,t={},n=Object.keys(js);n.forEach(i=>{const r=js[i];t[i]=e[i],e[i]=r});try{return A()}finally{n.forEach(i=>{e[i]=t[i]})}}function kT(){let A=!1;const e={enable:()=>{A=!0},disable:()=>{A=!1},isEnabled:()=>A};return X?Jc.forEach(t=>{e[t]=(...n)=>{A&&$s(()=>{Ae.console[t](`${FT}[${t}]:`,...n)})}}):Jc.forEach(t=>{e[t]=()=>{}}),e}const N=Ks("logger",kT);function Ws(A,e=0){return typeof A!="string"||e===0||A.length<=e?A:`${A.slice(0,e)}...`}function zg(A,e){if(!Array.isArray(A))return"";const t=[];for(let n=0;n<A.length;n++){const i=A[n];try{Xg(i)?t.push("[VueViewModel]"):t.push(String(i))}catch{t.push("[value cannot be serialized]")}}return t.join(e)}function IT(A,e,t=!1){return Yt(A)?bT(e)?e.test(A):Yt(e)?t?A===e:A.includes(e):!1:!1}function Js(A,e=[],t=!1){return e.some(n=>IT(A,n,t))}function it(A,e,t){if(!(e in A))return;const n=A[e];if(typeof n!="function")return;const i=t(n);typeof i=="function"&&Zg(i,n);try{A[e]=i}catch{X&&N.log(`Failed to replace method "${e}" in object`,A)}}function ZA(A,e,t){try{Object.defineProperty(A,e,{value:t,writable:!0,configurable:!0})}catch{X&&N.log(`Failed to add non-enumerable property "${e}" to object`,A)}}function Zg(A,e){try{const t=e.prototype||{};A.prototype=e.prototype=t,ZA(A,"__sentry_original__",e)}catch{}}function Xc(A){return A.__sentry_original__}function ep(A){if(Vc(A))return{message:A.message,name:A.name,stack:A.stack,...Ap(A)};if(Gs(A)){const e={type:A.type,target:tp(A.target),currentTarget:tp(A.currentTarget),...Ap(A)};return typeof CustomEvent<"u"&&IA(A,CustomEvent)&&(e.detail=A.detail),e}else return A}function tp(A){try{return yT(A)?qg(A):Object.prototype.toString.call(A)}catch{return"<unknown>"}}function Ap(A){if(typeof A=="object"&&A!==null){const e={};for(const t in A)Object.prototype.hasOwnProperty.call(A,t)&&(e[t]=A[t]);return e}else return{}}function _T(A,e=40){const t=Object.keys(ep(A));t.sort();const n=t[0];if(!n)return"[object has no keys]";if(n.length>=e)return Ws(n,e);for(let i=t.length;i>0;i--){const r=t.slice(0,i).join(", ");if(!(r.length>e))return i===t.length?r:Ws(r,e)}return""}function xT(){const A=Ae;return A.crypto||A.msCrypto}function dt(A=xT()){let e=()=>Math.random()*16;try{if(A?.randomUUID)return A.randomUUID().replace(/-/g,"");A?.getRandomValues&&(e=()=>{const t=new Uint8Array(1);return A.getRandomValues(t),t[0]})}catch{}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,t=>(t^(e()&15)>>t/4).toString(16))}function np(A){return A.exception?.values?.[0]}function en(A){const{message:e,event_id:t}=A;if(e)return e;const n=np(A);return n?n.type&&n.value?`${n.type}: ${n.value}`:n.type||n.value||t||"<unknown>":t||"<unknown>"}function qc(A,e,t){const n=A.exception=A.exception||{},i=n.values=n.values||[],r=i[0]=i[0]||{};r.value||(r.value=e||""),r.type||(r.type=t||"Error")}function Hn(A,e){const t=np(A);if(!t)return;const n={type:"generic",handled:!0},i=t.mechanism;if(t.mechanism={...n,...i,...e},e&&"data"in e){const r={...i?.data,...e.data};t.mechanism.data=r}}function ip(A){if(RT(A))return!0;try{ZA(A,"__sentry_captured__",!0)}catch{}return!1}function RT(A){try{return A.__sentry_captured__}catch{}}const rp=1e3;function Pi(){return Date.now()/rp}function PT(){const{performance:A}=Ae;if(!A?.now)return Pi;const e=Date.now()-A.now(),t=A.timeOrigin==null?e:A.timeOrigin;return()=>(t+A.now())/rp}const zt=PT();function DT(A){const e=zt(),t={sid:dt(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>OT(t)};return A&&Mn(t,A),t}function Mn(A,e={}){if(e.user&&(!A.ipAddress&&e.user.ip_address&&(A.ipAddress=e.user.ip_address),!A.did&&!e.did&&(A.did=e.user.id||e.user.email||e.user.username)),A.timestamp=e.timestamp||zt(),e.abnormal_mechanism&&(A.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(A.ignoreDuration=e.ignoreDuration),e.sid&&(A.sid=e.sid.length===32?e.sid:dt()),e.init!==void 0&&(A.init=e.init),!A.did&&e.did&&(A.did=`${e.did}`),typeof e.started=="number"&&(A.started=e.started),A.ignoreDuration)A.duration=void 0;else if(typeof e.duration=="number")A.duration=e.duration;else{const t=A.timestamp-A.started;A.duration=t>=0?t:0}e.release&&(A.release=e.release),e.environment&&(A.environment=e.environment),!A.ipAddress&&e.ipAddress&&(A.ipAddress=e.ipAddress),!A.userAgent&&e.userAgent&&(A.userAgent=e.userAgent),typeof e.errors=="number"&&(A.errors=e.errors),e.status&&(A.status=e.status)}function LT(A,e){let t={};e?t={status:e}:A.status==="ok"&&(t={status:"exited"}),Mn(A,t)}function OT(A){return{sid:`${A.sid}`,init:A.init,started:new Date(A.started*1e3).toISOString(),timestamp:new Date(A.timestamp*1e3).toISOString(),status:A.status,errors:A.errors,did:typeof A.did=="number"||typeof A.did=="string"?`${A.did}`:void 0,duration:A.duration,abnormal_mechanism:A.abnormal_mechanism,attrs:{release:A.release,environment:A.environment,ip_address:A.ipAddress,user_agent:A.userAgent}}}function Di(A,e,t=2){if(!e||typeof e!="object"||t<=0)return e;if(A&&Object.keys(e).length===0)return A;const n={...A};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=Di(n[i],e[i],t-1));return n}const Yc="_sentrySpan";function sp(A,e){e?ZA(A,Yc,e):delete A[Yc]}function op(A){return A[Yc]}function ap(){return dt()}function cp(){return dt().substring(16)}const HT=100;class Tt{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:ap(),sampleRand:Math.random()}}clone(){const e=new Tt;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,sp(e,op(this)),e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Mn(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this._tags={...this._tags,[e]:t},this._notifyScopeListeners(),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return t===null?delete this._contexts[e]:this._contexts[e]=t,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;const t=typeof e=="function"?e(this):e,n=t instanceof Tt?t.getScopeData():Ri(t)?e:void 0,{tags:i,extra:r,user:s,contexts:o,level:a,fingerprint:c=[],propagationContext:u}=n||{};return this._tags={...this._tags,...i},this._extra={...this._extra,...r},this._contexts={...this._contexts,...o},s&&Object.keys(s).length&&(this._user=s),a&&(this._level=a),c.length&&(this._fingerprint=c),u&&(this._propagationContext=u),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,sp(this,void 0),this._attachments=[],this.setPropagationContext({traceId:ap(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(e,t){const n=typeof t=="number"?t:HT;if(n<=0)return this;const i={timestamp:Pi(),...e,message:e.message?Ws(e.message,2048):e.message};return this._breadcrumbs.push(i),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client?.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:op(this)}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=Di(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,t){const n=t?.event_id||dt();if(!this._client)return N.warn("No client configured on scope - will not capture exception!"),n;const i=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:i,...t,event_id:n},this),n}captureMessage(e,t,n){const i=n?.event_id||dt();if(!this._client)return N.warn("No client configured on scope - will not capture message!"),i;const r=new Error(e);return this._client.captureMessage(e,t,{originalException:e,syntheticException:r,...n,event_id:i},this),i}captureEvent(e,t){const n=t?.event_id||dt();return this._client?(this._client.captureEvent(e,{...t,event_id:n},this),n):(N.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}function MT(){return Ks("defaultCurrentScope",()=>new Tt)}function NT(){return Ks("defaultIsolationScope",()=>new Tt)}class KT{constructor(e,t){let n;e?n=e:n=new Tt;let i;t?i=t:i=new Tt,this._stack=[{scope:n}],this._isolationScope=i}withScope(e){const t=this._pushScope();let n;try{n=e(t)}catch(i){throw this._popScope(),i}return Vs(n)?n.then(i=>(this._popScope(),i),i=>{throw this._popScope(),i}):(this._popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}function Nn(){const A=Ms(),e=Ns(A);return e.stack=e.stack||new KT(MT(),NT())}function GT(A){return Nn().withScope(A)}function VT(A,e){const t=Nn();return t.withScope(()=>(t.getStackTop().scope=A,e(A)))}function up(A){return Nn().withScope(()=>A(Nn().getIsolationScope()))}function jT(){return{withIsolationScope:up,withScope:GT,withSetScope:VT,withSetIsolationScope:(A,e)=>up(e),getCurrentScope:()=>Nn().getScope(),getIsolationScope:()=>Nn().getIsolationScope()}}function zc(A){const e=Ns(A);return e.acs?e.acs:jT()}function Kn(){const A=Ms();return zc(A).getCurrentScope()}function Li(){const A=Ms();return zc(A).getIsolationScope()}function $T(){return Ks("globalScope",()=>new Tt)}function lp(...A){const e=Ms(),t=zc(e);if(A.length===2){const[n,i]=A;return n?t.withSetScope(n,i):t.withScope(i)}return t.withScope(A[0])}function Ne(){return Kn().getClient()}function WT(A){const e=A.getPropagationContext(),{traceId:t,parentSpanId:n,propagationSpanId:i}=e,r={trace_id:t,span_id:i||cp()};return n&&(r.parent_span_id=n),r}const JT="sentry.source",XT="sentry.sample_rate",qT="sentry.previous_trace_sample_rate",YT="sentry.op",zT="sentry.origin",dp="sentry.profile_id",hp="sentry.exclusive_time",ZT=0,eQ=1,tQ="_sentryScope",AQ="_sentryIsolationScope";function fp(A){return{scope:A[tQ],isolationScope:A[AQ]}}function nQ(A){if(typeof A=="boolean")return Number(A);const e=typeof A=="string"?parseFloat(A):A;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}const iQ="sentry-",rQ=/^sentry-/;function sQ(A){const e=oQ(A);if(!e)return;const t=Object.entries(e).reduce((n,[i,r])=>{if(i.match(rQ)){const s=i.slice(iQ.length);n[s]=r}return n},{});if(Object.keys(t).length>0)return t}function oQ(A){if(!(!A||!Yt(A)&&!Array.isArray(A)))return Array.isArray(A)?A.reduce((e,t)=>{const n=gp(t);return Object.entries(n).forEach(([i,r])=>{e[i]=r}),e},{}):gp(A)}function gp(A){return A.split(",").map(e=>e.split("=").map(t=>{try{return decodeURIComponent(t.trim())}catch{return}})).reduce((e,[t,n])=>(t&&n&&(e[t]=n),e),{})}const pp=1;let mp=!1;function aQ(A){const{spanId:e,traceId:t,isRemote:n}=A.spanContext(),i=n?e:Zc(A).parent_span_id,r=fp(A).scope,s=n?r?.getPropagationContext().propagationSpanId||cp():e;return{parent_span_id:i,span_id:s,trace_id:t}}function cQ(A){if(A&&A.length>0)return A.map(({context:{spanId:e,traceId:t,traceFlags:n,...i},attributes:r})=>({span_id:e,trace_id:t,sampled:n===pp,attributes:r,...i}))}function Bp(A){return typeof A=="number"?vp(A):Array.isArray(A)?A[0]+A[1]/1e9:A instanceof Date?vp(A.getTime()):zt()}function vp(A){return A>9999999999?A/1e3:A}function Zc(A){if(lQ(A))return A.getSpanJSON();const{spanId:e,traceId:t}=A.spanContext();if(uQ(A)){const{attributes:n,startTime:i,name:r,endTime:s,status:o,links:a}=A,c="parentSpanId"in A?A.parentSpanId:"parentSpanContext"in A?A.parentSpanContext?.spanId:void 0;return{span_id:e,trace_id:t,data:n,description:r,parent_span_id:c,start_timestamp:Bp(i),timestamp:Bp(s)||void 0,status:hQ(o),op:n[YT],origin:n[zT],links:cQ(a)}}return{span_id:e,trace_id:t,start_timestamp:0,data:{}}}function uQ(A){const e=A;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function lQ(A){return typeof A.getSpanJSON=="function"}function dQ(A){const{traceFlags:e}=A.spanContext();return e===pp}function hQ(A){if(!(!A||A.code===ZT))return A.code===eQ?"ok":A.message||"unknown_error"}const fQ="_sentryRootSpan";function Cp(A){return A[fQ]||A}function wp(){mp||($s(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")}),mp=!0)}const yp=50,tn="?",bp=/\(error: (.*)\)/,Ep=/captureMessage|captureException/;function gQ(...A){const e=A.sort((t,n)=>t[0]-n[0]).map(t=>t[1]);return(t,n=0,i=0)=>{const r=[],s=t.split(`
|
|
111
|
+
`);for(let o=n;o<s.length;o++){const a=s[o];if(a.length>1024)continue;const c=bp.test(a)?a.replace(bp,"$1"):a;if(!c.match(/\S*Error: /)){for(const u of e){const l=u(c);if(l){r.push(l);break}}if(r.length>=yp+i)break}}return pQ(r.slice(i))}}function pQ(A){if(!A.length)return[];const e=Array.from(A);return/sentryWrapped/.test(Xs(e).function||"")&&e.pop(),e.reverse(),Ep.test(Xs(e).function||"")&&(e.pop(),Ep.test(Xs(e).function||"")&&e.pop()),e.slice(0,yp).map(t=>({...t,filename:t.filename||Xs(e).filename,function:t.function||tn}))}function Xs(A){return A[A.length-1]||{}}const eu="<anonymous>";function _A(A){try{return!A||typeof A!="function"?eu:A.name||eu}catch{return eu}}function Sp(A){const e=A.exception;if(e){const t=[];try{return e.values.forEach(n=>{n.stacktrace.frames&&t.push(...n.stacktrace.frames)}),t}catch{return}}}const qs={},Up={};function An(A,e){qs[A]=qs[A]||[],qs[A].push(e)}function nn(A,e){if(!Up[A]){Up[A]=!0;try{e()}catch(t){X&&N.error(`Error while instrumenting ${A}`,t)}}}function Qt(A,e){const t=A&&qs[A];if(t)for(const n of t)try{n(e)}catch(i){X&&N.error(`Error while triggering instrumentation handler.
|
|
112
112
|
Type: ${A}
|
|
113
113
|
Name: ${_A(n)}
|
|
114
|
-
Error:`,i)}}let
|
|
114
|
+
Error:`,i)}}let tu=null;function mQ(A){const e="error";An(e,A),nn(e,BQ)}function BQ(){tu=Ae.onerror,Ae.onerror=function(A,e,t,n,i){return Qt("error",{column:n,error:i,line:t,msg:A,url:e}),tu?tu.apply(this,arguments):!1},Ae.onerror.__SENTRY_INSTRUMENTED__=!0}let Au=null;function vQ(A){const e="unhandledrejection";An(e,A),nn(e,CQ)}function CQ(){Au=Ae.onunhandledrejection,Ae.onunhandledrejection=function(A){return Qt("unhandledrejection",A),Au?Au.apply(this,arguments):!0},Ae.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function wQ(A){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const e=A||Ne()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}const nu="production",yQ=/^o(\d+)\./,bQ=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function EQ(A){return A==="http"||A==="https"}function Ys(A,e=!1){const{host:t,path:n,pass:i,port:r,projectId:s,protocol:o,publicKey:a}=A;return`${o}://${a}${e&&i?`:${i}`:""}@${t}${r?`:${r}`:""}/${n&&`${n}/`}${s}`}function SQ(A){const e=bQ.exec(A);if(!e){$s(()=>{console.error(`Invalid Sentry Dsn: ${A}`)});return}const[t,n,i="",r="",s="",o=""]=e.slice(1);let a="",c=o;const u=c.split("/");if(u.length>1&&(a=u.slice(0,-1).join("/"),c=u.pop()),c){const l=c.match(/^\d+/);l&&(c=l[0])}return Tp({host:r,pass:i,path:a,projectId:c,port:s,protocol:t,publicKey:n})}function Tp(A){return{protocol:A.protocol,publicKey:A.publicKey||"",pass:A.pass||"",host:A.host,port:A.port||"",path:A.path||"",projectId:A.projectId}}function UQ(A){if(!X)return!0;const{port:e,projectId:t,protocol:n}=A;return["protocol","publicKey","host","projectId"].find(s=>A[s]?!1:(N.error(`Invalid Sentry Dsn: ${s} missing`),!0))?!1:t.match(/^\d+$/)?EQ(n)?e&&isNaN(parseInt(e,10))?(N.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(N.error(`Invalid Sentry Dsn: Invalid protocol ${n}`),!1):(N.error(`Invalid Sentry Dsn: Invalid projectId ${t}`),!1)}function TQ(A){return A.match(yQ)?.[1]}function QQ(A){const e=typeof A=="string"?SQ(A):Tp(A);if(!(!e||!UQ(e)))return e}const FQ="_frozenDsc";function Qp(A,e){const t=e.getOptions(),{publicKey:n,host:i}=e.getDsn()||{};let r;t.orgId?r=String(t.orgId):i&&(r=TQ(i));const s={environment:t.environment||nu,release:t.release,public_key:n,trace_id:A,org_id:r};return e.emit("createDsc",s),s}function kQ(A,e){const t=e.getPropagationContext();return t.dsc||Qp(t.traceId,A)}function IQ(A){const e=Ne();if(!e)return{};const t=Cp(A),n=Zc(t),i=n.data,r=t.spanContext().traceState,s=r?.get("sentry.sample_rate")??i[XT]??i[qT];function o(f){return(typeof s=="number"||typeof s=="string")&&(f.sample_rate=`${s}`),f}const a=t[FQ];if(a)return o(a);const c=r?.get("sentry.dsc"),u=c&&sQ(c);if(u)return o(u);const l=Qp(A.spanContext().traceId,e),d=i[JT],h=n.description;return d!=="url"&&h&&(l.transaction=h),wQ()&&(l.sampled=String(dQ(t)),l.sample_rand=r?.get("sentry.sample_rand")??fp(t).scope?.getPropagationContext().sampleRand.toString()),o(l),e.emit("createDsc",l,t),l}function Zt(A,e=100,t=1/0){try{return iu("",A,e,t)}catch(n){return{ERROR:`**non-serializable** (${n})`}}}function Fp(A,e=3,t=100*1024){const n=Zt(A,e);return PQ(n)>t?Fp(A,e-1,t):n}function iu(A,e,t=1/0,n=1/0,i=DQ()){const[r,s]=i;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;const o=_Q(A,e);if(!o.startsWith("[object "))return o;if(e.__sentry_skip_normalization__)return e;const a=typeof e.__sentry_override_normalization_depth__=="number"?e.__sentry_override_normalization_depth__:t;if(a===0)return o.replace("object ","");if(r(e))return"[Circular ~]";const c=e;if(c&&typeof c.toJSON=="function")try{const h=c.toJSON();return iu("",h,a-1,n,i)}catch{}const u=Array.isArray(e)?[]:{};let l=0;const d=ep(e);for(const h in d){if(!Object.prototype.hasOwnProperty.call(d,h))continue;if(l>=n){u[h]="[MaxProperties ~]";break}const f=d[h];u[h]=iu(h,f,a-1,n,i),l++}return s(e),u}function _Q(A,e){try{if(A==="domain"&&e&&typeof e=="object"&&e._events)return"[Domain]";if(A==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&e===global)return"[Global]";if(typeof window<"u"&&e===window)return"[Window]";if(typeof document<"u"&&e===document)return"[Document]";if(Xg(e))return"[VueViewModel]";if(ET(e))return"[SyntheticEvent]";if(typeof e=="number"&&!Number.isFinite(e))return`[${e}]`;if(typeof e=="function")return`[Function: ${_A(e)}]`;if(typeof e=="symbol")return`[${String(e)}]`;if(typeof e=="bigint")return`[BigInt: ${String(e)}]`;const t=xQ(e);return/^HTML(\w*)Element$/.test(t)?`[HTMLElement: ${t}]`:`[object ${t}]`}catch(t){return`**non-serializable** (${t})`}}function xQ(A){const e=Object.getPrototypeOf(A);return e?.constructor?e.constructor.name:"null prototype"}function RQ(A){return~-encodeURI(A).split(/%..|./).length}function PQ(A){return RQ(JSON.stringify(A))}function DQ(){const A=new WeakSet;function e(n){return A.has(n)?!0:(A.add(n),!1)}function t(n){A.delete(n)}return[e,t]}function Oi(A,e=[]){return[A,e]}function LQ(A,e){const[t,n]=A;return[t,[...n,e]]}function kp(A,e){const t=A[1];for(const n of t){const i=n[0].type;if(e(n,i))return!0}return!1}function ru(A){const e=Ns(Ae);return e.encodePolyfill?e.encodePolyfill(A):new TextEncoder().encode(A)}function OQ(A){const[e,t]=A;let n=JSON.stringify(e);function i(r){typeof n=="string"?n=typeof r=="string"?n+r:[ru(n),r]:n.push(typeof r=="string"?ru(r):r)}for(const r of t){const[s,o]=r;if(i(`
|
|
115
115
|
${JSON.stringify(s)}
|
|
116
|
-
`),typeof o=="string"||o instanceof Uint8Array)i(o);else{let a;try{a=JSON.stringify(o)}catch{a=JSON.stringify(Zt(o))}i(a)}}return typeof n=="string"?n:MQ(n)}function MQ(A){const e=A.reduce((i,r)=>i+r.length,0),t=new Uint8Array(e);let n=0;for(const i of A)t.set(i,n),n+=i.length;return t}function NQ(A){const e=typeof A.data=="string"?ou(A.data):A.data;return[{type:"attachment",length:e.length,filename:A.filename,content_type:A.contentType,attachment_type:A.attachmentType},e]}const KQ={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",log:"log_item"};function Ip(A){return KQ[A]}function _p(A){if(!A?.sdk)return;const{name:e,version:t}=A.sdk;return{name:e,version:t}}function GQ(A,e,t,n){const i=A.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:A.event_id,sent_at:new Date().toISOString(),...e&&{sdk:e},...!!t&&n&&{dsn:Ys(n)},...i&&{trace:i}}}function VQ(A,e){return e&&(A.sdk=A.sdk||{},A.sdk.name=A.sdk.name||e.name,A.sdk.version=A.sdk.version||e.version,A.sdk.integrations=[...A.sdk.integrations||[],...e.integrations||[]],A.sdk.packages=[...A.sdk.packages||[],...e.packages||[]]),A}function jQ(A,e,t,n){const i=_p(t),r={sent_at:new Date().toISOString(),...i&&{sdk:i},...!!n&&e&&{dsn:Ys(e)}},s="aggregates"in A?[{type:"sessions"},A]:[{type:"session"},A.toJSON()];return Oi(r,[s])}function $Q(A,e,t,n){const i=_p(t),r=A.type&&A.type!=="replay_event"?A.type:"event";VQ(A,t?.sdk);const s=GQ(A,i,n,e);return delete A.sdkProcessingMetadata,Oi(s,[[{type:r},A]])}var eA;(function(A){A[A.PENDING=0]="PENDING";const t=1;A[A.RESOLVED=t]="RESOLVED";const n=2;A[A.REJECTED=n]="REJECTED"})(eA||(eA={}));function rn(A){return new xA(e=>{e(A)})}function zs(A){return new xA((e,t)=>{t(A)})}class xA{constructor(e){this._state=eA.PENDING,this._handlers=[],this._runExecutor(e)}then(e,t){return new xA((n,i)=>{this._handlers.push([!1,r=>{if(!e)n(r);else try{n(e(r))}catch(s){i(s)}},r=>{if(!t)i(r);else try{n(t(r))}catch(s){i(s)}}]),this._executeHandlers()})}catch(e){return this.then(t=>t,e)}finally(e){return new xA((t,n)=>{let i,r;return this.then(s=>{r=!1,i=s,e&&e()},s=>{r=!0,i=s,e&&e()}).then(()=>{if(r){n(i);return}t(i)})})}_executeHandlers(){if(this._state===eA.PENDING)return;const e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===eA.RESOLVED&&t[1](this._value),this._state===eA.REJECTED&&t[2](this._value),t[0]=!0)})}_runExecutor(e){const t=(r,s)=>{if(this._state===eA.PENDING){if(Vs(s)){s.then(n,i);return}this._state=r,this._value=s,this._executeHandlers()}},n=r=>{t(eA.RESOLVED,r)},i=r=>{t(eA.REJECTED,r)};try{e(n,i)}catch(r){i(r)}}}function au(A,e,t,n=0){return new xA((i,r)=>{const s=A[n];if(e===null||typeof s!="function")i(e);else{const o=s({...e},t);X&&s.id&&o===null&&N.log(`Event processor "${s.id}" dropped event`),Vs(o)?o.then(a=>au(A,a,t,n+1).then(i)).then(null,r):au(A,o,t,n+1).then(i).then(null,r)}})}let Zs,xp,eo;function WQ(A){const e=Ae._sentryDebugIds;if(!e)return{};const t=Object.keys(e);return eo&&t.length===xp||(xp=t.length,eo=t.reduce((n,i)=>{Zs||(Zs={});const r=Zs[i];if(r)n[r[0]]=r[1];else{const s=A(i);for(let o=s.length-1;o>=0;o--){const c=s[o]?.filename,u=e[i];if(c&&u){n[c]=u,Zs[i]=[c,u];break}}}return n},{})),eo}function JQ(A,e){const{fingerprint:t,span:n,breadcrumbs:i,sdkProcessingMetadata:r}=e;XQ(A,e),n&&zQ(A,n),ZQ(A,t),qQ(A,i),YQ(A,r)}function Rp(A,e){const{extra:t,tags:n,user:i,contexts:r,level:s,sdkProcessingMetadata:o,breadcrumbs:a,fingerprint:c,eventProcessors:u,attachments:l,propagationContext:d,transactionName:h,span:f}=e;to(A,"extra",t),to(A,"tags",n),to(A,"user",i),to(A,"contexts",r),A.sdkProcessingMetadata=Di(A.sdkProcessingMetadata,o,2),s&&(A.level=s),h&&(A.transactionName=h),f&&(A.span=f),a.length&&(A.breadcrumbs=[...A.breadcrumbs,...a]),c.length&&(A.fingerprint=[...A.fingerprint,...c]),u.length&&(A.eventProcessors=[...A.eventProcessors,...u]),l.length&&(A.attachments=[...A.attachments,...l]),A.propagationContext={...A.propagationContext,...d}}function to(A,e,t){A[e]=Di(A[e],t,1)}function XQ(A,e){const{extra:t,tags:n,user:i,contexts:r,level:s,transactionName:o}=e;Object.keys(t).length&&(A.extra={...t,...A.extra}),Object.keys(n).length&&(A.tags={...n,...A.tags}),Object.keys(i).length&&(A.user={...i,...A.user}),Object.keys(r).length&&(A.contexts={...r,...A.contexts}),s&&(A.level=s),o&&A.type!=="transaction"&&(A.transaction=o)}function qQ(A,e){const t=[...A.breadcrumbs||[],...e];A.breadcrumbs=t.length?t:void 0}function YQ(A,e){A.sdkProcessingMetadata={...A.sdkProcessingMetadata,...e}}function zQ(A,e){A.contexts={trace:cQ(e),...A.contexts},A.sdkProcessingMetadata={dynamicSamplingContext:_Q(e),...A.sdkProcessingMetadata};const t=Cp(e),n=tu(t).description;n&&!A.transaction&&A.type==="transaction"&&(A.transaction=n)}function ZQ(A,e){A.fingerprint=A.fingerprint?Array.isArray(A.fingerprint)?A.fingerprint:[A.fingerprint]:[],e&&(A.fingerprint=A.fingerprint.concat(e)),A.fingerprint.length||delete A.fingerprint}function eF(A,e,t,n,i,r){const{normalizeDepth:s=3,normalizeMaxBreadth:o=1e3}=A,a={...e,event_id:e.event_id||t.event_id||dt(),timestamp:e.timestamp||Pi()},c=t.integrations||A.integrations.map(p=>p.name);tF(a,A),iF(a,c),i&&i.emit("applyFrameMetadata",e),e.type===void 0&&AF(a,A.stackParser);const u=sF(n,t.captureContext);t.mechanism&&Hn(a,t.mechanism);const l=i?i.getEventProcessors():[],d=WT().getScopeData();if(r){const p=r.getScopeData();Rp(d,p)}if(u){const p=u.getScopeData();Rp(d,p)}const h=[...t.attachments||[],...d.attachments];h.length&&(t.attachments=h),JQ(a,d);const f=[...l,...d.eventProcessors];return au(f,a,t).then(p=>(p&&nF(p),typeof s=="number"&&s>0?rF(p,s,o):p))}function tF(A,e){const{environment:t,release:n,dist:i,maxValueLength:r=250}=e;A.environment=A.environment||t||ru,!A.release&&n&&(A.release=n),!A.dist&&i&&(A.dist=i);const s=A.request;s?.url&&(s.url=Ws(s.url,r))}function AF(A,e){const t=WQ(e);A.exception?.values?.forEach(n=>{n.stacktrace?.frames?.forEach(i=>{i.filename&&(i.debug_id=t[i.filename])})})}function nF(A){const e={};if(A.exception?.values?.forEach(n=>{n.stacktrace?.frames?.forEach(i=>{i.debug_id&&(i.abs_path?e[i.abs_path]=i.debug_id:i.filename&&(e[i.filename]=i.debug_id),delete i.debug_id)})}),Object.keys(e).length===0)return;A.debug_meta=A.debug_meta||{},A.debug_meta.images=A.debug_meta.images||[];const t=A.debug_meta.images;Object.entries(e).forEach(([n,i])=>{t.push({type:"sourcemap",code_file:n,debug_id:i})})}function iF(A,e){e.length>0&&(A.sdk=A.sdk||{},A.sdk.integrations=[...A.sdk.integrations||[],...e])}function rF(A,e,t){if(!A)return null;const n={...A,...A.breadcrumbs&&{breadcrumbs:A.breadcrumbs.map(i=>({...i,...i.data&&{data:Zt(i.data,e,t)}}))},...A.user&&{user:Zt(A.user,e,t)},...A.contexts&&{contexts:Zt(A.contexts,e,t)},...A.extra&&{extra:Zt(A.extra,e,t)}};return A.contexts?.trace&&n.contexts&&(n.contexts.trace=A.contexts.trace,A.contexts.trace.data&&(n.contexts.trace.data=Zt(A.contexts.trace.data,e,t))),A.spans&&(n.spans=A.spans.map(i=>({...i,...i.data&&{data:Zt(i.data,e,t)}}))),A.contexts?.flags&&n.contexts&&(n.contexts.flags=Zt(A.contexts.flags,3,t)),n}function sF(A,e){if(!e)return A;const t=A?A.clone():new Tt;return t.update(e),t}function oF(A){if(A)return aF(A)?{captureContext:A}:uF(A)?{captureContext:A}:A}function aF(A){return A instanceof Tt||typeof A=="function"}const cF=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function uF(A){return Object.keys(A).some(e=>cF.includes(e))}function lF(A,e){return Kn().captureException(A,oF(e))}function Pp(A,e){return Kn().captureEvent(A,e)}function Dp(A){const e=Li(),t=Kn(),{userAgent:n}=Ae.navigator||{},i=LT({user:t.getUser()||e.getUser(),...n&&{userAgent:n},...A}),r=e.getSession();return r?.status==="ok"&&Mn(r,{status:"exited"}),Lp(),e.setSession(i),i}function Lp(){const A=Li(),t=Kn().getSession()||A.getSession();t&&OT(t),Op(),A.setSession()}function Op(){const A=Li(),e=Ne(),t=A.getSession();t&&e&&e.captureSession(t)}function Hp(A=!1){if(A){Lp();return}Op()}const dF="7";function hF(A){const e=A.protocol?`${A.protocol}:`:"",t=A.port?`:${A.port}`:"";return`${e}//${A.host}${t}${A.path?`/${A.path}`:""}/api/`}function fF(A){return`${hF(A)}${A.projectId}/envelope/`}function gF(A,e){const t={sentry_version:dF};return A.publicKey&&(t.sentry_key=A.publicKey),e&&(t.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(t).toString()}function pF(A,e,t){return e||`${fF(A)}?${gF(A,t)}`}const Mp=[];function mF(A,e){const t={};return e.forEach(n=>{n&&Kp(A,n,t)}),t}function Np(A,e){for(const t of e)t?.afterAllSetup&&t.afterAllSetup(A)}function Kp(A,e,t){if(t[e.name]){X&&N.log(`Integration skipped because it was already installed: ${e.name}`);return}if(t[e.name]=e,Mp.indexOf(e.name)===-1&&typeof e.setupOnce=="function"&&(e.setupOnce(),Mp.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(A),typeof e.preprocessEvent=="function"){const n=e.preprocessEvent.bind(e);A.on("preprocessEvent",(i,r)=>n(i,r,A))}if(typeof e.processEvent=="function"){const n=e.processEvent.bind(e),i=Object.assign((r,s)=>n(r,s,A),{id:e.name});A.addEventProcessor(i)}X&&N.log(`Integration installed: ${e.name}`)}function F_(A){return A}function Gp(A){const e=[];A.message&&e.push(A.message);try{const t=A.exception.values[A.exception.values.length-1];t?.value&&(e.push(t.value),t.type&&e.push(`${t.type}: ${t.value}`))}catch{}return e}function BF(A){const{trace_id:e,parent_span_id:t,span_id:n,status:i,origin:r,data:s,op:o}=A.contexts?.trace??{};return{data:s??{},description:A.transaction,op:o,parent_span_id:t,span_id:n??"",start_timestamp:A.start_timestamp??0,status:i,timestamp:A.timestamp,trace_id:e??"",origin:r,profile_id:s?.[dp],exclusive_time:s?.[hp],measurements:A.measurements,is_segment:!0}}function vF(A){return{type:"transaction",timestamp:A.timestamp,start_timestamp:A.start_timestamp,transaction:A.description,contexts:{trace:{trace_id:A.trace_id,span_id:A.span_id,parent_span_id:A.parent_span_id,op:A.op,status:A.status,origin:A.origin,data:{...A.data,...A.profile_id&&{[dp]:A.profile_id},...A.exclusive_time&&{[hp]:A.exclusive_time}}}},measurements:A.measurements}}function CF(A,e,t){const n=[{type:"client_report"},{timestamp:t||Pi(),discarded_events:A}];return Oi(e?{dsn:e}:{},[n])}const Vp="Not capturing exception because it's already been captured.",jp="Discarded session because of missing or non-string release",$p=Symbol.for("SentryInternalError"),Wp=Symbol.for("SentryDoNotSendEventError");function Ao(A){return{message:A,[$p]:!0}}function cu(A){return{message:A,[Wp]:!0}}function Jp(A){return!!A&&typeof A=="object"&&$p in A}function Xp(A){return!!A&&typeof A=="object"&&Wp in A}class wF{constructor(e){if(this._options=e,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],e.dsn?this._dsn=FQ(e.dsn):X&&N.warn("No DSN provided, client will not send events."),this._dsn){const t=pF(this._dsn,e.tunnel,e._metadata?e._metadata.sdk:void 0);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:t})}}captureException(e,t,n){const i=dt();if(ip(e))return X&&N.log(Vp),i;const r={event_id:i,...t};return this._process(this.eventFromException(e,r).then(s=>this._captureEvent(s,r,n))),r.event_id}captureMessage(e,t,n,i){const r={event_id:dt(),...n},s=Wc(e)?e:String(e),o=Jc(e)?this.eventFromMessage(s,t,r):this.eventFromException(e,r);return this._process(o.then(a=>this._captureEvent(a,r,i))),r.event_id}captureEvent(e,t,n){const i=dt();if(t?.originalException&&ip(t.originalException))return X&&N.log(Vp),i;const r={event_id:i,...t},s=e.sdkProcessingMetadata||{},o=s.capturedSpanScope,a=s.capturedSpanIsolationScope;return this._process(this._captureEvent(e,r,o||n,a)),r.event_id}captureSession(e){this.sendSession(e),Mn(e,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(e){const t=this._transport;return t?(this.emit("flush"),this._isClientDoneProcessing(e).then(n=>t.flush(e).then(i=>n&&i))):rn(!0)}close(e){return this.flush(e).then(t=>(this.getOptions().enabled=!1,this.emit("close"),t))}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}addIntegration(e){const t=this._integrations[e.name];Kp(this,e,this._integrations),t||Np(this,[e])}sendEvent(e,t={}){this.emit("beforeSendEvent",e,t);let n=$Q(e,this._dsn,this._options._metadata,this._options.tunnel);for(const r of t.attachments||[])n=OQ(n,NQ(r));const i=this.sendEnvelope(n);i&&i.then(r=>this.emit("afterSendEvent",e,r),null)}sendSession(e){const{release:t,environment:n=ru}=this._options;if("aggregates"in e){const r=e.attrs||{};if(!r.release&&!t){X&&N.warn(jp);return}r.release=r.release||t,r.environment=r.environment||n,e.attrs=r}else{if(!e.release&&!t){X&&N.warn(jp);return}e.release=e.release||t,e.environment=e.environment||n}this.emit("beforeSendSession",e);const i=jQ(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(i)}recordDroppedEvent(e,t,n=1){if(this._options.sendClientReports){const i=`${e}:${t}`;X&&N.log(`Recording outcome: "${i}"${n>1?` (${n} times)`:""}`),this._outcomes[i]=(this._outcomes[i]||0)+n}}on(e,t){const n=this._hooks[e]=this._hooks[e]||[];return n.push(t),()=>{const i=n.indexOf(t);i>-1&&n.splice(i,1)}}emit(e,...t){const n=this._hooks[e];n&&n.forEach(i=>i(...t))}sendEnvelope(e){return this.emit("beforeEnvelope",e),this._isEnabled()&&this._transport?this._transport.send(e).then(null,t=>(X&&N.error("Error while sending envelope:",t),t)):(X&&N.error("Transport disabled"),rn({}))}_setupIntegrations(){const{integrations:e}=this._options;this._integrations=mF(this,e),Np(this,e)}_updateSessionFromEvent(e,t){let n=t.level==="fatal",i=!1;const r=t.exception?.values;if(r){i=!0;for(const a of r)if(a.mechanism?.handled===!1){n=!0;break}}const s=e.status==="ok";(s&&e.errors===0||s&&n)&&(Mn(e,{...n&&{status:"crashed"},errors:e.errors||Number(i||n)}),this.captureSession(e))}_isClientDoneProcessing(e){return new xA(t=>{let n=0;const i=1,r=setInterval(()=>{this._numProcessing==0?(clearInterval(r),t(!0)):(n+=i,e&&n>=e&&(clearInterval(r),t(!1)))},i)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,t,n,i){const r=this.getOptions(),s=Object.keys(this._integrations);return!t.integrations&&s?.length&&(t.integrations=s),this.emit("preprocessEvent",e,t),e.type||i.setLastEventId(e.event_id||t.event_id),eF(r,e,t,n,this,i).then(o=>{if(o===null)return o;this.emit("postprocessEvent",o,t),o.contexts={trace:JT(n),...o.contexts};const a=IQ(this,n);return o.sdkProcessingMetadata={dynamicSamplingContext:a,...o.sdkProcessingMetadata},o})}_captureEvent(e,t={},n=Kn(),i=Li()){return X&&uu(e)&&N.log(`Captured error event \`${Gp(e)[0]||"<unknown>"}\``),this._processEvent(e,t,n,i).then(r=>r.event_id,r=>{X&&(Xp(r)?N.log(r.message):Jp(r)?N.warn(r.message):N.warn(r))})}_processEvent(e,t,n,i){const r=this.getOptions(),{sampleRate:s}=r,o=qp(e),a=uu(e),c=e.type||"error",u=`before send for type \`${c}\``,l=typeof s>"u"?void 0:iQ(s);if(a&&typeof l=="number"&&Math.random()>l)return this.recordDroppedEvent("sample_rate","error"),zs(cu(`Discarding event because it's not included in the random sample (sampling rate = ${s})`));const d=c==="replay_event"?"replay":c;return this._prepareEvent(e,t,n,i).then(h=>{if(h===null)throw this.recordDroppedEvent("event_processor",d),cu("An event processor returned `null`, will not send event.");if(t.data&&t.data.__sentry__===!0)return h;const g=bF(this,r,h,t);return yF(g,u)}).then(h=>{if(h===null){if(this.recordDroppedEvent("before_send",d),o){const B=1+(e.spans||[]).length;this.recordDroppedEvent("before_send","span",B)}throw cu(`${u} returned \`null\`, will not send event.`)}const f=n.getSession()||i.getSession();if(a&&f&&this._updateSessionFromEvent(f,h),o){const p=h.sdkProcessingMetadata?.spanCountBeforeProcessing||0,B=h.spans?h.spans.length:0,y=p-B;y>0&&this.recordDroppedEvent("before_send","span",y)}const g=h.transaction_info;if(o&&g&&h.transaction!==e.transaction){const p="custom";h.transaction_info={...g,source:p}}return this.sendEvent(h,t),h}).then(null,h=>{throw Xp(h)||Jp(h)?h:(this.captureException(h,{data:{__sentry__:!0},originalException:h}),Ao(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
|
|
117
|
-
Reason: ${h}`))})}_process(e){this._numProcessing++,e.then(t=>(this._numProcessing--,t),t=>(this._numProcessing--,t))}_clearOutcomes(){const e=this._outcomes;return this._outcomes={},Object.entries(e).map(([t,n])=>{const[i,r]=t.split(":");return{reason:i,category:r,quantity:n}})}_flushOutcomes(){X&&N.log("Flushing outcomes...");const e=this._clearOutcomes();if(e.length===0){X&&N.log("No outcomes to send");return}if(!this._dsn){X&&N.log("No dsn provided, will not send outcomes");return}X&&N.log("Sending outcomes:",e);const t=
|
|
118
|
-
Event: ${en(A)}`),!0}else{if(
|
|
119
|
-
Event: ${en(A)}`),!0;if(
|
|
120
|
-
Event: ${en(A)}`),!0;if(
|
|
116
|
+
`),typeof o=="string"||o instanceof Uint8Array)i(o);else{let a;try{a=JSON.stringify(o)}catch{a=JSON.stringify(Zt(o))}i(a)}}return typeof n=="string"?n:HQ(n)}function HQ(A){const e=A.reduce((i,r)=>i+r.length,0),t=new Uint8Array(e);let n=0;for(const i of A)t.set(i,n),n+=i.length;return t}function MQ(A){const e=typeof A.data=="string"?ru(A.data):A.data;return[{type:"attachment",length:e.length,filename:A.filename,content_type:A.contentType,attachment_type:A.attachmentType},e]}const NQ={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",log:"log_item"};function Ip(A){return NQ[A]}function _p(A){if(!A?.sdk)return;const{name:e,version:t}=A.sdk;return{name:e,version:t}}function KQ(A,e,t,n){const i=A.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:A.event_id,sent_at:new Date().toISOString(),...e&&{sdk:e},...!!t&&n&&{dsn:Ys(n)},...i&&{trace:i}}}function GQ(A,e){return e&&(A.sdk=A.sdk||{},A.sdk.name=A.sdk.name||e.name,A.sdk.version=A.sdk.version||e.version,A.sdk.integrations=[...A.sdk.integrations||[],...e.integrations||[]],A.sdk.packages=[...A.sdk.packages||[],...e.packages||[]]),A}function VQ(A,e,t,n){const i=_p(t),r={sent_at:new Date().toISOString(),...i&&{sdk:i},...!!n&&e&&{dsn:Ys(e)}},s="aggregates"in A?[{type:"sessions"},A]:[{type:"session"},A.toJSON()];return Oi(r,[s])}function jQ(A,e,t,n){const i=_p(t),r=A.type&&A.type!=="replay_event"?A.type:"event";GQ(A,t?.sdk);const s=KQ(A,i,n,e);return delete A.sdkProcessingMetadata,Oi(s,[[{type:r},A]])}var eA;(function(A){A[A.PENDING=0]="PENDING";const t=1;A[A.RESOLVED=t]="RESOLVED";const n=2;A[A.REJECTED=n]="REJECTED"})(eA||(eA={}));function rn(A){return new xA(e=>{e(A)})}function zs(A){return new xA((e,t)=>{t(A)})}class xA{constructor(e){this._state=eA.PENDING,this._handlers=[],this._runExecutor(e)}then(e,t){return new xA((n,i)=>{this._handlers.push([!1,r=>{if(!e)n(r);else try{n(e(r))}catch(s){i(s)}},r=>{if(!t)i(r);else try{n(t(r))}catch(s){i(s)}}]),this._executeHandlers()})}catch(e){return this.then(t=>t,e)}finally(e){return new xA((t,n)=>{let i,r;return this.then(s=>{r=!1,i=s,e&&e()},s=>{r=!0,i=s,e&&e()}).then(()=>{if(r){n(i);return}t(i)})})}_executeHandlers(){if(this._state===eA.PENDING)return;const e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===eA.RESOLVED&&t[1](this._value),this._state===eA.REJECTED&&t[2](this._value),t[0]=!0)})}_runExecutor(e){const t=(r,s)=>{if(this._state===eA.PENDING){if(Vs(s)){s.then(n,i);return}this._state=r,this._value=s,this._executeHandlers()}},n=r=>{t(eA.RESOLVED,r)},i=r=>{t(eA.REJECTED,r)};try{e(n,i)}catch(r){i(r)}}}function su(A,e,t,n=0){return new xA((i,r)=>{const s=A[n];if(e===null||typeof s!="function")i(e);else{const o=s({...e},t);X&&s.id&&o===null&&N.log(`Event processor "${s.id}" dropped event`),Vs(o)?o.then(a=>su(A,a,t,n+1).then(i)).then(null,r):su(A,o,t,n+1).then(i).then(null,r)}})}let Zs,xp,eo;function $Q(A){const e=Ae._sentryDebugIds;if(!e)return{};const t=Object.keys(e);return eo&&t.length===xp||(xp=t.length,eo=t.reduce((n,i)=>{Zs||(Zs={});const r=Zs[i];if(r)n[r[0]]=r[1];else{const s=A(i);for(let o=s.length-1;o>=0;o--){const c=s[o]?.filename,u=e[i];if(c&&u){n[c]=u,Zs[i]=[c,u];break}}}return n},{})),eo}function WQ(A,e){const{fingerprint:t,span:n,breadcrumbs:i,sdkProcessingMetadata:r}=e;JQ(A,e),n&&YQ(A,n),zQ(A,t),XQ(A,i),qQ(A,r)}function Rp(A,e){const{extra:t,tags:n,user:i,contexts:r,level:s,sdkProcessingMetadata:o,breadcrumbs:a,fingerprint:c,eventProcessors:u,attachments:l,propagationContext:d,transactionName:h,span:f}=e;to(A,"extra",t),to(A,"tags",n),to(A,"user",i),to(A,"contexts",r),A.sdkProcessingMetadata=Di(A.sdkProcessingMetadata,o,2),s&&(A.level=s),h&&(A.transactionName=h),f&&(A.span=f),a.length&&(A.breadcrumbs=[...A.breadcrumbs,...a]),c.length&&(A.fingerprint=[...A.fingerprint,...c]),u.length&&(A.eventProcessors=[...A.eventProcessors,...u]),l.length&&(A.attachments=[...A.attachments,...l]),A.propagationContext={...A.propagationContext,...d}}function to(A,e,t){A[e]=Di(A[e],t,1)}function JQ(A,e){const{extra:t,tags:n,user:i,contexts:r,level:s,transactionName:o}=e;Object.keys(t).length&&(A.extra={...t,...A.extra}),Object.keys(n).length&&(A.tags={...n,...A.tags}),Object.keys(i).length&&(A.user={...i,...A.user}),Object.keys(r).length&&(A.contexts={...r,...A.contexts}),s&&(A.level=s),o&&A.type!=="transaction"&&(A.transaction=o)}function XQ(A,e){const t=[...A.breadcrumbs||[],...e];A.breadcrumbs=t.length?t:void 0}function qQ(A,e){A.sdkProcessingMetadata={...A.sdkProcessingMetadata,...e}}function YQ(A,e){A.contexts={trace:aQ(e),...A.contexts},A.sdkProcessingMetadata={dynamicSamplingContext:IQ(e),...A.sdkProcessingMetadata};const t=Cp(e),n=Zc(t).description;n&&!A.transaction&&A.type==="transaction"&&(A.transaction=n)}function zQ(A,e){A.fingerprint=A.fingerprint?Array.isArray(A.fingerprint)?A.fingerprint:[A.fingerprint]:[],e&&(A.fingerprint=A.fingerprint.concat(e)),A.fingerprint.length||delete A.fingerprint}function ZQ(A,e,t,n,i,r){const{normalizeDepth:s=3,normalizeMaxBreadth:o=1e3}=A,a={...e,event_id:e.event_id||t.event_id||dt(),timestamp:e.timestamp||Pi()},c=t.integrations||A.integrations.map(p=>p.name);eF(a,A),nF(a,c),i&&i.emit("applyFrameMetadata",e),e.type===void 0&&tF(a,A.stackParser);const u=rF(n,t.captureContext);t.mechanism&&Hn(a,t.mechanism);const l=i?i.getEventProcessors():[],d=$T().getScopeData();if(r){const p=r.getScopeData();Rp(d,p)}if(u){const p=u.getScopeData();Rp(d,p)}const h=[...t.attachments||[],...d.attachments];h.length&&(t.attachments=h),WQ(a,d);const f=[...l,...d.eventProcessors];return su(f,a,t).then(p=>(p&&AF(p),typeof s=="number"&&s>0?iF(p,s,o):p))}function eF(A,e){const{environment:t,release:n,dist:i,maxValueLength:r=250}=e;A.environment=A.environment||t||nu,!A.release&&n&&(A.release=n),!A.dist&&i&&(A.dist=i);const s=A.request;s?.url&&(s.url=Ws(s.url,r))}function tF(A,e){const t=$Q(e);A.exception?.values?.forEach(n=>{n.stacktrace?.frames?.forEach(i=>{i.filename&&(i.debug_id=t[i.filename])})})}function AF(A){const e={};if(A.exception?.values?.forEach(n=>{n.stacktrace?.frames?.forEach(i=>{i.debug_id&&(i.abs_path?e[i.abs_path]=i.debug_id:i.filename&&(e[i.filename]=i.debug_id),delete i.debug_id)})}),Object.keys(e).length===0)return;A.debug_meta=A.debug_meta||{},A.debug_meta.images=A.debug_meta.images||[];const t=A.debug_meta.images;Object.entries(e).forEach(([n,i])=>{t.push({type:"sourcemap",code_file:n,debug_id:i})})}function nF(A,e){e.length>0&&(A.sdk=A.sdk||{},A.sdk.integrations=[...A.sdk.integrations||[],...e])}function iF(A,e,t){if(!A)return null;const n={...A,...A.breadcrumbs&&{breadcrumbs:A.breadcrumbs.map(i=>({...i,...i.data&&{data:Zt(i.data,e,t)}}))},...A.user&&{user:Zt(A.user,e,t)},...A.contexts&&{contexts:Zt(A.contexts,e,t)},...A.extra&&{extra:Zt(A.extra,e,t)}};return A.contexts?.trace&&n.contexts&&(n.contexts.trace=A.contexts.trace,A.contexts.trace.data&&(n.contexts.trace.data=Zt(A.contexts.trace.data,e,t))),A.spans&&(n.spans=A.spans.map(i=>({...i,...i.data&&{data:Zt(i.data,e,t)}}))),A.contexts?.flags&&n.contexts&&(n.contexts.flags=Zt(A.contexts.flags,3,t)),n}function rF(A,e){if(!e)return A;const t=A?A.clone():new Tt;return t.update(e),t}function sF(A){if(A)return oF(A)?{captureContext:A}:cF(A)?{captureContext:A}:A}function oF(A){return A instanceof Tt||typeof A=="function"}const aF=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function cF(A){return Object.keys(A).some(e=>aF.includes(e))}function uF(A,e){return Kn().captureException(A,sF(e))}function Pp(A,e){return Kn().captureEvent(A,e)}function Dp(A){const e=Li(),t=Kn(),{userAgent:n}=Ae.navigator||{},i=DT({user:t.getUser()||e.getUser(),...n&&{userAgent:n},...A}),r=e.getSession();return r?.status==="ok"&&Mn(r,{status:"exited"}),Lp(),e.setSession(i),i}function Lp(){const A=Li(),t=Kn().getSession()||A.getSession();t&<(t),Op(),A.setSession()}function Op(){const A=Li(),e=Ne(),t=A.getSession();t&&e&&e.captureSession(t)}function Hp(A=!1){if(A){Lp();return}Op()}const lF="7";function dF(A){const e=A.protocol?`${A.protocol}:`:"",t=A.port?`:${A.port}`:"";return`${e}//${A.host}${t}${A.path?`/${A.path}`:""}/api/`}function hF(A){return`${dF(A)}${A.projectId}/envelope/`}function fF(A,e){const t={sentry_version:lF};return A.publicKey&&(t.sentry_key=A.publicKey),e&&(t.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(t).toString()}function gF(A,e,t){return e||`${hF(A)}?${fF(A,t)}`}const Mp=[];function pF(A,e){const t={};return e.forEach(n=>{n&&Kp(A,n,t)}),t}function Np(A,e){for(const t of e)t?.afterAllSetup&&t.afterAllSetup(A)}function Kp(A,e,t){if(t[e.name]){X&&N.log(`Integration skipped because it was already installed: ${e.name}`);return}if(t[e.name]=e,Mp.indexOf(e.name)===-1&&typeof e.setupOnce=="function"&&(e.setupOnce(),Mp.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(A),typeof e.preprocessEvent=="function"){const n=e.preprocessEvent.bind(e);A.on("preprocessEvent",(i,r)=>n(i,r,A))}if(typeof e.processEvent=="function"){const n=e.processEvent.bind(e),i=Object.assign((r,s)=>n(r,s,A),{id:e.name});A.addEventProcessor(i)}X&&N.log(`Integration installed: ${e.name}`)}function F_(A){return A}function Gp(A){const e=[];A.message&&e.push(A.message);try{const t=A.exception.values[A.exception.values.length-1];t?.value&&(e.push(t.value),t.type&&e.push(`${t.type}: ${t.value}`))}catch{}return e}function mF(A){const{trace_id:e,parent_span_id:t,span_id:n,status:i,origin:r,data:s,op:o}=A.contexts?.trace??{};return{data:s??{},description:A.transaction,op:o,parent_span_id:t,span_id:n??"",start_timestamp:A.start_timestamp??0,status:i,timestamp:A.timestamp,trace_id:e??"",origin:r,profile_id:s?.[dp],exclusive_time:s?.[hp],measurements:A.measurements,is_segment:!0}}function BF(A){return{type:"transaction",timestamp:A.timestamp,start_timestamp:A.start_timestamp,transaction:A.description,contexts:{trace:{trace_id:A.trace_id,span_id:A.span_id,parent_span_id:A.parent_span_id,op:A.op,status:A.status,origin:A.origin,data:{...A.data,...A.profile_id&&{[dp]:A.profile_id},...A.exclusive_time&&{[hp]:A.exclusive_time}}}},measurements:A.measurements}}function vF(A,e,t){const n=[{type:"client_report"},{timestamp:t||Pi(),discarded_events:A}];return Oi(e?{dsn:e}:{},[n])}const Vp="Not capturing exception because it's already been captured.",jp="Discarded session because of missing or non-string release",$p=Symbol.for("SentryInternalError"),Wp=Symbol.for("SentryDoNotSendEventError");function Ao(A){return{message:A,[$p]:!0}}function ou(A){return{message:A,[Wp]:!0}}function Jp(A){return!!A&&typeof A=="object"&&$p in A}function Xp(A){return!!A&&typeof A=="object"&&Wp in A}class CF{constructor(e){if(this._options=e,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],e.dsn?this._dsn=QQ(e.dsn):X&&N.warn("No DSN provided, client will not send events."),this._dsn){const t=gF(this._dsn,e.tunnel,e._metadata?e._metadata.sdk:void 0);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:t})}}captureException(e,t,n){const i=dt();if(ip(e))return X&&N.log(Vp),i;const r={event_id:i,...t};return this._process(this.eventFromException(e,r).then(s=>this._captureEvent(s,r,n))),r.event_id}captureMessage(e,t,n,i){const r={event_id:dt(),...n},s=jc(e)?e:String(e),o=$c(e)?this.eventFromMessage(s,t,r):this.eventFromException(e,r);return this._process(o.then(a=>this._captureEvent(a,r,i))),r.event_id}captureEvent(e,t,n){const i=dt();if(t?.originalException&&ip(t.originalException))return X&&N.log(Vp),i;const r={event_id:i,...t},s=e.sdkProcessingMetadata||{},o=s.capturedSpanScope,a=s.capturedSpanIsolationScope;return this._process(this._captureEvent(e,r,o||n,a)),r.event_id}captureSession(e){this.sendSession(e),Mn(e,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(e){const t=this._transport;return t?(this.emit("flush"),this._isClientDoneProcessing(e).then(n=>t.flush(e).then(i=>n&&i))):rn(!0)}close(e){return this.flush(e).then(t=>(this.getOptions().enabled=!1,this.emit("close"),t))}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}addIntegration(e){const t=this._integrations[e.name];Kp(this,e,this._integrations),t||Np(this,[e])}sendEvent(e,t={}){this.emit("beforeSendEvent",e,t);let n=jQ(e,this._dsn,this._options._metadata,this._options.tunnel);for(const r of t.attachments||[])n=LQ(n,MQ(r));const i=this.sendEnvelope(n);i&&i.then(r=>this.emit("afterSendEvent",e,r),null)}sendSession(e){const{release:t,environment:n=nu}=this._options;if("aggregates"in e){const r=e.attrs||{};if(!r.release&&!t){X&&N.warn(jp);return}r.release=r.release||t,r.environment=r.environment||n,e.attrs=r}else{if(!e.release&&!t){X&&N.warn(jp);return}e.release=e.release||t,e.environment=e.environment||n}this.emit("beforeSendSession",e);const i=VQ(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(i)}recordDroppedEvent(e,t,n=1){if(this._options.sendClientReports){const i=`${e}:${t}`;X&&N.log(`Recording outcome: "${i}"${n>1?` (${n} times)`:""}`),this._outcomes[i]=(this._outcomes[i]||0)+n}}on(e,t){const n=this._hooks[e]=this._hooks[e]||[];return n.push(t),()=>{const i=n.indexOf(t);i>-1&&n.splice(i,1)}}emit(e,...t){const n=this._hooks[e];n&&n.forEach(i=>i(...t))}sendEnvelope(e){return this.emit("beforeEnvelope",e),this._isEnabled()&&this._transport?this._transport.send(e).then(null,t=>(X&&N.error("Error while sending envelope:",t),t)):(X&&N.error("Transport disabled"),rn({}))}_setupIntegrations(){const{integrations:e}=this._options;this._integrations=pF(this,e),Np(this,e)}_updateSessionFromEvent(e,t){let n=t.level==="fatal",i=!1;const r=t.exception?.values;if(r){i=!0;for(const a of r)if(a.mechanism?.handled===!1){n=!0;break}}const s=e.status==="ok";(s&&e.errors===0||s&&n)&&(Mn(e,{...n&&{status:"crashed"},errors:e.errors||Number(i||n)}),this.captureSession(e))}_isClientDoneProcessing(e){return new xA(t=>{let n=0;const i=1,r=setInterval(()=>{this._numProcessing==0?(clearInterval(r),t(!0)):(n+=i,e&&n>=e&&(clearInterval(r),t(!1)))},i)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,t,n,i){const r=this.getOptions(),s=Object.keys(this._integrations);return!t.integrations&&s?.length&&(t.integrations=s),this.emit("preprocessEvent",e,t),e.type||i.setLastEventId(e.event_id||t.event_id),ZQ(r,e,t,n,this,i).then(o=>{if(o===null)return o;this.emit("postprocessEvent",o,t),o.contexts={trace:WT(n),...o.contexts};const a=kQ(this,n);return o.sdkProcessingMetadata={dynamicSamplingContext:a,...o.sdkProcessingMetadata},o})}_captureEvent(e,t={},n=Kn(),i=Li()){return X&&au(e)&&N.log(`Captured error event \`${Gp(e)[0]||"<unknown>"}\``),this._processEvent(e,t,n,i).then(r=>r.event_id,r=>{X&&(Xp(r)?N.log(r.message):Jp(r)?N.warn(r.message):N.warn(r))})}_processEvent(e,t,n,i){const r=this.getOptions(),{sampleRate:s}=r,o=qp(e),a=au(e),c=e.type||"error",u=`before send for type \`${c}\``,l=typeof s>"u"?void 0:nQ(s);if(a&&typeof l=="number"&&Math.random()>l)return this.recordDroppedEvent("sample_rate","error"),zs(ou(`Discarding event because it's not included in the random sample (sampling rate = ${s})`));const d=c==="replay_event"?"replay":c;return this._prepareEvent(e,t,n,i).then(h=>{if(h===null)throw this.recordDroppedEvent("event_processor",d),ou("An event processor returned `null`, will not send event.");if(t.data&&t.data.__sentry__===!0)return h;const g=yF(this,r,h,t);return wF(g,u)}).then(h=>{if(h===null){if(this.recordDroppedEvent("before_send",d),o){const B=1+(e.spans||[]).length;this.recordDroppedEvent("before_send","span",B)}throw ou(`${u} returned \`null\`, will not send event.`)}const f=n.getSession()||i.getSession();if(a&&f&&this._updateSessionFromEvent(f,h),o){const p=h.sdkProcessingMetadata?.spanCountBeforeProcessing||0,B=h.spans?h.spans.length:0,y=p-B;y>0&&this.recordDroppedEvent("before_send","span",y)}const g=h.transaction_info;if(o&&g&&h.transaction!==e.transaction){const p="custom";h.transaction_info={...g,source:p}}return this.sendEvent(h,t),h}).then(null,h=>{throw Xp(h)||Jp(h)?h:(this.captureException(h,{data:{__sentry__:!0},originalException:h}),Ao(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
|
|
117
|
+
Reason: ${h}`))})}_process(e){this._numProcessing++,e.then(t=>(this._numProcessing--,t),t=>(this._numProcessing--,t))}_clearOutcomes(){const e=this._outcomes;return this._outcomes={},Object.entries(e).map(([t,n])=>{const[i,r]=t.split(":");return{reason:i,category:r,quantity:n}})}_flushOutcomes(){X&&N.log("Flushing outcomes...");const e=this._clearOutcomes();if(e.length===0){X&&N.log("No outcomes to send");return}if(!this._dsn){X&&N.log("No dsn provided, will not send outcomes");return}X&&N.log("Sending outcomes:",e);const t=vF(e,this._options.tunnel&&Ys(this._dsn));this.sendEnvelope(t)}}function wF(A,e){const t=`${e} must return \`null\` or a valid event.`;if(Vs(A))return A.then(n=>{if(!Ri(n)&&n!==null)throw Ao(t);return n},n=>{throw Ao(`${e} rejected with ${n}`)});if(!Ri(A)&&A!==null)throw Ao(t);return A}function yF(A,e,t,n){const{beforeSend:i,beforeSendTransaction:r,beforeSendSpan:s}=e;let o=t;if(au(o)&&i)return i(o,n);if(qp(o)){if(s){const a=s(mF(o));if(a?o=Di(t,BF(a)):wp(),o.spans){const c=[];for(const u of o.spans){const l=s(u);l?c.push(l):(wp(),c.push(u))}o.spans=c}}if(r){if(o.spans){const a=o.spans.length;o.sdkProcessingMetadata={...t.sdkProcessingMetadata,spanCountBeforeProcessing:a}}return r(o,n)}}return o}function au(A){return A.type===void 0}function qp(A){return A.type==="transaction"}function bF(A){return[{type:"log",item_count:A.length,content_type:"application/vnd.sentry.items.log+json"},{items:A}]}function EF(A,e,t,n){const i={};return e?.sdk&&(i.sdk={name:e.sdk.name,version:e.sdk.version}),t&&n&&(i.dsn=Ys(n)),Oi(i,[bF(A)])}Ae._sentryClientToLogBufferMap=new WeakMap;function cu(A,e){const t=e??SF(A)??[];if(t.length===0)return;const n=A.getOptions(),i=EF(t,n._metadata,n.tunnel,A.getDsn());Ae._sentryClientToLogBufferMap?.set(A,[]),A.emit("flushLogs"),A.sendEnvelope(i)}function SF(A){return Ae._sentryClientToLogBufferMap?.get(A)}const Yp=Symbol.for("SentryBufferFullError");function UF(A){const e=[];function t(){return A===void 0||e.length<A}function n(s){return e.splice(e.indexOf(s),1)[0]||Promise.resolve(void 0)}function i(s){if(!t())return zs(Yp);const o=s();return e.indexOf(o)===-1&&e.push(o),o.then(()=>n(o)).then(null,()=>n(o).then(null,()=>{})),o}function r(s){return new xA((o,a)=>{let c=e.length;if(!c)return o(!0);const u=setTimeout(()=>{s&&s>0&&o(!1)},s);e.forEach(l=>{rn(l).then(()=>{--c||(clearTimeout(u),o(!0))},a)})})}return{$:e,add:i,drain:r}}const TF=60*1e3;function QF(A,e=Date.now()){const t=parseInt(`${A}`,10);if(!isNaN(t))return t*1e3;const n=Date.parse(`${A}`);return isNaN(n)?TF:n-e}function FF(A,e){return A[e]||A.all||0}function kF(A,e,t=Date.now()){return FF(A,e)>t}function IF(A,{statusCode:e,headers:t},n=Date.now()){const i={...A},r=t?.["x-sentry-rate-limits"],s=t?.["retry-after"];if(r)for(const o of r.trim().split(",")){const[a,c,,,u]=o.split(":",5),l=parseInt(a,10),d=(isNaN(l)?60:l)*1e3;if(!c)i.all=n+d;else for(const h of c.split(";"))h==="metric_bucket"?(!u||u.split(";").includes("custom"))&&(i[h]=n+d):i[h]=n+d}else s?i.all=n+QF(s,n):e===429&&(i.all=n+60*1e3);return i}const _F=64;function xF(A,e,t=UF(A.bufferSize||_F)){let n={};const i=s=>t.drain(s);function r(s){const o=[];if(kp(s,(l,d)=>{const h=Ip(d);kF(n,h)?A.recordDroppedEvent("ratelimit_backoff",h):o.push(l)}),o.length===0)return rn({});const a=Oi(s[0],o),c=l=>{kp(a,(d,h)=>{A.recordDroppedEvent(l,Ip(h))})},u=()=>e({body:OQ(a)}).then(l=>(l.statusCode!==void 0&&(l.statusCode<200||l.statusCode>=300)&&X&&N.warn(`Sentry responded with status code ${l.statusCode} to sent event.`),n=IF(n,l),l),l=>{throw c("network_error"),X&&N.error("Encountered error running transport request:",l),l});return t.add(u).then(l=>l,l=>{if(l===Yp)return X&&N.error("Skipped sending event because buffer is full."),c("queue_overflow"),rn({});throw l})}return{send:r,flush:i}}function RF(A){A.user?.ip_address===void 0&&(A.user={...A.user,ip_address:"{{auto}}"})}function PF(A){"aggregates"in A?A.attrs?.ip_address===void 0&&(A.attrs={...A.attrs,ip_address:"{{auto}}"}):A.ipAddress===void 0&&(A.ipAddress="{{auto}}")}function DF(A,e,t=[e],n="npm"){const i=A._metadata||{};i.sdk||(i.sdk={name:`sentry.javascript.${e}`,packages:t.map(r=>({name:`${n}:@sentry/${r}`,version:zA})),version:zA}),A._metadata=i}const LF=100;function sn(A,e){const t=Ne(),n=Li();if(!t)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:r=LF}=t.getOptions();if(r<=0)return;const o={timestamp:Pi(),...A},a=i?$s(()=>i(o,e)):o;a!==null&&(t.emit&&t.emit("beforeAddBreadcrumb",a,e),n.addBreadcrumb(a,r))}let zp;const OF="FunctionToString",Zp=new WeakMap,HF=()=>({name:OF,setupOnce(){zp=Function.prototype.toString;try{Function.prototype.toString=function(...A){const e=Xc(this),t=Zp.has(Ne())&&e!==void 0?e:this;return zp.apply(t,A)}}catch{}},setup(A){Zp.set(A,!0)}}),MF=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/,/^Java exception was raised during method invocation$/],NF="EventFilters",KF=(A={})=>{let e;return{name:NF,setup(t){const n=t.getOptions();e=em(A,n)},processEvent(t,n,i){if(!e){const r=i.getOptions();e=em(A,r)}return VF(t,e)?null:t}}},GF=(A={})=>({...KF(A),name:"InboundFilters"});function em(A={},e={}){return{allowUrls:[...A.allowUrls||[],...e.allowUrls||[]],denyUrls:[...A.denyUrls||[],...e.denyUrls||[]],ignoreErrors:[...A.ignoreErrors||[],...e.ignoreErrors||[],...A.disableErrorDefaults?[]:MF],ignoreTransactions:[...A.ignoreTransactions||[],...e.ignoreTransactions||[]]}}function VF(A,e){if(A.type){if(A.type==="transaction"&&$F(A,e.ignoreTransactions))return X&&N.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.
|
|
118
|
+
Event: ${en(A)}`),!0}else{if(jF(A,e.ignoreErrors))return X&&N.warn(`Event dropped due to being matched by \`ignoreErrors\` option.
|
|
119
|
+
Event: ${en(A)}`),!0;if(qF(A))return X&&N.warn(`Event dropped due to not having an error message, error type or stacktrace.
|
|
120
|
+
Event: ${en(A)}`),!0;if(WF(A,e.denyUrls))return X&&N.warn(`Event dropped due to being matched by \`denyUrls\` option.
|
|
121
121
|
Event: ${en(A)}.
|
|
122
|
-
Url: ${no(A)}`),!0;if(!
|
|
122
|
+
Url: ${no(A)}`),!0;if(!JF(A,e.allowUrls))return X&&N.warn(`Event dropped due to not being matched by \`allowUrls\` option.
|
|
123
123
|
Event: ${en(A)}.
|
|
124
|
-
Url: ${no(A)}`),!0}return!1}function $F(A,e){return e?.length?Gp(A).some(t=>Js(t,e)):!1}function WF(A,e){if(!e?.length)return!1;const t=A.transaction;return t?Js(t,e):!1}function JF(A,e){if(!e?.length)return!1;const t=no(A);return t?Js(t,e):!1}function XF(A,e){if(!e?.length)return!0;const t=no(A);return t?Js(t,e):!0}function qF(A=[]){for(let e=A.length-1;e>=0;e--){const t=A[e];if(t&&t.filename!=="<anonymous>"&&t.filename!=="[native code]")return t.filename||null}return null}function no(A){try{const t=[...A.exception?.values??[]].reverse().find(n=>n.mechanism?.parent_id===void 0&&n.stacktrace?.frames?.length)?.stacktrace?.frames;return t?qF(t):null}catch{return X&&N.error(`Cannot extract url for event ${en(A)}`),null}}function YF(A){return A.exception?.values?.length?!A.message&&!A.exception.values.some(e=>e.stacktrace||e.type&&e.type!=="Error"||e.value):!1}function zF(A,e,t,n,i,r){if(!i.exception?.values||!r||!IA(r.originalException,Error))return;const s=i.exception.values.length>0?i.exception.values[i.exception.values.length-1]:void 0;s&&(i.exception.values=du(A,e,n,r.originalException,t,i.exception.values,s,0))}function du(A,e,t,n,i,r,s,o){if(r.length>=t+1)return r;let a=[...r];if(IA(n[i],Error)){tm(s,o);const c=A(e,n[i]),u=a.length;Am(c,i,u,o),a=du(A,e,t,n[i],i,[c,...a],c,u)}return Array.isArray(n.errors)&&n.errors.forEach((c,u)=>{if(IA(c,Error)){tm(s,o);const l=A(e,c),d=a.length;Am(l,`errors[${u}]`,d,o),a=du(A,e,t,c,i,[l,...a],l,d)}}),a}function tm(A,e){A.mechanism=A.mechanism||{type:"generic",handled:!0},A.mechanism={...A.mechanism,...A.type==="AggregateError"&&{is_exception_group:!0},exception_id:e}}function Am(A,e,t,n){A.mechanism=A.mechanism||{type:"generic",handled:!0},A.mechanism={...A.mechanism,type:"chained",source:e,exception_id:t,parent_id:n}}function ZF(A){const e="console";An(e,A),nn(e,ek)}function ek(){"console"in Ae&&qc.forEach(function(A){A in Ae.console&&it(Ae.console,A,function(e){return js[A]=e,function(...t){Qt("console",{args:t,level:A}),js[A]?.apply(Ae.console,t)}})})}function tk(A){return A==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(A)?A:"log"}const Ak="Dedupe",nk=()=>{let A;return{name:Ak,processEvent(e){if(e.type)return e;try{if(ik(e,A))return X&&N.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return A=e}}};function ik(A,e){return e?!!(rk(A,e)||sk(A,e)):!1}function rk(A,e){const t=A.message,n=e.message;return!(!t&&!n||t&&!n||!t&&n||t!==n||!im(A,e)||!nm(A,e))}function sk(A,e){const t=rm(e),n=rm(A);return!(!t||!n||t.type!==n.type||t.value!==n.value||!im(A,e)||!nm(A,e))}function nm(A,e){let t=Sp(A),n=Sp(e);if(!t&&!n)return!0;if(t&&!n||!t&&n||(t=t,n=n,n.length!==t.length))return!1;for(let i=0;i<n.length;i++){const r=n[i],s=t[i];if(r.filename!==s.filename||r.lineno!==s.lineno||r.colno!==s.colno||r.function!==s.function)return!1}return!0}function im(A,e){let t=A.fingerprint,n=e.fingerprint;if(!t&&!n)return!0;if(t&&!n||!t&&n)return!1;t=t,n=n;try{return t.join("")===n.join("")}catch{return!1}}function rm(A){return A.exception?.values&&A.exception.values[0]}function hu(A){if(!A)return{};const e=A.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const t=e[6]||"",n=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:t,hash:n,relative:e[5]+t+n}}function sm(A){if(A!==void 0)return A>=400&&A<500?"warning":A>=500?"error":void 0}const Hi=Ae;function ok(){return"history"in Hi&&!!Hi.history}function ak(){if(!("fetch"in Hi))return!1;try{return new Headers,new Request("http://www.example.com"),new Response,!0}catch{return!1}}function fu(A){return A&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(A.toString())}function ck(){if(typeof EdgeRuntime=="string")return!0;if(!ak())return!1;if(fu(Hi.fetch))return!0;let A=!1;const e=Hi.document;if(e&&typeof e.createElement=="function")try{const t=e.createElement("iframe");t.hidden=!0,e.head.appendChild(t),t.contentWindow?.fetch&&(A=fu(t.contentWindow.fetch)),e.head.removeChild(t)}catch(t){X&&N.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",t)}return A}function uk(A,e){const t="fetch";An(t,A),nn(t,()=>lk(void 0,e))}function lk(A,e=!1){e&&!ck()||it(Ae,"fetch",function(t){return function(...n){const i=new Error,{method:r,url:s}=dk(n),o={args:n,fetchData:{method:r,url:s},startTimestamp:zt()*1e3,virtualError:i,headers:hk(n)};return A||Qt("fetch",{...o}),t.apply(Ae,n).then(async a=>(A?A(a):Qt("fetch",{...o,endTimestamp:zt()*1e3,response:a}),a),a=>{if(Qt("fetch",{...o,endTimestamp:zt()*1e3,error:a}),$c(a)&&a.stack===void 0&&(a.stack=i.stack,ZA(a,"framesToPop",1)),a instanceof TypeError&&(a.message==="Failed to fetch"||a.message==="Load failed"||a.message==="NetworkError when attempting to fetch resource."))try{const c=new URL(o.fetchData.url);a.message=`${a.message} (${c.host})`}catch{}throw a})}})}function gu(A,e){return!!A&&typeof A=="object"&&!!A[e]}function om(A){return typeof A=="string"?A:A?gu(A,"url")?A.url:A.toString?A.toString():"":""}function dk(A){if(A.length===0)return{method:"GET",url:""};if(A.length===2){const[t,n]=A;return{url:om(t),method:gu(n,"method")?String(n.method).toUpperCase():"GET"}}const e=A[0];return{url:om(e),method:gu(e,"method")?String(e.method).toUpperCase():"GET"}}function hk(A){const[e,t]=A;try{if(typeof t=="object"&&t!==null&&"headers"in t&&t.headers)return new Headers(t.headers);if(UT(e))return new Headers(e.headers)}catch{}}function fk(){return"npm"}const xe=Ae;let pu=0;function am(){return pu>0}function gk(){pu++,setTimeout(()=>{pu--})}function Gn(A,e={}){function t(i){return typeof i=="function"}if(!t(A))return A;try{const i=A.__sentry_wrapped__;if(i)return typeof i=="function"?i:A;if(Yc(A))return A}catch{return A}const n=function(...i){try{const r=i.map(s=>Gn(s,e));return A.apply(this,r)}catch(r){throw gk(),lp(s=>{s.addEventProcessor(o=>(e.mechanism&&(zc(o,void 0,void 0),Hn(o,e.mechanism)),o.extra={...o.extra,arguments:i},o)),lF(r)}),r}};try{for(const i in A)Object.prototype.hasOwnProperty.call(A,i)&&(n[i]=A[i])}catch{}Zg(n,A),ZA(A,"__sentry_wrapped__",n);try{Object.getOwnPropertyDescriptor(n,"name").configurable&&Object.defineProperty(n,"name",{get(){return A.name}})}catch{}return n}function pk(){const A=Yg(),{referrer:e}=xe.document||{},{userAgent:t}=xe.navigator||{},n={...e&&{Referer:e},...t&&{"User-Agent":t}};return{url:A,headers:n}}function mu(A,e){const t=vu(A,e),n={type:wk(e),value:yk(e)};return t.length&&(n.stacktrace={frames:t}),n.type===void 0&&n.value===""&&(n.value="Unrecoverable error caught"),n}function mk(A,e,t,n){const r=Ne()?.getOptions().normalizeDepth,s=Tk(e),o={__serialized__:Fp(e,r)};if(s)return{exception:{values:[mu(A,s)]},extra:o};const a={exception:{values:[{type:Gs(e)?e.constructor.name:n?"UnhandledRejection":"Error",value:Sk(e,{isUnhandledRejection:n})}]},extra:o};if(t){const c=vu(A,t);c.length&&(a.exception.values[0].stacktrace={frames:c})}return a}function Bu(A,e){return{exception:{values:[mu(A,e)]}}}function vu(A,e){const t=e.stacktrace||e.stack||"",n=vk(e),i=Ck(e);try{return A(t,n,i)}catch{}return[]}const Bk=/Minified React error #\d+;/i;function vk(A){return A&&Bk.test(A.message)?1:0}function Ck(A){return typeof A.framesToPop=="number"?A.framesToPop:0}function cm(A){return typeof WebAssembly<"u"&&typeof WebAssembly.Exception<"u"?A instanceof WebAssembly.Exception:!1}function wk(A){const e=A?.name;return!e&&cm(A)?A.message&&Array.isArray(A.message)&&A.message.length==2?A.message[0]:"WebAssembly.Exception":e}function yk(A){const e=A?.message;return cm(A)?Array.isArray(A.message)&&A.message.length==2?A.message[1]:"wasm exception":e?e.error&&typeof e.error.message=="string"?e.error.message:e:"No error message"}function bk(A,e,t,n){const i=t?.syntheticException||void 0,r=Cu(A,e,i,n);return Hn(r),r.level="error",t?.event_id&&(r.event_id=t.event_id),rn(r)}function Ek(A,e,t="info",n,i){const r=n?.syntheticException||void 0,s=wu(A,e,r,i);return s.level=t,n?.event_id&&(s.event_id=n.event_id),rn(s)}function Cu(A,e,t,n,i){let r;if(Wg(e)&&e.error)return Bu(A,e.error);if(Jg(e)||yT(e)){const s=e;if("stack"in e)r=Bu(A,e);else{const o=s.name||(Jg(s)?"DOMError":"DOMException"),a=s.message?`${o}: ${s.message}`:o;r=wu(A,a,t,n),zc(r,a)}return"code"in s&&(r.tags={...r.tags,"DOMException.code":`${s.code}`}),r}return $c(e)?Bu(A,e):Ri(e)||Gs(e)?(r=mk(A,e,t,i),Hn(r,{synthetic:!0}),r):(r=wu(A,e,t,n),zc(r,`${e}`,void 0),Hn(r,{synthetic:!0}),r)}function wu(A,e,t,n){const i={};if(n&&t){const r=vu(A,t);r.length&&(i.exception={values:[{value:e,stacktrace:{frames:r}}]}),Hn(i,{synthetic:!0})}if(Wc(e)){const{__sentry_template_string__:r,__sentry_template_values__:s}=e;return i.logentry={message:r,params:s},i}return i.message=e,i}function Sk(A,{isUnhandledRejection:e}){const t=xT(A),n=e?"promise rejection":"exception";return Wg(A)?`Event \`ErrorEvent\` captured as ${n} with message \`${A.message}\``:Gs(A)?`Event \`${Uk(A)}\` (type=${A.type}) captured as ${n}`:`Object captured as ${n} with keys: ${t}`}function Uk(A){try{const e=Object.getPrototypeOf(A);return e?e.constructor.name:void 0}catch{}}function Tk(A){for(const e in A)if(Object.prototype.hasOwnProperty.call(A,e)){const t=A[e];if(t instanceof Error)return t}}const Qk=5e3;class Fk extends wF{constructor(e){const t=kk(e),n=xe.SENTRY_SDK_SOURCE||fk();LF(t,"browser",["browser"],n),super(t);const{sendDefaultPii:i,sendClientReports:r,_experiments:s}=this._options,o=s?.enableLogs;xe.document&&(r||o)&&xe.document.addEventListener("visibilitychange",()=>{xe.document.visibilityState==="hidden"&&(r&&this._flushOutcomes(),o&&lu(this))}),o&&(this.on("flush",()=>{lu(this)}),this.on("afterCaptureLog",()=>{this._logFlushIdleTimeout&&clearTimeout(this._logFlushIdleTimeout),this._logFlushIdleTimeout=setTimeout(()=>{lu(this)},Qk)})),i&&(this.on("postprocessEvent",PF),this.on("beforeSendSession",DF))}eventFromException(e,t){return bk(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t="info",n){return Ek(this._options.stackParser,e,t,n,this._options.attachStacktrace)}_prepareEvent(e,t,n,i){return e.platform=e.platform||"javascript",super._prepareEvent(e,t,n,i)}}function kk(A){return{release:typeof __SENTRY_RELEASE__=="string"?__SENTRY_RELEASE__:xe.SENTRY_RELEASE?.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...A}}const Ik=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Ke=Ae,_k=1e3;let um,yu,bu;function xk(A){const e="dom";An(e,A),nn(e,Rk)}function Rk(){if(!Ke.document)return;const A=Qt.bind(null,"dom"),e=lm(A,!0);Ke.document.addEventListener("click",e,!1),Ke.document.addEventListener("keypress",e,!1),["EventTarget","Node"].forEach(t=>{const i=Ke[t]?.prototype;i?.hasOwnProperty?.("addEventListener")&&(it(i,"addEventListener",function(r){return function(s,o,a){if(s==="click"||s=="keypress")try{const c=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},u=c[s]=c[s]||{refCount:0};if(!u.handler){const l=lm(A);u.handler=l,r.call(this,s,l,a)}u.refCount++}catch{}return r.call(this,s,o,a)}}),it(i,"removeEventListener",function(r){return function(s,o,a){if(s==="click"||s=="keypress")try{const c=this.__sentry_instrumentation_handlers__||{},u=c[s];u&&(u.refCount--,u.refCount<=0&&(r.call(this,s,u.handler,a),u.handler=void 0,delete c[s]),Object.keys(c).length===0&&delete this.__sentry_instrumentation_handlers__)}catch{}return r.call(this,s,o,a)}}))})}function Pk(A){if(A.type!==yu)return!1;try{if(!A.target||A.target._sentryId!==bu)return!1}catch{}return!0}function Dk(A,e){return A!=="keypress"?!1:e?.tagName?!(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable):!0}function lm(A,e=!1){return t=>{if(!t||t._sentryCaptured)return;const n=Lk(t);if(Dk(t.type,n))return;ZA(t,"_sentryCaptured",!0),n&&!n._sentryId&&ZA(n,"_sentryId",dt());const i=t.type==="keypress"?"input":t.type;Pk(t)||(A({event:t,name:i,global:e}),yu=t.type,bu=n?n._sentryId:void 0),clearTimeout(um),um=Ke.setTimeout(()=>{bu=void 0,yu=void 0},_k)}}function Lk(A){try{return A.target}catch{return null}}let io;function dm(A){const e="history";An(e,A),nn(e,Ok)}function Ok(){if(Ke.addEventListener("popstate",()=>{const e=Ke.location.href,t=io;if(io=e,t===e)return;Qt("history",{from:t,to:e})}),!ok())return;function A(e){return function(...t){const n=t.length>2?t[2]:void 0;if(n){const i=io,r=Hk(String(n));if(io=r,i===r)return e.apply(this,t);Qt("history",{from:i,to:r})}return e.apply(this,t)}}it(Ke.history,"pushState",A),it(Ke.history,"replaceState",A)}function Hk(A){try{return new URL(A,Ke.location.origin).toString()}catch{return A}}const ro={};function Mk(A){const e=ro[A];if(e)return e;let t=Ke[A];if(fu(t))return ro[A]=t.bind(Ke);const n=Ke.document;if(n&&typeof n.createElement=="function")try{const i=n.createElement("iframe");i.hidden=!0,n.head.appendChild(i);const r=i.contentWindow;r?.[A]&&(t=r[A]),n.head.removeChild(i)}catch(i){Ik&&N.warn(`Could not create sandbox iframe for ${A} check, bailing to window.${A}: `,i)}return t&&(ro[A]=t.bind(Ke))}function hm(A){ro[A]=void 0}const Mi="__sentry_xhr_v3__";function Nk(A){const e="xhr";An(e,A),nn(e,Kk)}function Kk(){if(!Ke.XMLHttpRequest)return;const A=XMLHttpRequest.prototype;A.open=new Proxy(A.open,{apply(e,t,n){const i=new Error,r=zt()*1e3,s=Yt(n[0])?n[0].toUpperCase():void 0,o=Gk(n[1]);if(!s||!o)return e.apply(t,n);t[Mi]={method:s,url:o,request_headers:{}},s==="POST"&&o.match(/sentry_key/)&&(t.__sentry_own_request__=!0);const a=()=>{const c=t[Mi];if(c&&t.readyState===4){try{c.status_code=t.status}catch{}const u={endTimestamp:zt()*1e3,startTimestamp:r,xhr:t,virtualError:i};Qt("xhr",u)}};return"onreadystatechange"in t&&typeof t.onreadystatechange=="function"?t.onreadystatechange=new Proxy(t.onreadystatechange,{apply(c,u,l){return a(),c.apply(u,l)}}):t.addEventListener("readystatechange",a),t.setRequestHeader=new Proxy(t.setRequestHeader,{apply(c,u,l){const[d,h]=l,f=u[Mi];return f&&Yt(d)&&Yt(h)&&(f.request_headers[d.toLowerCase()]=h),c.apply(u,l)}}),e.apply(t,n)}}),A.send=new Proxy(A.send,{apply(e,t,n){const i=t[Mi];if(!i)return e.apply(t,n);n[0]!==void 0&&(i.body=n[0]);const r={startTimestamp:zt()*1e3,xhr:t};return Qt("xhr",r),e.apply(t,n)}})}function Gk(A){if(Yt(A))return A;try{return A.toString()}catch{}}function Vk(A,e=Mk("fetch")){let t=0,n=0;function i(r){const s=r.body.length;t+=s,n++;const o={body:r.body,method:"POST",referrerPolicy:"strict-origin",headers:A.headers,keepalive:t<=6e4&&n<15,...A.fetchOptions};if(!e)return hm("fetch"),zs("No fetch implementation available");try{return e(A.url,o).then(a=>(t-=s,n--,{statusCode:a.status,headers:{"x-sentry-rate-limits":a.headers.get("X-Sentry-Rate-Limits"),"retry-after":a.headers.get("Retry-After")}}))}catch(a){return hm("fetch"),t-=s,n--,zs(a)}}return RF(A,i)}const jk=30,$k=50;function Eu(A,e,t,n){const i={filename:A,function:e==="<anonymous>"?tn:e,in_app:!0};return t!==void 0&&(i.lineno=t),n!==void 0&&(i.colno=n),i}const Wk=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Jk=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Xk=/\((\S*)(?::(\d+))(?::(\d+))\)/,qk=[jk,A=>{const e=Wk.exec(A);if(e){const[,n,i,r]=e;return Eu(n,tn,+i,+r)}const t=Jk.exec(A);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=Xk.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=fm(t[1]||tn,t[2]);return Eu(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}}],Yk=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zk=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Zk=pQ(...[qk,[$k,A=>{const e=Yk.exec(A);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=zk.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let n=e[3],i=e[1]||tn;return[i,n]=fm(i,n),Eu(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]),fm=(A,e)=>{const t=A.indexOf("safari-extension")!==-1,n=A.indexOf("safari-web-extension")!==-1;return t||n?[A.indexOf("@")!==-1?A.split("@")[0]:tn,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[A,e]},Su=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,so=1024,eI="Breadcrumbs",tI=(A={})=>{const e={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...A};return{name:eI,setup(t){e.console&&ZF(iI(t)),e.dom&&xk(nI(t,e.dom)),e.xhr&&Nk(rI(t)),e.fetch&&uk(sI(t)),e.history&&dm(oI(t)),e.sentry&&t.on("beforeSendEvent",AI(t))}}};function AI(A){return function(t){Ne()===A&&sn({category:`sentry.${t.type==="transaction"?"transaction":"event"}`,event_id:t.event_id,level:t.level,message:en(t)},{event:t})}}function nI(A,e){return function(n){if(Ne()!==A)return;let i,r,s=typeof e=="object"?e.serializeAttribute:void 0,o=typeof e=="object"&&typeof e.maxStringLength=="number"?e.maxStringLength:void 0;o&&o>so&&(Su&&N.warn(`\`dom.maxStringLength\` cannot exceed ${so}, but a value of ${o} was configured. Sentry will use ${so} instead.`),o=so),typeof s=="string"&&(s=[s]);try{const c=n.event,u=aI(c)?c.target:c;i=qg(u,{keyAttrs:s,maxStringLength:o}),r=FT(u)}catch{i="<unknown>"}if(i.length===0)return;const a={category:`ui.${n.name}`,message:i};r&&(a.data={"ui.component_name":r}),sn(a,{event:n.event,name:n.name,global:n.global})}}function iI(A){return function(t){if(Ne()!==A)return;const n={category:"console",data:{arguments:t.args,logger:"console"},level:tk(t.level),message:zg(t.args," ")};if(t.level==="assert")if(t.args[0]===!1)n.message=`Assertion failed: ${zg(t.args.slice(1)," ")||"console.assert"}`,n.data.arguments=t.args.slice(1);else return;sn(n,{input:t.args,level:t.level})}}function rI(A){return function(t){if(Ne()!==A)return;const{startTimestamp:n,endTimestamp:i}=t,r=t.xhr[Mi];if(!n||!i||!r)return;const{method:s,url:o,status_code:a,body:c}=r,u={method:s,url:o,status_code:a},l={xhr:t.xhr,input:c,startTimestamp:n,endTimestamp:i},d={category:"xhr",data:u,type:"http",level:sm(a)};A.emit("beforeOutgoingRequestBreadcrumb",d,l),sn(d,l)}}function sI(A){return function(t){if(Ne()!==A)return;const{startTimestamp:n,endTimestamp:i}=t;if(i&&!(t.fetchData.url.match(/sentry_key/)&&t.fetchData.method==="POST"))if(t.fetchData.method,t.fetchData.url,t.error){const r=t.fetchData,s={data:t.error,input:t.args,startTimestamp:n,endTimestamp:i},o={category:"fetch",data:r,level:"error",type:"http"};A.emit("beforeOutgoingRequestBreadcrumb",o,s),sn(o,s)}else{const r=t.response,s={...t.fetchData,status_code:r?.status};t.fetchData.request_body_size,t.fetchData.response_body_size,r?.status;const o={input:t.args,response:r,startTimestamp:n,endTimestamp:i},a={category:"fetch",data:s,type:"http",level:sm(s.status_code)};A.emit("beforeOutgoingRequestBreadcrumb",a,o),sn(a,o)}}}function oI(A){return function(t){if(Ne()!==A)return;let n=t.from,i=t.to;const r=hu(xe.location.href);let s=n?hu(n):void 0;const o=hu(i);s?.path||(s=r),r.protocol===o.protocol&&r.host===o.host&&(i=o.relative),r.protocol===s.protocol&&r.host===s.host&&(n=s.relative),sn({category:"navigation",data:{from:n,to:i}})}}function aI(A){return!!A&&!!A.target}const cI=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],uI="BrowserApiErrors",lI=(A={})=>{const e={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...A};return{name:uI,setupOnce(){e.setTimeout&&it(xe,"setTimeout",gm),e.setInterval&&it(xe,"setInterval",gm),e.requestAnimationFrame&&it(xe,"requestAnimationFrame",dI),e.XMLHttpRequest&&"XMLHttpRequest"in xe&&it(XMLHttpRequest.prototype,"send",hI);const t=e.eventTarget;t&&(Array.isArray(t)?t:cI).forEach(fI)}}};function gm(A){return function(...e){const t=e[0];return e[0]=Gn(t,{mechanism:{data:{function:_A(A)},handled:!1,type:"instrument"}}),A.apply(this,e)}}function dI(A){return function(e){return A.apply(this,[Gn(e,{mechanism:{data:{function:"requestAnimationFrame",handler:_A(A)},handled:!1,type:"instrument"}})])}}function hI(A){return function(...e){const t=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(i=>{i in t&&typeof t[i]=="function"&&it(t,i,function(r){const s={mechanism:{data:{function:i,handler:_A(r)},handled:!1,type:"instrument"}},o=Yc(r);return o&&(s.mechanism.data.handler=_A(o)),Gn(r,s)})}),A.apply(this,e)}}function fI(A){const t=xe[A]?.prototype;t?.hasOwnProperty?.("addEventListener")&&(it(t,"addEventListener",function(n){return function(i,r,s){try{gI(r)&&(r.handleEvent=Gn(r.handleEvent,{mechanism:{data:{function:"handleEvent",handler:_A(r),target:A},handled:!1,type:"instrument"}}))}catch{}return n.apply(this,[i,Gn(r,{mechanism:{data:{function:"addEventListener",handler:_A(r),target:A},handled:!1,type:"instrument"}}),s])}}),it(t,"removeEventListener",function(n){return function(i,r,s){try{const o=r.__sentry_wrapped__;o&&n.call(this,i,o,s)}catch{}return n.call(this,i,r,s)}}))}function gI(A){return typeof A.handleEvent=="function"}const pI=()=>({name:"BrowserSession",setupOnce(){if(typeof xe.document>"u"){Su&&N.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");return}Dp({ignoreDuration:!0}),Hp(),dm(({from:A,to:e})=>{A!==void 0&&A!==e&&(Dp({ignoreDuration:!0}),Hp())})}}),mI="GlobalHandlers",BI=(A={})=>{const e={onerror:!0,onunhandledrejection:!0,...A};return{name:mI,setupOnce(){Error.stackTraceLimit=50},setup(t){e.onerror&&(vI(t),pm("onerror")),e.onunhandledrejection&&(CI(t),pm("onunhandledrejection"))}}};function vI(A){BQ(e=>{const{stackParser:t,attachStacktrace:n}=mm();if(Ne()!==A||am())return;const{msg:i,url:r,line:s,column:o,error:a}=e,c=bI(Cu(t,a||i,void 0,n,!1),r,s,o);c.level="error",Pp(c,{originalException:a,mechanism:{handled:!1,type:"onerror"}})})}function CI(A){CQ(e=>{const{stackParser:t,attachStacktrace:n}=mm();if(Ne()!==A||am())return;const i=wI(e),r=Jc(i)?yI(i):Cu(t,i,void 0,n,!0);r.level="error",Pp(r,{originalException:i,mechanism:{handled:!1,type:"onunhandledrejection"}})})}function wI(A){if(Jc(A))return A;try{if("reason"in A)return A.reason;if("detail"in A&&"reason"in A.detail)return A.detail.reason}catch{}return A}function yI(A){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(A)}`}]}}}function bI(A,e,t,n){const i=A.exception=A.exception||{},r=i.values=i.values||[],s=r[0]=r[0]||{},o=s.stacktrace=s.stacktrace||{},a=o.frames=o.frames||[],c=n,u=t,l=Yt(e)&&e.length>0?e:Yg();return a.length===0&&a.push({colno:c,filename:l,function:tn,in_app:!0,lineno:u}),A}function pm(A){Su&&N.log(`Global Handler attached: ${A}`)}function mm(){return Ne()?.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}const EI=()=>({name:"HttpContext",preprocessEvent(A){if(!xe.navigator&&!xe.location&&!xe.document)return;const e=pk(),t={...e.headers,...A.request?.headers};A.request={...e,...A.request,headers:t}}}),SI="cause",UI=5,TI="LinkedErrors",QI=(A={})=>{const e=A.limit||UI,t=A.key||SI;return{name:TI,preprocessEvent(n,i,r){const s=r.getOptions();zF(mu,s.stackParser,t,e,n,i)}}};function FI(A){return[VF(),MF(),lI(),tI(),BI(),QI(),nk(),EI(),pI()]}function kI(){const A=FI().filter(n=>!["BrowserApiErrors","Breadcrumbs","GlobalHandlers","HttpContext"].includes(n.name)),e=new Fk({dsn:"https://ac54bd10eac67be2dafbc346e704e4d4@o4507251798835200.ingest.us.sentry.io/4509409566392320",environment:"production",transport:Vk,stackParser:Zk,integrations:A,beforeSend(n,i){const r=i.originalException;return r instanceof Error&&(r.message.includes("Failed to fetch")||r.message.includes("Network request failed")||r.message.includes("Load failed")||r.message.includes("Permission denied")||r.message.includes("NotAllowedError"))?null:n},release:process.env.npm_package_version||"0.6.2"}),t=new Tt;return t.setClient(e),e.init(),t}let oo=null,rt={};function II(){oo||(oo=kI())}function ht(A,e){{if(II(),!oo)return;lp(t=>{Object.entries(rt).forEach(([n,i])=>{i!==void 0&&t.setTag(n,String(i))}),e&&(Object.entries(e).forEach(([n,i])=>{i!==void 0&&t.setTag(n,String(i))}),(e.userId||e.userEmail)&&t.setUser({id:e.userId,email:e.userEmail,...e.userMetadata}),(e.eventType||e.eventData||e.userJourney)&&t.setContext("eventContext",{eventType:e.eventType,eventData:e.eventData,userJourney:e.userJourney,timestamp:new Date().toISOString()})),oo.captureException(A)})}}function se(A,e,t){rt.eventType=A,rt.eventData=e,rt.userJourney||(rt.userJourney=[]);const n=`${new Date().toISOString()}: ${A}${t?` (${t})`:""}`;rt.userJourney.push(n),rt.userJourney.length>10&&(rt.userJourney=rt.userJourney.slice(-10))}function Ni(A){rt={...rt,...A}}function Ki(A,e,t){return async(...n)=>{try{se(`${e}_started`,{componentName:t},t);const i=await A(...n);return se(`${e}_completed`,{componentName:t},t),i}catch(i){throw ht(i,{...rt,componentName:t,handlerName:e,eventType:`${e}_failed`,eventData:{error:i instanceof Error?i.message:String(i)}}),i}}}function _I(A,e,t){return(...n)=>{try{se(`${e}_started`,{componentName:t},t);const i=A(...n);return se(`${e}_completed`,{componentName:t},t),i}catch(i){throw ht(i,{...rt,componentName:t,handlerName:e,eventType:`${e}_failed`,eventData:{error:i instanceof Error?i.message:String(i)}}),i}}}function Bm(A){return{trackLifecycle:(e,t)=>{try{se(`${A}_${e}`,{},A),t()}catch(n){throw ht(n,{componentName:A,lifecycle:e,eventType:`${A}_${e}_failed`}),n}},trackRender:e=>{try{return e()}catch(t){return ht(t,{componentName:A,lifecycle:"render",eventType:`${A}_render_failed`}),L.html`<div>Error rendering ${A}</div>`}},setContext:()=>{Ni({componentName:A}),se(`${A}_initialized`,{},A)}}}var xI=Object.defineProperty,RI=Object.getOwnPropertyDescriptor,ao=(A,e,t,n)=>{for(var i=n>1?void 0:n?RI(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&xI(e,t,i),i};class Vn extends L.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("obi-nav-icon-click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return L.html`
|
|
124
|
+
Url: ${no(A)}`),!0}return!1}function jF(A,e){return e?.length?Gp(A).some(t=>Js(t,e)):!1}function $F(A,e){if(!e?.length)return!1;const t=A.transaction;return t?Js(t,e):!1}function WF(A,e){if(!e?.length)return!1;const t=no(A);return t?Js(t,e):!1}function JF(A,e){if(!e?.length)return!0;const t=no(A);return t?Js(t,e):!0}function XF(A=[]){for(let e=A.length-1;e>=0;e--){const t=A[e];if(t&&t.filename!=="<anonymous>"&&t.filename!=="[native code]")return t.filename||null}return null}function no(A){try{const t=[...A.exception?.values??[]].reverse().find(n=>n.mechanism?.parent_id===void 0&&n.stacktrace?.frames?.length)?.stacktrace?.frames;return t?XF(t):null}catch{return X&&N.error(`Cannot extract url for event ${en(A)}`),null}}function qF(A){return A.exception?.values?.length?!A.message&&!A.exception.values.some(e=>e.stacktrace||e.type&&e.type!=="Error"||e.value):!1}function YF(A,e,t,n,i,r){if(!i.exception?.values||!r||!IA(r.originalException,Error))return;const s=i.exception.values.length>0?i.exception.values[i.exception.values.length-1]:void 0;s&&(i.exception.values=uu(A,e,n,r.originalException,t,i.exception.values,s,0))}function uu(A,e,t,n,i,r,s,o){if(r.length>=t+1)return r;let a=[...r];if(IA(n[i],Error)){tm(s,o);const c=A(e,n[i]),u=a.length;Am(c,i,u,o),a=uu(A,e,t,n[i],i,[c,...a],c,u)}return Array.isArray(n.errors)&&n.errors.forEach((c,u)=>{if(IA(c,Error)){tm(s,o);const l=A(e,c),d=a.length;Am(l,`errors[${u}]`,d,o),a=uu(A,e,t,c,i,[l,...a],l,d)}}),a}function tm(A,e){A.mechanism=A.mechanism||{type:"generic",handled:!0},A.mechanism={...A.mechanism,...A.type==="AggregateError"&&{is_exception_group:!0},exception_id:e}}function Am(A,e,t,n){A.mechanism=A.mechanism||{type:"generic",handled:!0},A.mechanism={...A.mechanism,type:"chained",source:e,exception_id:t,parent_id:n}}function zF(A){const e="console";An(e,A),nn(e,ZF)}function ZF(){"console"in Ae&&Jc.forEach(function(A){A in Ae.console&&it(Ae.console,A,function(e){return js[A]=e,function(...t){Qt("console",{args:t,level:A}),js[A]?.apply(Ae.console,t)}})})}function ek(A){return A==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(A)?A:"log"}const tk="Dedupe",Ak=()=>{let A;return{name:tk,processEvent(e){if(e.type)return e;try{if(nk(e,A))return X&&N.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return A=e}}};function nk(A,e){return e?!!(ik(A,e)||rk(A,e)):!1}function ik(A,e){const t=A.message,n=e.message;return!(!t&&!n||t&&!n||!t&&n||t!==n||!im(A,e)||!nm(A,e))}function rk(A,e){const t=rm(e),n=rm(A);return!(!t||!n||t.type!==n.type||t.value!==n.value||!im(A,e)||!nm(A,e))}function nm(A,e){let t=Sp(A),n=Sp(e);if(!t&&!n)return!0;if(t&&!n||!t&&n||(t=t,n=n,n.length!==t.length))return!1;for(let i=0;i<n.length;i++){const r=n[i],s=t[i];if(r.filename!==s.filename||r.lineno!==s.lineno||r.colno!==s.colno||r.function!==s.function)return!1}return!0}function im(A,e){let t=A.fingerprint,n=e.fingerprint;if(!t&&!n)return!0;if(t&&!n||!t&&n)return!1;t=t,n=n;try{return t.join("")===n.join("")}catch{return!1}}function rm(A){return A.exception?.values&&A.exception.values[0]}function lu(A){if(!A)return{};const e=A.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const t=e[6]||"",n=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:t,hash:n,relative:e[5]+t+n}}function sm(A){if(A!==void 0)return A>=400&&A<500?"warning":A>=500?"error":void 0}const Hi=Ae;function sk(){return"history"in Hi&&!!Hi.history}function ok(){if(!("fetch"in Hi))return!1;try{return new Headers,new Request("http://www.example.com"),new Response,!0}catch{return!1}}function du(A){return A&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(A.toString())}function ak(){if(typeof EdgeRuntime=="string")return!0;if(!ok())return!1;if(du(Hi.fetch))return!0;let A=!1;const e=Hi.document;if(e&&typeof e.createElement=="function")try{const t=e.createElement("iframe");t.hidden=!0,e.head.appendChild(t),t.contentWindow?.fetch&&(A=du(t.contentWindow.fetch)),e.head.removeChild(t)}catch(t){X&&N.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",t)}return A}function ck(A,e){const t="fetch";An(t,A),nn(t,()=>uk(void 0,e))}function uk(A,e=!1){e&&!ak()||it(Ae,"fetch",function(t){return function(...n){const i=new Error,{method:r,url:s}=lk(n),o={args:n,fetchData:{method:r,url:s},startTimestamp:zt()*1e3,virtualError:i,headers:dk(n)};return A||Qt("fetch",{...o}),t.apply(Ae,n).then(async a=>(A?A(a):Qt("fetch",{...o,endTimestamp:zt()*1e3,response:a}),a),a=>{if(Qt("fetch",{...o,endTimestamp:zt()*1e3,error:a}),Vc(a)&&a.stack===void 0&&(a.stack=i.stack,ZA(a,"framesToPop",1)),a instanceof TypeError&&(a.message==="Failed to fetch"||a.message==="Load failed"||a.message==="NetworkError when attempting to fetch resource."))try{const c=new URL(o.fetchData.url);a.message=`${a.message} (${c.host})`}catch{}throw a})}})}function hu(A,e){return!!A&&typeof A=="object"&&!!A[e]}function om(A){return typeof A=="string"?A:A?hu(A,"url")?A.url:A.toString?A.toString():"":""}function lk(A){if(A.length===0)return{method:"GET",url:""};if(A.length===2){const[t,n]=A;return{url:om(t),method:hu(n,"method")?String(n.method).toUpperCase():"GET"}}const e=A[0];return{url:om(e),method:hu(e,"method")?String(e.method).toUpperCase():"GET"}}function dk(A){const[e,t]=A;try{if(typeof t=="object"&&t!==null&&"headers"in t&&t.headers)return new Headers(t.headers);if(ST(e))return new Headers(e.headers)}catch{}}function hk(){return"npm"}const xe=Ae;let fu=0;function am(){return fu>0}function fk(){fu++,setTimeout(()=>{fu--})}function Gn(A,e={}){function t(i){return typeof i=="function"}if(!t(A))return A;try{const i=A.__sentry_wrapped__;if(i)return typeof i=="function"?i:A;if(Xc(A))return A}catch{return A}const n=function(...i){try{const r=i.map(s=>Gn(s,e));return A.apply(this,r)}catch(r){throw fk(),lp(s=>{s.addEventProcessor(o=>(e.mechanism&&(qc(o,void 0,void 0),Hn(o,e.mechanism)),o.extra={...o.extra,arguments:i},o)),uF(r)}),r}};try{for(const i in A)Object.prototype.hasOwnProperty.call(A,i)&&(n[i]=A[i])}catch{}Zg(n,A),ZA(A,"__sentry_wrapped__",n);try{Object.getOwnPropertyDescriptor(n,"name").configurable&&Object.defineProperty(n,"name",{get(){return A.name}})}catch{}return n}function gk(){const A=Yg(),{referrer:e}=xe.document||{},{userAgent:t}=xe.navigator||{},n={...e&&{Referer:e},...t&&{"User-Agent":t}};return{url:A,headers:n}}function gu(A,e){const t=mu(A,e),n={type:Ck(e),value:wk(e)};return t.length&&(n.stacktrace={frames:t}),n.type===void 0&&n.value===""&&(n.value="Unrecoverable error caught"),n}function pk(A,e,t,n){const r=Ne()?.getOptions().normalizeDepth,s=Uk(e),o={__serialized__:Fp(e,r)};if(s)return{exception:{values:[gu(A,s)]},extra:o};const a={exception:{values:[{type:Gs(e)?e.constructor.name:n?"UnhandledRejection":"Error",value:Ek(e,{isUnhandledRejection:n})}]},extra:o};if(t){const c=mu(A,t);c.length&&(a.exception.values[0].stacktrace={frames:c})}return a}function pu(A,e){return{exception:{values:[gu(A,e)]}}}function mu(A,e){const t=e.stacktrace||e.stack||"",n=Bk(e),i=vk(e);try{return A(t,n,i)}catch{}return[]}const mk=/Minified React error #\d+;/i;function Bk(A){return A&&mk.test(A.message)?1:0}function vk(A){return typeof A.framesToPop=="number"?A.framesToPop:0}function cm(A){return typeof WebAssembly<"u"&&typeof WebAssembly.Exception<"u"?A instanceof WebAssembly.Exception:!1}function Ck(A){const e=A?.name;return!e&&cm(A)?A.message&&Array.isArray(A.message)&&A.message.length==2?A.message[0]:"WebAssembly.Exception":e}function wk(A){const e=A?.message;return cm(A)?Array.isArray(A.message)&&A.message.length==2?A.message[1]:"wasm exception":e?e.error&&typeof e.error.message=="string"?e.error.message:e:"No error message"}function yk(A,e,t,n){const i=t?.syntheticException||void 0,r=Bu(A,e,i,n);return Hn(r),r.level="error",t?.event_id&&(r.event_id=t.event_id),rn(r)}function bk(A,e,t="info",n,i){const r=n?.syntheticException||void 0,s=vu(A,e,r,i);return s.level=t,n?.event_id&&(s.event_id=n.event_id),rn(s)}function Bu(A,e,t,n,i){let r;if(Wg(e)&&e.error)return pu(A,e.error);if(Jg(e)||wT(e)){const s=e;if("stack"in e)r=pu(A,e);else{const o=s.name||(Jg(s)?"DOMError":"DOMException"),a=s.message?`${o}: ${s.message}`:o;r=vu(A,a,t,n),qc(r,a)}return"code"in s&&(r.tags={...r.tags,"DOMException.code":`${s.code}`}),r}return Vc(e)?pu(A,e):Ri(e)||Gs(e)?(r=pk(A,e,t,i),Hn(r,{synthetic:!0}),r):(r=vu(A,e,t,n),qc(r,`${e}`,void 0),Hn(r,{synthetic:!0}),r)}function vu(A,e,t,n){const i={};if(n&&t){const r=mu(A,t);r.length&&(i.exception={values:[{value:e,stacktrace:{frames:r}}]}),Hn(i,{synthetic:!0})}if(jc(e)){const{__sentry_template_string__:r,__sentry_template_values__:s}=e;return i.logentry={message:r,params:s},i}return i.message=e,i}function Ek(A,{isUnhandledRejection:e}){const t=_T(A),n=e?"promise rejection":"exception";return Wg(A)?`Event \`ErrorEvent\` captured as ${n} with message \`${A.message}\``:Gs(A)?`Event \`${Sk(A)}\` (type=${A.type}) captured as ${n}`:`Object captured as ${n} with keys: ${t}`}function Sk(A){try{const e=Object.getPrototypeOf(A);return e?e.constructor.name:void 0}catch{}}function Uk(A){for(const e in A)if(Object.prototype.hasOwnProperty.call(A,e)){const t=A[e];if(t instanceof Error)return t}}const Tk=5e3;class Qk extends CF{constructor(e){const t=Fk(e),n=xe.SENTRY_SDK_SOURCE||hk();DF(t,"browser",["browser"],n),super(t);const{sendDefaultPii:i,sendClientReports:r,_experiments:s}=this._options,o=s?.enableLogs;xe.document&&(r||o)&&xe.document.addEventListener("visibilitychange",()=>{xe.document.visibilityState==="hidden"&&(r&&this._flushOutcomes(),o&&cu(this))}),o&&(this.on("flush",()=>{cu(this)}),this.on("afterCaptureLog",()=>{this._logFlushIdleTimeout&&clearTimeout(this._logFlushIdleTimeout),this._logFlushIdleTimeout=setTimeout(()=>{cu(this)},Tk)})),i&&(this.on("postprocessEvent",RF),this.on("beforeSendSession",PF))}eventFromException(e,t){return yk(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t="info",n){return bk(this._options.stackParser,e,t,n,this._options.attachStacktrace)}_prepareEvent(e,t,n,i){return e.platform=e.platform||"javascript",super._prepareEvent(e,t,n,i)}}function Fk(A){return{release:typeof __SENTRY_RELEASE__=="string"?__SENTRY_RELEASE__:xe.SENTRY_RELEASE?.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...A}}const kk=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Ke=Ae,Ik=1e3;let um,Cu,wu;function _k(A){const e="dom";An(e,A),nn(e,xk)}function xk(){if(!Ke.document)return;const A=Qt.bind(null,"dom"),e=lm(A,!0);Ke.document.addEventListener("click",e,!1),Ke.document.addEventListener("keypress",e,!1),["EventTarget","Node"].forEach(t=>{const i=Ke[t]?.prototype;i?.hasOwnProperty?.("addEventListener")&&(it(i,"addEventListener",function(r){return function(s,o,a){if(s==="click"||s=="keypress")try{const c=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},u=c[s]=c[s]||{refCount:0};if(!u.handler){const l=lm(A);u.handler=l,r.call(this,s,l,a)}u.refCount++}catch{}return r.call(this,s,o,a)}}),it(i,"removeEventListener",function(r){return function(s,o,a){if(s==="click"||s=="keypress")try{const c=this.__sentry_instrumentation_handlers__||{},u=c[s];u&&(u.refCount--,u.refCount<=0&&(r.call(this,s,u.handler,a),u.handler=void 0,delete c[s]),Object.keys(c).length===0&&delete this.__sentry_instrumentation_handlers__)}catch{}return r.call(this,s,o,a)}}))})}function Rk(A){if(A.type!==Cu)return!1;try{if(!A.target||A.target._sentryId!==wu)return!1}catch{}return!0}function Pk(A,e){return A!=="keypress"?!1:e?.tagName?!(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable):!0}function lm(A,e=!1){return t=>{if(!t||t._sentryCaptured)return;const n=Dk(t);if(Pk(t.type,n))return;ZA(t,"_sentryCaptured",!0),n&&!n._sentryId&&ZA(n,"_sentryId",dt());const i=t.type==="keypress"?"input":t.type;Rk(t)||(A({event:t,name:i,global:e}),Cu=t.type,wu=n?n._sentryId:void 0),clearTimeout(um),um=Ke.setTimeout(()=>{wu=void 0,Cu=void 0},Ik)}}function Dk(A){try{return A.target}catch{return null}}let io;function dm(A){const e="history";An(e,A),nn(e,Lk)}function Lk(){if(Ke.addEventListener("popstate",()=>{const e=Ke.location.href,t=io;if(io=e,t===e)return;Qt("history",{from:t,to:e})}),!sk())return;function A(e){return function(...t){const n=t.length>2?t[2]:void 0;if(n){const i=io,r=Ok(String(n));if(io=r,i===r)return e.apply(this,t);Qt("history",{from:i,to:r})}return e.apply(this,t)}}it(Ke.history,"pushState",A),it(Ke.history,"replaceState",A)}function Ok(A){try{return new URL(A,Ke.location.origin).toString()}catch{return A}}const ro={};function Hk(A){const e=ro[A];if(e)return e;let t=Ke[A];if(du(t))return ro[A]=t.bind(Ke);const n=Ke.document;if(n&&typeof n.createElement=="function")try{const i=n.createElement("iframe");i.hidden=!0,n.head.appendChild(i);const r=i.contentWindow;r?.[A]&&(t=r[A]),n.head.removeChild(i)}catch(i){kk&&N.warn(`Could not create sandbox iframe for ${A} check, bailing to window.${A}: `,i)}return t&&(ro[A]=t.bind(Ke))}function hm(A){ro[A]=void 0}const Mi="__sentry_xhr_v3__";function Mk(A){const e="xhr";An(e,A),nn(e,Nk)}function Nk(){if(!Ke.XMLHttpRequest)return;const A=XMLHttpRequest.prototype;A.open=new Proxy(A.open,{apply(e,t,n){const i=new Error,r=zt()*1e3,s=Yt(n[0])?n[0].toUpperCase():void 0,o=Kk(n[1]);if(!s||!o)return e.apply(t,n);t[Mi]={method:s,url:o,request_headers:{}},s==="POST"&&o.match(/sentry_key/)&&(t.__sentry_own_request__=!0);const a=()=>{const c=t[Mi];if(c&&t.readyState===4){try{c.status_code=t.status}catch{}const u={endTimestamp:zt()*1e3,startTimestamp:r,xhr:t,virtualError:i};Qt("xhr",u)}};return"onreadystatechange"in t&&typeof t.onreadystatechange=="function"?t.onreadystatechange=new Proxy(t.onreadystatechange,{apply(c,u,l){return a(),c.apply(u,l)}}):t.addEventListener("readystatechange",a),t.setRequestHeader=new Proxy(t.setRequestHeader,{apply(c,u,l){const[d,h]=l,f=u[Mi];return f&&Yt(d)&&Yt(h)&&(f.request_headers[d.toLowerCase()]=h),c.apply(u,l)}}),e.apply(t,n)}}),A.send=new Proxy(A.send,{apply(e,t,n){const i=t[Mi];if(!i)return e.apply(t,n);n[0]!==void 0&&(i.body=n[0]);const r={startTimestamp:zt()*1e3,xhr:t};return Qt("xhr",r),e.apply(t,n)}})}function Kk(A){if(Yt(A))return A;try{return A.toString()}catch{}}function Gk(A,e=Hk("fetch")){let t=0,n=0;function i(r){const s=r.body.length;t+=s,n++;const o={body:r.body,method:"POST",referrerPolicy:"strict-origin",headers:A.headers,keepalive:t<=6e4&&n<15,...A.fetchOptions};if(!e)return hm("fetch"),zs("No fetch implementation available");try{return e(A.url,o).then(a=>(t-=s,n--,{statusCode:a.status,headers:{"x-sentry-rate-limits":a.headers.get("X-Sentry-Rate-Limits"),"retry-after":a.headers.get("Retry-After")}}))}catch(a){return hm("fetch"),t-=s,n--,zs(a)}}return xF(A,i)}const Vk=30,jk=50;function yu(A,e,t,n){const i={filename:A,function:e==="<anonymous>"?tn:e,in_app:!0};return t!==void 0&&(i.lineno=t),n!==void 0&&(i.colno=n),i}const $k=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Wk=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Jk=/\((\S*)(?::(\d+))(?::(\d+))\)/,Xk=[Vk,A=>{const e=$k.exec(A);if(e){const[,n,i,r]=e;return yu(n,tn,+i,+r)}const t=Wk.exec(A);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=Jk.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=fm(t[1]||tn,t[2]);return yu(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}}],qk=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Yk=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,zk=gQ(...[Xk,[jk,A=>{const e=qk.exec(A);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=Yk.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let n=e[3],i=e[1]||tn;return[i,n]=fm(i,n),yu(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]),fm=(A,e)=>{const t=A.indexOf("safari-extension")!==-1,n=A.indexOf("safari-web-extension")!==-1;return t||n?[A.indexOf("@")!==-1?A.split("@")[0]:tn,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[A,e]},bu=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,so=1024,Zk="Breadcrumbs",eI=(A={})=>{const e={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...A};return{name:Zk,setup(t){e.console&&zF(nI(t)),e.dom&&_k(AI(t,e.dom)),e.xhr&&Mk(iI(t)),e.fetch&&ck(rI(t)),e.history&&dm(sI(t)),e.sentry&&t.on("beforeSendEvent",tI(t))}}};function tI(A){return function(t){Ne()===A&&sn({category:`sentry.${t.type==="transaction"?"transaction":"event"}`,event_id:t.event_id,level:t.level,message:en(t)},{event:t})}}function AI(A,e){return function(n){if(Ne()!==A)return;let i,r,s=typeof e=="object"?e.serializeAttribute:void 0,o=typeof e=="object"&&typeof e.maxStringLength=="number"?e.maxStringLength:void 0;o&&o>so&&(bu&&N.warn(`\`dom.maxStringLength\` cannot exceed ${so}, but a value of ${o} was configured. Sentry will use ${so} instead.`),o=so),typeof s=="string"&&(s=[s]);try{const c=n.event,u=oI(c)?c.target:c;i=qg(u,{keyAttrs:s,maxStringLength:o}),r=QT(u)}catch{i="<unknown>"}if(i.length===0)return;const a={category:`ui.${n.name}`,message:i};r&&(a.data={"ui.component_name":r}),sn(a,{event:n.event,name:n.name,global:n.global})}}function nI(A){return function(t){if(Ne()!==A)return;const n={category:"console",data:{arguments:t.args,logger:"console"},level:ek(t.level),message:zg(t.args," ")};if(t.level==="assert")if(t.args[0]===!1)n.message=`Assertion failed: ${zg(t.args.slice(1)," ")||"console.assert"}`,n.data.arguments=t.args.slice(1);else return;sn(n,{input:t.args,level:t.level})}}function iI(A){return function(t){if(Ne()!==A)return;const{startTimestamp:n,endTimestamp:i}=t,r=t.xhr[Mi];if(!n||!i||!r)return;const{method:s,url:o,status_code:a,body:c}=r,u={method:s,url:o,status_code:a},l={xhr:t.xhr,input:c,startTimestamp:n,endTimestamp:i},d={category:"xhr",data:u,type:"http",level:sm(a)};A.emit("beforeOutgoingRequestBreadcrumb",d,l),sn(d,l)}}function rI(A){return function(t){if(Ne()!==A)return;const{startTimestamp:n,endTimestamp:i}=t;if(i&&!(t.fetchData.url.match(/sentry_key/)&&t.fetchData.method==="POST"))if(t.fetchData.method,t.fetchData.url,t.error){const r=t.fetchData,s={data:t.error,input:t.args,startTimestamp:n,endTimestamp:i},o={category:"fetch",data:r,level:"error",type:"http"};A.emit("beforeOutgoingRequestBreadcrumb",o,s),sn(o,s)}else{const r=t.response,s={...t.fetchData,status_code:r?.status};t.fetchData.request_body_size,t.fetchData.response_body_size,r?.status;const o={input:t.args,response:r,startTimestamp:n,endTimestamp:i},a={category:"fetch",data:s,type:"http",level:sm(s.status_code)};A.emit("beforeOutgoingRequestBreadcrumb",a,o),sn(a,o)}}}function sI(A){return function(t){if(Ne()!==A)return;let n=t.from,i=t.to;const r=lu(xe.location.href);let s=n?lu(n):void 0;const o=lu(i);s?.path||(s=r),r.protocol===o.protocol&&r.host===o.host&&(i=o.relative),r.protocol===s.protocol&&r.host===s.host&&(n=s.relative),sn({category:"navigation",data:{from:n,to:i}})}}function oI(A){return!!A&&!!A.target}const aI=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],cI="BrowserApiErrors",uI=(A={})=>{const e={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...A};return{name:cI,setupOnce(){e.setTimeout&&it(xe,"setTimeout",gm),e.setInterval&&it(xe,"setInterval",gm),e.requestAnimationFrame&&it(xe,"requestAnimationFrame",lI),e.XMLHttpRequest&&"XMLHttpRequest"in xe&&it(XMLHttpRequest.prototype,"send",dI);const t=e.eventTarget;t&&(Array.isArray(t)?t:aI).forEach(hI)}}};function gm(A){return function(...e){const t=e[0];return e[0]=Gn(t,{mechanism:{data:{function:_A(A)},handled:!1,type:"instrument"}}),A.apply(this,e)}}function lI(A){return function(e){return A.apply(this,[Gn(e,{mechanism:{data:{function:"requestAnimationFrame",handler:_A(A)},handled:!1,type:"instrument"}})])}}function dI(A){return function(...e){const t=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(i=>{i in t&&typeof t[i]=="function"&&it(t,i,function(r){const s={mechanism:{data:{function:i,handler:_A(r)},handled:!1,type:"instrument"}},o=Xc(r);return o&&(s.mechanism.data.handler=_A(o)),Gn(r,s)})}),A.apply(this,e)}}function hI(A){const t=xe[A]?.prototype;t?.hasOwnProperty?.("addEventListener")&&(it(t,"addEventListener",function(n){return function(i,r,s){try{fI(r)&&(r.handleEvent=Gn(r.handleEvent,{mechanism:{data:{function:"handleEvent",handler:_A(r),target:A},handled:!1,type:"instrument"}}))}catch{}return n.apply(this,[i,Gn(r,{mechanism:{data:{function:"addEventListener",handler:_A(r),target:A},handled:!1,type:"instrument"}}),s])}}),it(t,"removeEventListener",function(n){return function(i,r,s){try{const o=r.__sentry_wrapped__;o&&n.call(this,i,o,s)}catch{}return n.call(this,i,r,s)}}))}function fI(A){return typeof A.handleEvent=="function"}const gI=()=>({name:"BrowserSession",setupOnce(){if(typeof xe.document>"u"){bu&&N.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");return}Dp({ignoreDuration:!0}),Hp(),dm(({from:A,to:e})=>{A!==void 0&&A!==e&&(Dp({ignoreDuration:!0}),Hp())})}}),pI="GlobalHandlers",mI=(A={})=>{const e={onerror:!0,onunhandledrejection:!0,...A};return{name:pI,setupOnce(){Error.stackTraceLimit=50},setup(t){e.onerror&&(BI(t),pm("onerror")),e.onunhandledrejection&&(vI(t),pm("onunhandledrejection"))}}};function BI(A){mQ(e=>{const{stackParser:t,attachStacktrace:n}=mm();if(Ne()!==A||am())return;const{msg:i,url:r,line:s,column:o,error:a}=e,c=yI(Bu(t,a||i,void 0,n,!1),r,s,o);c.level="error",Pp(c,{originalException:a,mechanism:{handled:!1,type:"onerror"}})})}function vI(A){vQ(e=>{const{stackParser:t,attachStacktrace:n}=mm();if(Ne()!==A||am())return;const i=CI(e),r=$c(i)?wI(i):Bu(t,i,void 0,n,!0);r.level="error",Pp(r,{originalException:i,mechanism:{handled:!1,type:"onunhandledrejection"}})})}function CI(A){if($c(A))return A;try{if("reason"in A)return A.reason;if("detail"in A&&"reason"in A.detail)return A.detail.reason}catch{}return A}function wI(A){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(A)}`}]}}}function yI(A,e,t,n){const i=A.exception=A.exception||{},r=i.values=i.values||[],s=r[0]=r[0]||{},o=s.stacktrace=s.stacktrace||{},a=o.frames=o.frames||[],c=n,u=t,l=Yt(e)&&e.length>0?e:Yg();return a.length===0&&a.push({colno:c,filename:l,function:tn,in_app:!0,lineno:u}),A}function pm(A){bu&&N.log(`Global Handler attached: ${A}`)}function mm(){return Ne()?.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}const bI=()=>({name:"HttpContext",preprocessEvent(A){if(!xe.navigator&&!xe.location&&!xe.document)return;const e=gk(),t={...e.headers,...A.request?.headers};A.request={...e,...A.request,headers:t}}}),EI="cause",SI=5,UI="LinkedErrors",TI=(A={})=>{const e=A.limit||SI,t=A.key||EI;return{name:UI,preprocessEvent(n,i,r){const s=r.getOptions();YF(gu,s.stackParser,t,e,n,i)}}};function QI(A){return[GF(),HF(),uI(),eI(),mI(),TI(),Ak(),bI(),gI()]}function FI(){const A=QI().filter(n=>!["BrowserApiErrors","Breadcrumbs","GlobalHandlers","HttpContext"].includes(n.name)),e=new Qk({dsn:"https://ac54bd10eac67be2dafbc346e704e4d4@o4507251798835200.ingest.us.sentry.io/4509409566392320",environment:"production",transport:Gk,stackParser:zk,integrations:A,beforeSend(n,i){const r=i.originalException;return r instanceof Error&&(r.message.includes("Failed to fetch")||r.message.includes("Network request failed")||r.message.includes("Load failed")||r.message.includes("Permission denied")||r.message.includes("NotAllowedError"))?null:n},release:process.env.npm_package_version||"0.6.2"}),t=new Tt;return t.setClient(e),e.init(),t}let oo=null,rt={};function kI(){oo||(oo=FI())}function ht(A,e){{if(kI(),!oo)return;lp(t=>{Object.entries(rt).forEach(([n,i])=>{i!==void 0&&t.setTag(n,String(i))}),e&&(Object.entries(e).forEach(([n,i])=>{i!==void 0&&t.setTag(n,String(i))}),(e.userId||e.userEmail)&&t.setUser({id:e.userId,email:e.userEmail,...e.userMetadata}),(e.eventType||e.eventData||e.userJourney)&&t.setContext("eventContext",{eventType:e.eventType,eventData:e.eventData,userJourney:e.userJourney,timestamp:new Date().toISOString()})),oo.captureException(A)})}}function se(A,e,t){rt.eventType=A,rt.eventData=e,rt.userJourney||(rt.userJourney=[]);const n=`${new Date().toISOString()}: ${A}${t?` (${t})`:""}`;rt.userJourney.push(n),rt.userJourney.length>10&&(rt.userJourney=rt.userJourney.slice(-10))}function Ni(A){rt={...rt,...A}}function Ki(A,e,t){return async(...n)=>{try{se(`${e}_started`,{componentName:t},t);const i=await A(...n);return se(`${e}_completed`,{componentName:t},t),i}catch(i){throw ht(i,{...rt,componentName:t,handlerName:e,eventType:`${e}_failed`,eventData:{error:i instanceof Error?i.message:String(i)}}),i}}}function II(A,e,t){return(...n)=>{try{se(`${e}_started`,{componentName:t},t);const i=A(...n);return se(`${e}_completed`,{componentName:t},t),i}catch(i){throw ht(i,{...rt,componentName:t,handlerName:e,eventType:`${e}_failed`,eventData:{error:i instanceof Error?i.message:String(i)}}),i}}}function Bm(A){return{trackLifecycle:(e,t)=>{try{se(`${A}_${e}`,{},A),t()}catch(n){throw ht(n,{componentName:A,lifecycle:e,eventType:`${A}_${e}_failed`}),n}},trackRender:e=>{try{return e()}catch(t){return ht(t,{componentName:A,lifecycle:"render",eventType:`${A}_render_failed`}),L.html`<div>Error rendering ${A}</div>`}},setContext:()=>{Ni({componentName:A}),se(`${A}_initialized`,{},A)}}}class _I{constructor(e){this.namespace=e}getItem(e){return localStorage.getItem(`${this.namespace}.${e}`)}setItem(e,t){localStorage.setItem(`${this.namespace}.${e}`,t)}removeItem(e){localStorage.removeItem(`${this.namespace}.${e}`)}clear(){for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);t&&t.startsWith(`${this.namespace}.`)&&localStorage.removeItem(t)}}}const Eu={SESSION_DATA:"session_data"},Su=new _I("io.obi.widget");var xI=Object.defineProperty,RI=Object.getOwnPropertyDescriptor,ao=(A,e,t,n)=>{for(var i=n>1?void 0:n?RI(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&xI(e,t,i),i};class Vn extends L.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("obi-nav-icon-click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return L.html`
|
|
125
125
|
<button
|
|
126
126
|
id="obi-nav-${this.id}"
|
|
127
127
|
class=${this.isSpecial?"special":""}
|
|
@@ -267,7 +267,7 @@ Url: ${no(A)}`),!0}return!1}function $F(A,e){return e?.length?Gp(A).some(t=>Js(t
|
|
|
267
267
|
bottom: auto;
|
|
268
268
|
flex-direction: column;
|
|
269
269
|
}
|
|
270
|
-
`,jn([ee({type:Boolean})],RA.prototype,"isActive",2),jn([ee({type:Boolean})],RA.prototype,"isScreenActive",2),jn([ee({type:Object})],RA.prototype,"position",2),jn([ee({type:String})],RA.prototype,"currentState",2),jn([ee({type:String})],RA.prototype,"direction",2),jn([ee({type:Function})],RA.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",RA);var KI=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,tA=(A,e,t,n)=>{for(var i=n>1?void 0:n?GI(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&KI(e,t,i),i};class on extends L.LitElement{constructor(){super(),this.id="",this.name="",this.description="",this.duration=10,this.selected=!1,this.handleClick=
|
|
270
|
+
`,jn([ee({type:Boolean})],RA.prototype,"isActive",2),jn([ee({type:Boolean})],RA.prototype,"isScreenActive",2),jn([ee({type:Object})],RA.prototype,"position",2),jn([ee({type:String})],RA.prototype,"currentState",2),jn([ee({type:String})],RA.prototype,"direction",2),jn([ee({type:Function})],RA.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",RA);var KI=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,tA=(A,e,t,n)=>{for(var i=n>1?void 0:n?GI(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&KI(e,t,i),i};class on extends L.LitElement{constructor(){super(),this.id="",this.name="",this.description="",this.duration=10,this.selected=!1,this.handleClick=II(()=>{se("course_clicked",{courseId:this.id,courseName:this.name},"Course"),this.dispatchEvent(new CustomEvent("course-card-click",{detail:{id:this.id,name:this.name,description:this.description,duration:this.duration},bubbles:!0,composed:!0}))},"handleClick","Course");try{Bm("Course").setContext()}catch(e){ht(e,{componentName:"Course",lifecycle:"constructor"})}}render(){return L.html`
|
|
271
271
|
<div class="course-container ${this.selected?"selected":""}" @click=${this.handleClick}>
|
|
272
272
|
<div class="header-row">
|
|
273
273
|
<h2 class="course-title">${this.name}</h2>
|
|
@@ -698,7 +698,7 @@ Url: ${no(A)}`),!0}return!1}function $F(A,e){return e?.length?Gp(A).some(t=>Js(t
|
|
|
698
698
|
* @license
|
|
699
699
|
* Copyright 2020 Google LLC
|
|
700
700
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
701
|
-
*/const c_=()=>new u_;class u_{}const Qu=new WeakMap,l_=n_(class extends a_{render(A){return we}update(A,[e]){const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=A.options?.host,this.rt(this.ct=A.element)),we}rt(A){if(this.isConnected||(A=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Qu.get(e);t===void 0&&(t=new WeakMap,Qu.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,A),A!==void 0&&this.G.call(this.ht,A)}else this.G.value=A}get lt(){return typeof this.G=="function"?Qu.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var d_=Object.defineProperty,h_=Object.getOwnPropertyDescriptor,km=(A,e,t,n)=>{for(var i=n>1?void 0:n?h_(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&d_(e,t,i),i};let qi=class extends L.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=c_(),this.barCount=8,this.animationFrame=null,this.primaryColor=Hr}connectedCallback(){super.connectedCallback(),this.primaryColor=getComputedStyle(this).getPropertyValue("--obi-primary").trim()||Hr,this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const n=window.devicePixelRatio||1,i=e.clientWidth,r=e.clientHeight;e.width=Math.round(i*n),e.height=Math.round(r*n),t.scale(n,n),t.imageSmoothingEnabled=!1,t.clearRect(0,0,i,r);const s=3,o=Math.max(1,(i-(this.barCount-1)*s)/this.barCount),a=r/2,c=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,u=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(c===0)return;let l=[];if(u&&u.length>0){const d=u.length,h=Math.ceil(d/10);let f=[];for(let v=0;v<10;v++){const C=v*h,w=Math.min((v+1)*h,d);let S=0;for(let F=C;F<w;F++)S+=u[F]||0;f.push({region:v,startIdx:C,endIdx:w,energy:S})}f.sort((v,C)=>C.energy-v.energy);const g=f.slice(0,3),p=Math.min(...g.map(v=>v.startIdx)),B=Math.max(...g.map(v=>v.endIdx));if(B>p)for(let v=0;v<this.barCount;v++){const C=p+v/(this.barCount-1)*(B-p),w=Math.min(d-1,Math.floor(C));l[v]=u[w]||0}else for(let v=0;v<this.barCount;v++){const C=v/(this.barCount-1)*(d/2),w=Math.min(d-1,Math.floor(C));l[v]=u[w]||0}const y=Math.max(...l,1),b=this.volume.speaker==="USER"?.7:.6;l=l.map((v,C)=>{const w=v/y,S=b+C/(this.barCount-1)*.3;return Math.min(1,w*S)})}else if(this.volume.speaker!=="USER")for(let d=0;d<this.barCount;d++){const h=Date.now()*.002,f=.3+.2*Math.sin(h+d*.7);l[d]=f}for(let d=0;d<this.barCount;d++){const h=l.length>0&&l[d]!==void 0?l[d]:c;
|
|
701
|
+
*/const c_=()=>new u_;class u_{}const Qu=new WeakMap,l_=n_(class extends a_{render(A){return we}update(A,[e]){const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=A.options?.host,this.rt(this.ct=A.element)),we}rt(A){if(this.isConnected||(A=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Qu.get(e);t===void 0&&(t=new WeakMap,Qu.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,A),A!==void 0&&this.G.call(this.ht,A)}else this.G.value=A}get lt(){return typeof this.G=="function"?Qu.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var d_=Object.defineProperty,h_=Object.getOwnPropertyDescriptor,km=(A,e,t,n)=>{for(var i=n>1?void 0:n?h_(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&d_(e,t,i),i};let qi=class extends L.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=c_(),this.barCount=8,this.animationFrame=null,this.primaryColor=Hr}connectedCallback(){super.connectedCallback(),this.primaryColor=getComputedStyle(this).getPropertyValue("--obi-primary").trim()||Hr,this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const n=window.devicePixelRatio||1,i=e.clientWidth,r=e.clientHeight;e.width=Math.round(i*n),e.height=Math.round(r*n),t.scale(n,n),t.imageSmoothingEnabled=!1,t.clearRect(0,0,i,r);const s=3,o=Math.max(1,(i-(this.barCount-1)*s)/this.barCount),a=r/2,c=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,u=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(c===0)return;let l=[];if(u&&u.length>0){const d=u.length,h=Math.ceil(d/10);let f=[];for(let v=0;v<10;v++){const C=v*h,w=Math.min((v+1)*h,d);let S=0;for(let F=C;F<w;F++)S+=u[F]||0;f.push({region:v,startIdx:C,endIdx:w,energy:S})}f.sort((v,C)=>C.energy-v.energy);const g=f.slice(0,3),p=Math.min(...g.map(v=>v.startIdx)),B=Math.max(...g.map(v=>v.endIdx));if(B>p)for(let v=0;v<this.barCount;v++){const C=p+v/(this.barCount-1)*(B-p),w=Math.min(d-1,Math.floor(C));l[v]=u[w]||0}else for(let v=0;v<this.barCount;v++){const C=v/(this.barCount-1)*(d/2),w=Math.min(d-1,Math.floor(C));l[v]=u[w]||0}const y=Math.max(...l,1),b=this.volume.speaker==="USER"?.7:.6;l=l.map((v,C)=>{const w=v/y,S=b+C/(this.barCount-1)*.3;return Math.min(1,w*S)})}else if(this.volume.speaker!=="USER")for(let d=0;d<this.barCount;d++){const h=Date.now()*.002,f=.3+.2*Math.sin(h+d*.7);l[d]=f}for(let d=0;d<this.barCount;d++){const h=l.length>0&&l[d]!==void 0?l[d]:c;this.volume.speaker==="USER"?t.fillStyle=`${this.primaryColor}`:t.fillStyle="#FFFFFF";const f=Math.max(2,h*.8*a),g=i-(this.barCount-d)*(o+s),p=o/2;t.beginPath(),t.moveTo(g+p,r/2-f),t.lineTo(g+o-p,r/2-f),t.quadraticCurveTo(g+o,r/2-f,g+o,r/2-f+p),t.lineTo(g+o,r/2),t.lineTo(g,r/2),t.lineTo(g,r/2-f+p),t.quadraticCurveTo(g,r/2-f,g+p,r/2-f),t.fill(),t.beginPath(),t.moveTo(g,r/2),t.lineTo(g+o,r/2),t.lineTo(g+o,r/2+f-p),t.quadraticCurveTo(g+o,r/2+f,g+o-p,r/2+f),t.lineTo(g+p,r/2+f),t.quadraticCurveTo(g,r/2+f,g,r/2+f-p),t.lineTo(g,r/2),t.fill()}}render(){return L.html` <canvas ${l_(this.canvasRef)} width="40" height="40"></canvas> `}};qi.styles=L.css`
|
|
702
702
|
:host {
|
|
703
703
|
display: block;
|
|
704
704
|
width: 40px;
|
|
@@ -932,7 +932,7 @@ Url: ${no(A)}`),!0}return!1}function $F(A,e){return e?.length?Gp(A).some(t=>Js(t
|
|
|
932
932
|
align-items: center;
|
|
933
933
|
justify-content: center;
|
|
934
934
|
}
|
|
935
|
-
`,ku([ee({type:Object})],Yi.prototype,"session",2),ku([ee({type:Function})],Yi.prototype,"onStart",2),ku([ee({type:Function})],Yi.prototype,"onClose",2),customElements.get("obi-session-start-modal")||customElements.define("obi-session-start-modal",Yi);var v_=Object.defineProperty,C_=Object.getOwnPropertyDescriptor,Ze=(A,e,t,n)=>{for(var i=n>1?void 0:n?C_(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&v_(e,t,i),i};let Re=class extends L.LitElement{constructor(){super(),this.apiKey="",this.isActive=!0,this.linkOnlyAccess=!1,this.position="bottom-right",this.user=null,this.state=H.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.showSessionStartModal=!1,this.selectedCourse=null,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.obiClient=null,this.closeNavTimeoutRef=null,this.researchingTimeoutRef=null,this.connectObi=Ki(async e=>{if(this.activeSession){se("connection_already_exists",{sessionToken:e},"ObiWidget"),console.log("Connection already exists");return}se("session_connection_started",{sessionToken:e},"ObiWidget"),Ni({sessionId:e});try{const t=this.createSession(e);if(!t){this.handleSessionCreationFailure(()=>this.removeSessionUrlParams());return}this.setupSessionEventListeners(t,()=>this.removeSessionUrlParams()),t.on("screenCaptureRequested",Ki(async()=>{se("screen_capture_requested",{},"ObiWidget");try{const r=(await BT(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",r),se("screen_capture_completed",{},"ObiWidget")}catch(i){ht(i,{componentName:"ObiWidget",handlerName:"screenCaptureRequested",sessionToken:e}),console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error"),se("screen_capture_failed",{error:i instanceof Error?i.message:String(i)},"ObiWidget")}},"screenCaptureRequested","ObiWidget"));const n=await t.connect();n&&(this.sessionToken=e,this.roomToken=n.token,this.roomUrl=n.url,Ni({sessionId:e,widgetState:this.state.toString()}),this.removeSessionUrlParams(),se("session_connection_established",{sessionToken:e,hasRoomToken:!!n.token},"ObiWidget")),this.activeSession=t}catch(t){console.error("Failed to start session:",t),ht(t,{componentName:"ObiWidget",handlerName:"connectObi",sessionToken:e}),this.handleSessionCreationFailure(()=>this.removeSessionUrlParams())}},"connectObi","ObiWidget"),this.handleCourseSelectEvent=e=>{const t=e;this.selectedCourse=t.detail,this.showCourseModal=!1,this.showSessionStartModal=!0},this.handleUrlSessionEvent=Ki(async e=>{se("url_session_event",{sessionToken:e},"ObiWidget");try{if(!this.obiClient){const n=new Error("ObiClient not initialized");ht(n,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e}),console.error("ObiClient not initialized");return}const t=await this.obiClient.listSessions(this.apiKey);if(t.data){const n=t.data.sessions;console.log("[obi-sdk] sessions:",n),se("sessions_fetched",{sessionCount:n?.length||0,sessionToken:e},"ObiWidget");const i=n?.find(r=>r.uuid===e);if(i){const r=i;this.selectedCourse={id:e,name:r.onboarding_plan?.name||"",description:r.onboarding_plan?.description||""},this.state=H.LOADING,this.showSessionStartModal=!0,se("matching_session_found",{sessionToken:e,hasOnboardingPlan:!!r.onboarding_plan},"ObiWidget")}else console.log("[obi-sdk] no session found with token:",e),se("no_matching_session",{sessionToken:e},"ObiWidget")}}catch(t){console.error("Failed to fetch session details:",t),ht(t,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e})}},"handleUrlSessionEvent","ObiWidget"),this.handleSessionStart=Ki(async e=>{if(se("session_start_requested",{sessionToken:e},"ObiWidget"),this.activeSession){se("session_start_blocked",{sessionToken:e},"ObiWidget"),console.log("Connection already in progress or active session exists");return}this.showSessionStartModal=!1,this.state=H.LOADING,Ni({widgetState:this.state.toString()}),await this.connectObi(e)},"handleSessionStart","ObiWidget"),this.checkExistingSession=Ki(async()=>{se("checking_existing_session",{},"ObiWidget");try{const e=JSON.parse(jc.getItem(Vc.SESSION_DATA)||"{}"),{sessionToken:t,roomToken:n,roomUrl:i,sessionExpiry:r,obiState:s}=e;if(!t||!n||!i){se("no_existing_session_data",{},"ObiWidget");return}if(console.log("[obi-sdk] using existing session"),se("existing_session_data_found",{sessionToken:t,hasExpiry:!!r,obiState:s},"ObiWidget"),r&&new Date(r)<new Date){this.clearSessionStorage(),se("session_expired",{sessionToken:t},"ObiWidget");return}this.state=H.LOADING,Ni({sessionId:t,widgetState:this.state.toString()});const o=this.createSession(t);if(!o){this.handleSessionCreationFailure(()=>this.clearSessionStorage());return}this.setupSessionEventListeners(o,()=>this.clearSessionStorage()),await o.reconnect(i,n,s)?(this.activeSession=o,this.sessionToken=t,this.roomToken=n,this.roomUrl=i,this.state=s,this.storedActiveState=s,se("session_reconnected",{sessionToken:t,obiState:s},"ObiWidget")):(this.clearSessionStorage(),se("session_reconnection_failed",{sessionToken:t},"ObiWidget"))}catch(e){console.error("Error reconnecting to session:",e),ht(e,{componentName:"ObiWidget",handlerName:"checkExistingSession"}),this.handleSessionCreationFailure(()=>this.clearSessionStorage())}},"checkExistingSession","ObiWidget");try{Bm("ObiWidget").setContext(),this.obiClient=new Th({baseUrl:Ma});const t=()=>{try{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()}catch(n){ht(n,{componentName:"ObiWidget",handlerName:"handleUnload"})}};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",t),se("ObiWidget_constructor_completed",{},"ObiWidget")}catch(e){throw ht(e,{componentName:"ObiWidget",lifecycle:"constructor"}),e}}updateFromConfig(){if(window.obiWidgetConfig){this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,this.position=window.obiWidgetConfig.position||this.position,this.user=window.obiWidgetConfig.user||this.user,window.obiWidgetConfig.isActive!==void 0&&(this.isActive=window.obiWidgetConfig.isActive),window.obiWidgetConfig.linkOnlyAccess!==void 0&&(this.linkOnlyAccess=window.obiWidgetConfig.linkOnlyAccess);const e=window.obiWidgetConfig?.primaryColor||Hr;this.style.setProperty("--obi-primary",e),this.generateColorVariables(e)}}generateColorVariables(e){try{const t=Na(e,"#c4b5fd"),n=Na(e,"#c76cff"),i=ew(e),r=Na(e,"#A06DF9");this.style.setProperty("--obi-secondary",t),this.style.setProperty("--obi-course-selected",n),this.style.setProperty("--obi-course-selected-bg",i),this.style.setProperty("--obi-paused-pulse",r)}catch(t){console.warn("Failed to generate color variables:",t),this.style.setProperty("--obi-secondary","#c4b5fd"),this.style.setProperty("--obi-course-selected","#c76cff"),this.style.setProperty("--obi-course-selected-bg","#fbf3ff"),this.style.setProperty("--obi-paused-pulse","#A06DF9")}}removeSessionUrlParams(){const e=new URL(window.location.href);e.searchParams.delete(Rh),window.history.replaceState({},"",e.toString()),localStorage.removeItem("obi-url-params")}createSession(e){try{const t=new LC({sessionId:e,apiBaseUrl:Ma});return t||(console.error("Failed to create session"),null)}catch(t){return console.error("Error creating session:",t),null}}setupSessionEventListeners(e,t){e.on("stateChanged",n=>{if(n===H.RESEARCHING){this.researchingTimeoutRef&&window.clearTimeout(this.researchingTimeoutRef),this.state=n,this.researchingTimeoutRef=window.setTimeout(()=>{this.researchingTimeoutRef=null;const i=e.getCurrentState();this.state=i,i!==H.READY&&(this.storedActiveState=i)},1500),this.storedActiveState=n;return}this.researchingTimeoutRef===null&&(this.state=n,n!==H.READY&&(this.storedActiveState=n))}),e.on("volume",({speaker:n,spectrum:i,volume:r})=>{this.volume={speaker:n,spectrum:i,volume:r}}),e.on("error",n=>{console.error("Session error:",n),this.state=H.ERROR,this.activeSession=null,t&&t()})}handleSessionCreationFailure(e){this.state=H.ERROR,this.activeSession=null,e&&e()}clearSessionStorage(){jc.removeItem(Vc.SESSION_DATA)}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};jc.setItem(Vc.SESSION_DATA,JSON.stringify(t))}}async sessionConnectionCheck(){const e=function(){let t={};return t=JSON.parse(localStorage.getItem("obi-url-params")||"{}"),Object.keys(t).length===0&&new URLSearchParams(window.location.search).forEach((i,r)=>{t[r]=i}),localStorage.removeItem("obi-url-params"),t[Rh]}();if(!e){await this.checkExistingSession();return}console.log("[obi-sdk] using magic link"),this.apiKey?await this.handleUrlSessionEvent(e):(console.log("[obi-sdk] API key not ready, retrying..."),setTimeout(()=>{this.apiKey&&this.handleUrlSessionEvent(e)},100))}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.addEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.addEventListener("course-select",this.handleCourseSelectEvent),this.isActive&&this.sessionConnectionCheck()}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),this.removeSessionUrlParams()}handleConfigUpdate(e){const i=e.detail.isActive&&!this.isActive;this.updateFromConfig(),this.position&&this.setAttribute("position",this.position),i&&this.sessionConnectionCheck(),this.requestUpdate()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=H.READY}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}li([e,t]).with(["pause",!0],()=>{this.activeSession?.pauseRecording()}).with(["pause",!1],()=>{this.activeSession?.resumeRecording()}).with(["activate",!1],()=>{this.terminateSession()}).otherwise(()=>{})}render(){if(!this.isActive||this.linkOnlyAccess&&this.state===H.READY)return L.nothing;const e=li(this.state).with(H.LOADING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with(H.RESEARCHING,()=>L.html`<obi-searching-loader></obi-searching-loader>`).with(SC.union(H.USER_SPEAKING,H.AGENT_SPEAKING),()=>L.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with(H.THINKING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with(H.PAUSED,()=>co).otherwise(()=>co),t=this.state===H.USER_SPEAKING||this.state===H.AGENT_SPEAKING,n=this.state===H.PAUSED,i=this.state===H.RESEARCHING,r=this.state===H.USER_SPEAKING,s=this.state!==H.READY||this.navVisible,o=this.state!==H.READY||this.navVisible,a=this.position.includes("top")?"down":"up",c=["widget-container",s?"rotated":"",t?"pulse":"",n?"paused-pulse":"",i?"researching":"",r?"user-speaking":""].filter(Boolean).join(" ");return L.html`
|
|
935
|
+
`,ku([ee({type:Object})],Yi.prototype,"session",2),ku([ee({type:Function})],Yi.prototype,"onStart",2),ku([ee({type:Function})],Yi.prototype,"onClose",2),customElements.get("obi-session-start-modal")||customElements.define("obi-session-start-modal",Yi);var v_=Object.defineProperty,C_=Object.getOwnPropertyDescriptor,Ze=(A,e,t,n)=>{for(var i=n>1?void 0:n?C_(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&v_(e,t,i),i};let Re=class extends L.LitElement{constructor(){super(),this.apiKey="",this.isActive=!0,this.linkOnlyAccess=!1,this.position="bottom-right",this.user=null,this.state=H.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.showSessionStartModal=!1,this.selectedCourse=null,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.obiClient=null,this.closeNavTimeoutRef=null,this.researchingTimeoutRef=null,this.connectObi=Ki(async e=>{if(this.activeSession){se("connection_already_exists",{sessionToken:e},"ObiWidget"),console.log("Connection already exists");return}se("session_connection_started",{sessionToken:e},"ObiWidget"),Ni({sessionId:e});try{const t=this.createSession(e);if(!t){this.handleSessionCreationFailure(()=>this.removeSessionUrlParams());return}this.setupSessionEventListeners(t,()=>this.removeSessionUrlParams()),t.on("screenCaptureRequested",Ki(async()=>{se("screen_capture_requested",{},"ObiWidget");try{const r=(await BT(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",r),se("screen_capture_completed",{},"ObiWidget")}catch(i){ht(i,{componentName:"ObiWidget",handlerName:"screenCaptureRequested",sessionToken:e}),console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error"),se("screen_capture_failed",{error:i instanceof Error?i.message:String(i)},"ObiWidget")}},"screenCaptureRequested","ObiWidget"));const n=await t.connect();n&&(this.sessionToken=e,this.roomToken=n.token,this.roomUrl=n.url,Ni({sessionId:e,widgetState:this.state.toString()}),this.removeSessionUrlParams(),se("session_connection_established",{sessionToken:e,hasRoomToken:!!n.token},"ObiWidget")),this.activeSession=t}catch(t){console.error("Failed to start session:",t),ht(t,{componentName:"ObiWidget",handlerName:"connectObi",sessionToken:e}),this.handleSessionCreationFailure(()=>this.removeSessionUrlParams())}},"connectObi","ObiWidget"),this.handleCourseSelectEvent=e=>{const t=e;this.selectedCourse=t.detail,this.showCourseModal=!1,this.showSessionStartModal=!0},this.handleUrlSessionEvent=Ki(async e=>{se("url_session_event",{sessionToken:e},"ObiWidget");try{if(!this.obiClient){const n=new Error("ObiClient not initialized");ht(n,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e}),console.error("ObiClient not initialized");return}const t=await this.obiClient.startSession(e,this.apiKey);if(t.data){const{session:n}=t.data;if(console.log("[obi-sdk] session:",n),se("session_started",{sessionId:n?.id,sessionToken:e},"ObiWidget"),n){const i=n;this.selectedCourse={id:e,name:i.onboarding_plan?.name||"",description:i.onboarding_plan?.description||""},this.state=H.LOADING,this.showSessionStartModal=!0,se("matching_session_found",{sessionToken:e,hasOnboardingPlan:!!i.onboarding_plan},"ObiWidget")}else console.log("[obi-sdk] no session found with token:",e),se("no_matching_session",{sessionToken:e},"ObiWidget")}}catch(t){console.error("Failed to fetch session details:",t),ht(t,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e})}},"handleUrlSessionEvent","ObiWidget"),this.handleSessionStart=Ki(async e=>{if(se("session_start_requested",{sessionToken:e},"ObiWidget"),this.activeSession){se("session_start_blocked",{sessionToken:e},"ObiWidget"),console.log("Connection already in progress or active session exists");return}this.showSessionStartModal=!1,this.state=H.LOADING,Ni({widgetState:this.state.toString()}),await this.connectObi(e)},"handleSessionStart","ObiWidget"),this.checkExistingSession=Ki(async()=>{se("checking_existing_session",{},"ObiWidget");try{const e=JSON.parse(Su.getItem(Eu.SESSION_DATA)||"{}"),{sessionToken:t,roomToken:n,roomUrl:i,sessionExpiry:r,obiState:s}=e;if(!t||!n||!i){se("no_existing_session_data",{},"ObiWidget");return}if(console.log("[obi-sdk] using existing session"),se("existing_session_data_found",{sessionToken:t,hasExpiry:!!r,obiState:s},"ObiWidget"),r&&new Date(r)<new Date){this.clearSessionStorage(),se("session_expired",{sessionToken:t},"ObiWidget");return}this.state=H.LOADING,Ni({sessionId:t,widgetState:this.state.toString()});const o=this.createSession(t);if(!o){this.handleSessionCreationFailure(()=>this.clearSessionStorage());return}this.setupSessionEventListeners(o,()=>this.clearSessionStorage()),await o.reconnect(i,n,s)?(this.activeSession=o,this.sessionToken=t,this.roomToken=n,this.roomUrl=i,this.state=s,this.storedActiveState=s,se("session_reconnected",{sessionToken:t,obiState:s},"ObiWidget")):(this.clearSessionStorage(),se("session_reconnection_failed",{sessionToken:t},"ObiWidget"))}catch(e){console.error("Error reconnecting to session:",e),ht(e,{componentName:"ObiWidget",handlerName:"checkExistingSession"}),this.handleSessionCreationFailure(()=>this.clearSessionStorage())}},"checkExistingSession","ObiWidget");try{Bm("ObiWidget").setContext(),this.obiClient=new Th({baseUrl:Ma});const t=()=>{try{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()}catch(n){ht(n,{componentName:"ObiWidget",handlerName:"handleUnload"})}};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",t),se("ObiWidget_constructor_completed",{},"ObiWidget")}catch(e){throw ht(e,{componentName:"ObiWidget",lifecycle:"constructor"}),e}}updateFromConfig(){if(window.obiWidgetConfig){this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,this.position=window.obiWidgetConfig.position||this.position,this.user=window.obiWidgetConfig.user||this.user,window.obiWidgetConfig.isActive!==void 0&&(this.isActive=window.obiWidgetConfig.isActive),window.obiWidgetConfig.linkOnlyAccess!==void 0&&(this.linkOnlyAccess=window.obiWidgetConfig.linkOnlyAccess);const e=window.obiWidgetConfig?.primaryColor||Hr;this.style.setProperty("--obi-primary",e),this.generateColorVariables(e)}}generateColorVariables(e){try{const t=Na(e,"#c4b5fd"),n=Na(e,"#c76cff"),i=ew(e),r=Na(e,"#A06DF9");this.style.setProperty("--obi-secondary",t),this.style.setProperty("--obi-course-selected",n),this.style.setProperty("--obi-course-selected-bg",i),this.style.setProperty("--obi-paused-pulse",r)}catch(t){console.warn("Failed to generate color variables:",t),this.style.setProperty("--obi-secondary","#c4b5fd"),this.style.setProperty("--obi-course-selected","#c76cff"),this.style.setProperty("--obi-course-selected-bg","#fbf3ff"),this.style.setProperty("--obi-paused-pulse","#A06DF9")}}removeSessionUrlParams(){const e=new URL(window.location.href);e.searchParams.delete(Rh),window.history.replaceState({},"",e.toString()),localStorage.removeItem("obi-url-params")}createSession(e){try{const t=new LC({sessionId:e,apiBaseUrl:Ma});return t||(console.error("Failed to create session"),null)}catch(t){return console.error("Error creating session:",t),null}}setupSessionEventListeners(e,t){e.on("stateChanged",n=>{if(n===H.RESEARCHING){this.researchingTimeoutRef&&window.clearTimeout(this.researchingTimeoutRef),this.state=n,this.researchingTimeoutRef=window.setTimeout(()=>{this.researchingTimeoutRef=null;const i=e.getCurrentState();this.state=i,i!==H.READY&&(this.storedActiveState=i)},1500),this.storedActiveState=n;return}this.researchingTimeoutRef===null&&(this.state=n,n!==H.READY&&(this.storedActiveState=n))}),e.on("volume",({speaker:n,spectrum:i,volume:r})=>{this.volume={speaker:n,spectrum:i,volume:r}}),e.on("error",n=>{console.error("Session error:",n),this.state=H.ERROR,this.activeSession=null,t&&t()})}handleSessionCreationFailure(e){this.state=H.ERROR,this.activeSession=null,e&&e()}clearSessionStorage(){Su.removeItem(Eu.SESSION_DATA)}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};Su.setItem(Eu.SESSION_DATA,JSON.stringify(t))}}async sessionConnectionCheck(){const e=function(){let t={};return t=JSON.parse(localStorage.getItem("obi-url-params")||"{}"),Object.keys(t).length===0&&new URLSearchParams(window.location.search).forEach((i,r)=>{t[r]=i}),localStorage.removeItem("obi-url-params"),t[Rh]}();if(!e){await this.checkExistingSession();return}console.log("[obi-sdk] using magic link"),this.apiKey?await this.handleUrlSessionEvent(e):(console.log("[obi-sdk] API key not ready, retrying..."),setTimeout(()=>{this.apiKey&&this.handleUrlSessionEvent(e)},100))}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.addEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.addEventListener("course-select",this.handleCourseSelectEvent),this.isActive&&this.sessionConnectionCheck()}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),this.removeSessionUrlParams()}handleConfigUpdate(e){const i=e.detail.isActive&&!this.isActive;this.updateFromConfig(),this.position&&this.setAttribute("position",this.position),i&&this.sessionConnectionCheck(),this.requestUpdate()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=H.READY}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}li([e,t]).with(["pause",!0],()=>{this.activeSession?.pauseRecording()}).with(["pause",!1],()=>{this.activeSession?.resumeRecording()}).with(["activate",!1],()=>{this.terminateSession()}).otherwise(()=>{})}render(){if(!this.isActive||this.linkOnlyAccess&&this.state===H.READY)return L.nothing;const e=li(this.state).with(H.LOADING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with(H.RESEARCHING,()=>L.html`<obi-searching-loader></obi-searching-loader>`).with(SC.union(H.USER_SPEAKING,H.AGENT_SPEAKING),()=>L.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with(H.THINKING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with(H.PAUSED,()=>co).otherwise(()=>co),t=this.state===H.USER_SPEAKING||this.state===H.AGENT_SPEAKING,n=this.state===H.PAUSED,i=this.state===H.RESEARCHING,r=this.state===H.USER_SPEAKING,s=this.state!==H.READY||this.navVisible,o=this.state!==H.READY||this.navVisible,a=this.position.includes("top")?"down":"up",c=["widget-container",s?"rotated":"",t?"pulse":"",n?"paused-pulse":"",i?"researching":"",r?"user-speaking":""].filter(Boolean).join(" ");return L.html`
|
|
936
936
|
<div
|
|
937
937
|
class="${c}"
|
|
938
938
|
@mouseenter=${this.handleMouseEnter}
|