sip-connector 28.0.1 → 28.1.0

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.
@@ -0,0 +1 @@
1
+ "use strict";const j=require("@krivega/jssip"),ye=require("webrtc-mock"),_=require("events-constructor"),we=require("debug"),ee=require("@krivega/timeout-requester"),Z=require("@krivega/cancelable-promise"),N=require("xstate"),Ne=require("repeated-calls"),Ie=require("stack-promises"),Cn=require("ua-parser-js");require("sequent-promises");const pn=require("lodash"),Ge="sip-connector",Rn=we(Ge),Nn=()=>{we.enable(`${Ge}:*`)},In=()=>{we.enable(`-${Ge}:*`)},v=t=>Rn.extend(t),An="Error decline with 603",vn=1006,fn=t=>typeof t=="object"&&t!==null&&"code"in t&&t.code===vn,On=t=>t.message===An;var Te=(t=>(t.SPECTATOR="SPECTATOR",t.PARTICIPANT="PARTICIPANT",t))(Te||{}),q=(t=>(t.SHARE_STATE="application/vinteo.webrtc.sharedesktop",t.MAIN_CAM="application/vinteo.webrtc.maincam",t.ENTER_ROOM="application/vinteo.webrtc.roomname",t.MIC="application/vinteo.webrtc.mic",t.USE_LICENSE="application/vinteo.webrtc.uselic",t.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",t.NOTIFY="application/vinteo.webrtc.notify",t))(q||{}),x=(t=>(t.SHARE_STATE="application/vinteo.webrtc.sharedesktop",t.MAIN_CAM="application/vinteo.webrtc.maincam",t.CHANNELS="application/vinteo.webrtc.channels",t.MEDIA_STATE="application/vinteo.webrtc.mediastate",t.REFUSAL="application/vinteo.webrtc.refusal",t.STATS="application/vinteo.webrtc.stats",t))(x||{}),B=(t=>(t.PAUSE_MAIN_CAM="PAUSEMAINCAM",t.RESUME_MAIN_CAM="RESUMEMAINCAM",t.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",t.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",t.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",t))(B||{}),me=(t=>(t.ADMIN_STOP_MIC="ADMINSTOPMIC",t.ADMIN_START_MIC="ADMINSTARTMIC",t))(me||{}),gt=(t=>(t.H264="H264",t.VP8="VP8",t.VP9="VP9",t.AV1="AV1",t))(gt||{}),g=(t=>(t.CONTENT_TYPE="content-type",t.CONTENT_ENTER_ROOM="x-webrtc-enter-room",t.CONTENT_USE_LICENSE="x-webrtc-use-license",t.PARTICIPANT_NAME="x-webrtc-participant-name",t.INPUT_CHANNELS="x-webrtc-input-channels",t.OUTPUT_CHANNELS="x-webrtc-output-channels",t.MAIN_CAM="x-webrtc-maincam",t.MIC="x-webrtc-mic",t.MEDIA_SYNC="x-webrtc-sync",t.MAIN_CAM_RESOLUTION="x-webrtc-maincam-resolution",t.MEDIA_STATE="x-webrtc-media-state",t.MEDIA_TYPE="x-vinteo-media-type",t.MAIN_CAM_STATE="x-vinteo-maincam-state",t.MIC_STATE="x-vinteo-mic-state",t.CONTENT_PARTICIPANT_STATE="x-webrtc-partstate",t.AUDIO_ID="x-webrtc-audioid",t.SPECTATOR_MODE="x-webrtc-spectator-mode",t.NOTIFY="x-vinteo-notify",t.CONTENT_ENABLE_MEDIA_DEVICE="x-webrtc-request-enable-media-device",t.CONTENTED_STREAM_STATE="x-webrtc-share-state",t.CONTENTED_STREAM_CODEC="x-webrtc-share-codec",t.AVAILABLE_INCOMING_BITRATE="x-webrtc-available-incoming-bitrate",t.AUDIO_TRACK_COUNT="x-webrtc-audio-track-count",t.VIDEO_TRACK_COUNT="x-webrtc-video-track-count",t.TRACKS_DIRECTION="x-webrtc-tracks-direction",t.BEARER_TOKEN="x-bearer-token",t.IS_DIRECT_PEER_TO_PEER="x-webrtc-is-direct-p2p",t))(g||{}),ce=(t=>(t.AVAILABLE_CONTENTED_STREAM="YOUCANRECEIVECONTENT",t.NOT_AVAILABLE_CONTENTED_STREAM="CONTENTEND",t.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",t))(ce||{}),K=(t=>(t.AVAILABLE_CONTENTED_STREAM="x-webrtc-share-state: YOUCANRECEIVECONTENT",t.NOT_AVAILABLE_CONTENTED_STREAM="x-webrtc-share-state: CONTENTEND",t.ACK_PERMISSION_TO_START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",t.STOPPED_CLIENT_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",t.ENABLE_MAIN_CAM="x-webrtc-request-enable-media-device: LETMESTARTMAINCAM",t))(K||{}),Se=(t=>(t.ADMIN_SYNC_FORCED="1",t.ADMIN_SYNC_NOT_FORCED="0",t))(Se||{}),ke=(t=>(t.SPECTATOR_MANUAL="0",t.BY_STATE_CAM="1",t.SPECTATOR_FORCED="2",t))(ke||{}),Ue=(t=>(t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",t))(Ue||{});const $=t=>typeof t=="string"&&t.trim().length>0,Mn=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Tt=t=>typeof t=="boolean",_n=t=>Array.isArray(t)&&t.every($),mt=["enter-room","main-cam-control","use-license","new-dtmf","conference:participant-token-issued","contented-stream:available","contented-stream:not-available","presentation:must-stop","channels:all","channels:notify","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-stream","participant:move-request-to-spectators","participant:move-request-to-spectators-synthetic","participant:move-request-to-spectators-with-audio-id","participant:move-request-to-participants","participation:accepting-word-request","participation:cancelling-word-request","webcast:started","webcast:stopped","account:changed","account:deleted","admin:start-main-cam","admin:stop-main-cam","admin:start-mic","admin:stop-mic","admin:force-sync-media-state","failed-send-room-direct-p2p"],Pn=()=>new _.TypedEvents(mt),yn=t=>!(!Mn(t)||!$(t.conference)||!$(t.participant)||!$(t.jwt)),W=(t,e)=>{const n=e.toLowerCase(),s=Object.entries(t).find(([,r])=>typeof r=="string"&&r.toLowerCase()===n);return s?s[1]:void 0},bn=t=>typeof t=="string"&&!Number.isNaN(Number(t))&&Number.isFinite(Number(t)),Dn=t=>{if(bn(t))return Number(t)},Ln=t=>{const e=t.toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1},L=(t,e)=>{const n=t.getHeader(e.toLowerCase());if(!$(n))return;const s=n.toLowerCase();switch(e){case g.BEARER_TOKEN:return n;case g.CONTENT_ENTER_ROOM:case g.PARTICIPANT_NAME:case g.INPUT_CHANNELS:case g.OUTPUT_CHANNELS:case g.TRACKS_DIRECTION:case g.AUDIO_ID:case g.MAIN_CAM_RESOLUTION:case g.MEDIA_STATE:case g.NOTIFY:case g.CONTENT_ENABLE_MEDIA_DEVICE:return s;case g.MEDIA_TYPE:case g.MAIN_CAM_STATE:case g.MIC_STATE:case g.AVAILABLE_INCOMING_BITRATE:case g.AUDIO_TRACK_COUNT:case g.VIDEO_TRACK_COUNT:return Dn(s);case g.CONTENTED_STREAM_CODEC:return W(gt,s);case g.CONTENT_TYPE:return W(q,s);case g.CONTENT_USE_LICENSE:return W(Ue,s);case g.MAIN_CAM:return W(B,s);case g.MIC:return W(me,s);case g.MEDIA_SYNC:return W(Se,s);case g.CONTENT_PARTICIPANT_STATE:return W(Te,s);case g.SPECTATOR_MODE:return W(ke,s);case g.CONTENTED_STREAM_STATE:return W(ce,s);case g.IS_DIRECT_PEER_TO_PEER:return Ln(s);default:return}};var U=(t=>(t.CHANNELS="channels",t.WEBCAST_STARTED="WebcastStarted",t.WEBCAST_STOPPED="WebcastStopped",t.ACCOUNT_CHANGED="accountChanged",t.ACCOUNT_DELETED="accountDeleted",t.ADDED_TO_LIST_MODERATORS="addedToListModerators",t.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",t.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",t.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",t.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",t.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",t))(U||{});const We=v("ApiManager");class wn extends _.EventEmitterProxy{callManager;constructor(){super(Pn())}subscribe({connectionManager:e,callManager:n}){this.callManager=n,e.on("sipEvent",this.handleSipEvent),n.on("newInfo",this.handleNewInfo),n.on("newDTMF",({originator:s})=>{this.events.trigger("new-dtmf",{originator:s})})}async waitChannels(){return this.wait("channels:all")}async waitSyncMediaState(){return this.wait("admin:force-sync-media-state")}async sendDTMF(e){return new Promise((n,s)=>{let r;try{r=this.getEstablishedRTCSessionProtected()}catch(i){s(i)}r&&(this.callManager?.once("newDTMF",({originator:i})=>{i==="local"&&n()}),r.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:n}){const s=this.getEstablishedRTCSessionProtected(),r=`${g.INPUT_CHANNELS}: ${e}`,i=`${g.OUTPUT_CHANNELS}: ${n}`,a=[r,i];return s.sendInfo(x.CHANNELS,void 0,{extraHeaders:a})}sendEnterRoom(e){this.sendEnterRoomProtected(e).catch(n=>{this.events.trigger("failed-send-room-direct-p2p",{error:n})})}async sendMediaState({cam:e,mic:n},s={}){const r=this.getEstablishedRTCSessionProtected(),i=`${g.MEDIA_STATE}: currentstate`,a=`${g.MAIN_CAM_STATE}: ${Number(e)}`,o=`${g.MIC_STATE}: ${Number(n)}`,c=[i,a,o];return r.sendInfo(x.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const n=this.getEstablishedRTCSessionProtected(),r=[`${g.AVAILABLE_INCOMING_BITRATE}: ${e}`];return n.sendInfo(x.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:r})}async sendRefusalToTurnOn(e,n={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${g.MEDIA_TYPE}: ${a}`];return s.sendInfo(x.REFUSAL,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(x.SHARE_STATE,void 0,{extraHeaders:[K.AVAILABLE_CONTENTED_STREAM]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(x.SHARE_STATE,void 0,{extraHeaders:[K.ACK_PERMISSION_TO_START_PRESENTATION]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(x.SHARE_STATE,void 0,{extraHeaders:[K.STOPPED_CLIENT_PRESENTATION]})}async sendNotAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(x.SHARE_STATE,void 0,{extraHeaders:[K.NOT_AVAILABLE_CONTENTED_STREAM]})}async askPermissionToEnableCam(e={}){const n=this.getEstablishedRTCSessionProtected(),s=[K.ENABLE_MAIN_CAM];return n.sendInfo(x.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(r=>{if(On(r))throw r})}getEstablishedRTCSessionProtected=()=>{const e=this.callManager?.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const n=e.getHeader(g.NOTIFY);if(n){const s=JSON.parse(n);this.handleNotify(s)}}catch(n){We("error parse notify",n)}};handleNotify=e=>{switch(e.cmd){case U.CHANNELS:{this.triggerChannelsNotify(e);break}case U.WEBCAST_STARTED:{this.triggerWebcastStartedNotify(e);break}case U.WEBCAST_STOPPED:{this.triggerWebcastStoppedNotify(e);break}case U.ADDED_TO_LIST_MODERATORS:{this.triggerAddedToListModeratorsNotify(e);break}case U.REMOVED_FROM_LIST_MODERATORS:{this.triggerRemovedFromListModeratorsNotify(e);break}case U.ACCEPTING_WORD_REQUEST:{this.triggerParticipationAcceptingWordRequest(e);break}case U.CANCELLING_WORD_REQUEST:{this.triggerParticipationCancellingWordRequest(e);break}case U.MOVE_REQUEST_TO_STREAM:{this.triggerParticipantMoveRequestToStream(e);break}case U.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case U.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case U.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{this.maybeTriggerConferenceParticipantTokenIssued(e);break}default:We("unknown cmd",e)}};handleNewInfo=e=>{const{originator:n}=e;if(n!=="remote")return;const{request:s}=e,r=s,i=L(r,g.CONTENT_TYPE);if(i!==void 0)switch(i){case q.ENTER_ROOM:{this.triggerEnterRoom(r),this.maybeTriggerChannels(r);break}case q.NOTIFY:{this.maybeHandleNotify(r);break}case q.SHARE_STATE:{this.triggerContentedStreamState(r);break}case q.MAIN_CAM:{this.triggerMainCamControl(r);break}case q.MIC:{this.triggerMicControl(r);break}case q.USE_LICENSE:{this.triggerUseLicense(r);break}case q.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(r);break}}};triggerChannelsNotify=e=>{const n=e.input,s=e.output,r={inputChannels:n,outputChannels:s};this.events.trigger("channels:notify",r)};triggerWebcastStartedNotify=({body:{conference:e,type:n}})=>{const s={conference:e,type:n};this.events.trigger("webcast:started",s)};triggerWebcastStoppedNotify=({body:{conference:e,type:n}})=>{const s={conference:e,type:n};this.events.trigger("webcast:stopped",s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const n={conference:e};this.events.trigger("participant:added-to-list-moderators",n)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const n={conference:e};this.events.trigger("participant:removed-from-list-moderators",n)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const n={conference:e};this.events.trigger("participation:accepting-word-request",n)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const n={conference:e};this.events.trigger("participation:cancelling-word-request",n)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const n={conference:e};this.events.trigger("participant:move-request-to-stream",n)};triggerAccountChangedNotify=()=>{this.events.trigger("account:changed")};triggerAccountDeletedNotify=()=>{this.events.trigger("account:deleted")};maybeTriggerConferenceParticipantTokenIssued=({body:{conference:e,participant:n,jwt:s}})=>{const r={conference:e,participant:n,jwt:s};yn(r)&&this.events.trigger("conference:participant-token-issued",r)};maybeTriggerChannels=e=>{const n=L(e,g.INPUT_CHANNELS),s=L(e,g.OUTPUT_CHANNELS);if(n!==void 0&&s!==void 0){const r={inputChannels:n,outputChannels:s};this.events.trigger("channels:all",r)}};triggerEnterRoom=e=>{const n=L(e,g.CONTENT_ENTER_ROOM),s=L(e,g.PARTICIPANT_NAME),r=L(e,g.BEARER_TOKEN),i=L(e,g.IS_DIRECT_PEER_TO_PEER);n!==void 0&&s!==void 0&&this.events.trigger("enter-room",{room:n,participantName:s,bearerToken:r,isDirectPeerToPeer:i})};triggerContentedStreamState=e=>{const n=L(e,g.CONTENTED_STREAM_STATE);if(n!==void 0)switch(n){case ce.AVAILABLE_CONTENTED_STREAM:{const s=L(e,g.CONTENTED_STREAM_CODEC);this.events.trigger("contented-stream:available",{codec:s});break}case ce.NOT_AVAILABLE_CONTENTED_STREAM:{this.events.trigger("contented-stream:not-available");break}case ce.MUST_STOP_PRESENTATION:{this.events.trigger("presentation:must-stop");break}}};maybeTriggerParticipantMoveRequest=e=>{const n=L(e,g.CONTENT_PARTICIPANT_STATE),s=L(e,g.AUDIO_ID),r=L(e,g.SPECTATOR_MODE);if(n===Te.SPECTATOR){const i=r===ke.BY_STATE_CAM;s===void 0?(this.events.trigger("participant:move-request-to-spectators-synthetic",{isAvailableSendingMedia:i}),this.events.trigger("participant:move-request-to-spectators",{isAvailableSendingMedia:i,isSynthetic:!0})):(this.events.trigger("participant:move-request-to-spectators-with-audio-id",{isAvailableSendingMedia:i,audioId:s}),this.events.trigger("participant:move-request-to-spectators",{isAvailableSendingMedia:i,isSynthetic:!1,audioId:s}))}n===Te.PARTICIPANT&&this.events.trigger("participant:move-request-to-participants")};triggerMainCamControl=e=>{const n=L(e,g.MAIN_CAM),s=L(e,g.MEDIA_SYNC),r=s===Se.ADMIN_SYNC_FORCED;if(n===B.ADMIN_START_MAIN_CAM){this.events.trigger("admin:start-main-cam",{isSyncForced:r});return}if(n===B.ADMIN_STOP_MAIN_CAM){this.events.trigger("admin:stop-main-cam",{isSyncForced:r});return}(n===B.RESUME_MAIN_CAM||n===B.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger("admin:force-sync-media-state",{isSyncForced:r});const i=L(e,g.MAIN_CAM_RESOLUTION);this.events.trigger("main-cam-control",{mainCam:n,resolutionMainCam:i})};triggerMicControl=e=>{const n=L(e,g.MIC),r=L(e,g.MEDIA_SYNC)===Se.ADMIN_SYNC_FORCED;n===me.ADMIN_START_MIC?this.events.trigger("admin:start-mic",{isSyncForced:r}):n===me.ADMIN_STOP_MIC&&this.events.trigger("admin:stop-mic",{isSyncForced:r})};triggerUseLicense=e=>{const n=L(e,g.CONTENT_USE_LICENSE);n!==void 0&&this.events.trigger("use-license",n)};async sendEnterRoomProtected(e){return this.getEstablishedRTCSessionProtected().sendInfo(q.ENTER_ROOM,void 0,{extraHeaders:e})}}const Qe=0,Gn=30;class kn{countInner=Qe;initialCount=Qe;limitInner=Gn;isInProgress=!1;onStatusChange;constructor({onStatusChange:e}){this.onStatusChange=e}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.countInner>=this.limitInner}startAttempt(){this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}}class Un{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableGetParameters=void 0;constructor({connectionManager:e,interval:n}){this.connectionManager=e,this.interval=n}start(e,{onSuccessRequest:n,onFailRequest:s}){this.stop(),this.cancelableGetParameters=new Z.CancelableRequest(e),this.checkTelephonyByTimeout=ee.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableGetParameters)throw new Error("cancelableGetParameters is not defined");const r=await this.cancelableGetParameters.request();return this.connectionManager.checkTelephony(r)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),n()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableGetParameters?.cancelRequest(),this.cancelableGetParameters=void 0}}class St{callManager;disposers=[];constructor({callManager:e}){this.callManager=e}subscribe(e){this.unsubscribe(),this.disposers.push(this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange(e)})),this.handleCallStatusChange(e)}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[]}handleCallStatusChange({onActive:e,onInactive:n}){this.callManager.isCallActive?e?.():n()}}const Fn=15e3,Bn=2,Ae=v("PingServerRequester");class $n{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=ee.requesterByTimeoutsWithFailCalls(Bn,{whenPossibleRequest:async()=>{},requestInterval:Fn,request:async()=>(Ae("ping"),this.connectionManager.ping().then(()=>{Ae("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(Ae)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}const Ye=v("PingServerIfNotActiveCallRequester");class xn{pingServerRequester;notActiveCallSubscriber;constructor({connectionManager:e,callManager:n}){this.pingServerRequester=new $n({connectionManager:e}),this.notActiveCallSubscriber=new St({callManager:n})}start({onFailRequest:e}){Ye("start"),this.notActiveCallSubscriber.subscribe({onActive:()=>{this.pingServerRequester.stop()},onInactive:()=>{this.pingServerRequester.start({onFailRequest:e})}})}stop(){Ye("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.notActiveCallSubscriber.unsubscribe()}}class qn{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:n}){this.connectionManager=e,this.notActiveCallSubscriber=new St({callManager:n})}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.notActiveCallSubscriber.subscribe({onInactive:()=>{this.isRegistrationFailed&&e()}}),this.disposers.push(()=>{this.notActiveCallSubscriber.unsubscribe()})}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const Vn={baseRetryDelayMs:1e3,maxRetryDelayMs:3e4,warningThreshold:3,criticalThreshold:5},je={none:0,warning:1,critical:2};class Hn{failCount=0;nextRetryAtMs=0;escalationLevel="none";options;constructor(e){this.options={...Vn,...e}}registerFailure(){this.failCount+=1;const e=this.resolveEscalationLevel(this.failCount),n=je[e]>je[this.escalationLevel];this.escalationLevel=e;const s=Date.now(),r=Math.max(this.nextRetryAtMs-s,0);if(r>0)return{failCount:this.failCount,escalationLevel:this.escalationLevel,hasEscalated:n,shouldRequestReconnect:!1,nextRetryDelayMs:r};const i=this.resolveBackoffDelayMs(this.failCount);return this.nextRetryAtMs=s+i,{failCount:this.failCount,escalationLevel:this.escalationLevel,hasEscalated:n,shouldRequestReconnect:!0,nextRetryDelayMs:i}}reset(){this.failCount=0,this.nextRetryAtMs=0,this.escalationLevel="none"}resolveEscalationLevel(e){return e>=this.options.criticalThreshold?"critical":e>=this.options.warningThreshold?"warning":"none"}resolveBackoffDelayMs(e){return Math.min(this.options.baseRetryDelayMs*2**Math.max(e-1,0),this.options.maxRetryDelayMs)}}const k=v("AutoConnectorRuntime"),Wn=3e3,Qn=15e3;class Yn{connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;telephonyFailPolicy;emitters;reconnectActions;constructor(e){this.connectionManager=e.connectionManager,this.connectionQueueManager=e.connectionQueueManager,this.emitters=e.emitters,this.reconnectActions=e.reconnectActions,this.checkTelephonyRequester=new Un({connectionManager:this.connectionManager,interval:e.options?.checkTelephonyRequestInterval??Qn}),this.pingServerIfNotActiveCallRequester=new xn({connectionManager:this.connectionManager,callManager:e.callManager}),this.registrationFailedOutOfCallSubscriber=new qn({connectionManager:this.connectionManager,callManager:e.callManager}),this.delayBetweenAttempts=new ee.DelayRequester(e.options?.timeoutBetweenAttempts??Wn),this.telephonyFailPolicy=new Hn(e.options?.telephonyFailPolicy),this.attemptsState=new kn({onStatusChange:this.emitters.emitStatusChange})}async stopConnectionFlow(){k("stopConnectionFlow"),this.stopAttempts(),this.stopConnectTriggers(),await this.connectionQueueManager.disconnect()}async connect(e){await this.connectionQueueManager.connect(e.getParameters,e.options)}async delayBeforeRetry(){await this.delayBetweenAttempts.request()}cancelPendingRetry(){this.delayBetweenAttempts.cancelRequest()}hasLimitReached(){return this.attemptsState.hasLimitReached()}shouldDisconnectBeforeAttempt(){const{isDisconnected:e,isIdle:n,isDisconnecting:s,requested:r}=this.connectionManager;return s||r?!0:!(e||n)}beforeAttempt(){k("entryAttemptingGate"),this.emitters.emitBeforeAttempt(),this.stopConnectTriggers()}beforeConnectAttempt(){k("entryAttemptingConnect"),this.attemptsState.startAttempt(),this.attemptsState.increment()}onLimitReached(e){k("onLimitReachedTransition"),this.attemptsState.finishAttempt(),this.emitters.emitLimitReachedAttempts(),this.startCheckTelephony(e)}onConnectSucceeded(e){this.subscribeToConnectTriggers(e),this.emitters.emitSuccess()}emitTerminalOutcome({stopReason:e,lastError:n}){if(this.attemptsState.finishAttempt(),e==="halted"){this.emitters.emitStopAttemptsByError(n);return}if(e==="cancelled"){this.emitters.emitCancelledAttempts(n);return}if(e==="failed"){this.emitters.emitFailedAllAttempts(n);return}k("emitTerminalOutcome without stopReason",n)}onTelephonyStillConnected(){k("onTelephonyStillConnected"),this.stopConnectTriggers(),this.emitters.emitSuccess()}stopConnectTriggers(){k("stopConnectTriggers"),this.pingServerIfNotActiveCallRequester.stop(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.cancelPendingRetry(),this.attemptsState.reset()}startCheckTelephony(e){k("startCheckTelephony"),this.checkTelephonyRequester.start(async()=>e.getParameters(),{onSuccessRequest:()=>{k("startCheckTelephony: onSuccessRequest"),this.telephonyFailPolicy.reset(),this.isConnectionUnavailable()?this.reconnectActions.requestReconnect(e,"telephony-disconnected"):this.reconnectActions.notifyTelephonyStillConnected()},onFailRequest:n=>{const s=this.telephonyFailPolicy.registerFailure();this.emitters.emitTelephonyCheckFailure({failCount:s.failCount,escalationLevel:s.escalationLevel,shouldRequestReconnect:s.shouldRequestReconnect,nextRetryDelayMs:s.nextRetryDelayMs,error:n}),s.escalationLevel!=="none"&&s.hasEscalated&&this.emitters.emitTelephonyCheckEscalated({failCount:s.failCount,escalationLevel:s.escalationLevel,error:n}),s.shouldRequestReconnect&&this.reconnectActions.requestReconnect(e,"telephony-check-failed"),k("startCheckTelephony: onFailRequest",n?.message)}})}subscribeToConnectTriggers(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{k("pingRequester: onFailRequest")}}),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{k("registrationFailedOutOfCallListener callback"),this.reconnectActions.requestReconnect(e,"registration-failed-out-of-call")})}isConnectionUnavailable(){const{isDisconnected:e,isIdle:n}=this.connectionManager;return e||n}}class te{actor;subscriptions=[];stateChangeListeners=new Set;constructor(e){this.actor=N.createActor(e),this.actor.start(),this.addSubscription(this.subscribe(n=>{const s=n.value;this.stateChangeListeners.forEach(r=>{r(s)})}))}get state(){return this.getSnapshot().value}get context(){return this.getSnapshot().context}send(e){this.actor.send(e)}getSnapshot(){return this.actor.getSnapshot()}subscribe(e){const n=this.actor.subscribe(e);return this.addSubscription(n),n}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}stop(){this.stateChangeListeners.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0,this.actor.stop()}addSubscription(e){const n=typeof e=="function"?e:()=>{e.unsubscribe()};return this.subscriptions.push(n),n}}const Ct="Not ready for connection",pt=t=>t instanceof Error&&t.message===Ct,jn=()=>new Error(Ct),zn=async t=>typeof t=="function"?t():t,Jn=3;class Kn{resolveParametersRequester=new Z.CancelableRequest(zn);cancelableConnectWithRepeatedCalls;numberOfConnectionAttempts;dependencies;constructor(e,{numberOfConnectionAttempts:n=Jn}={}){this.dependencies=e,this.numberOfConnectionAttempts=n,this.proxyEvents()}connect=async(e,n)=>(this.dependencies.stateMachine.toStartConnect(),this.dependencies.events.trigger("connect-started",{}),this.cancelRequests(),this.resolveParametersRequester.request(e).then(s=>(this.dependencies.events.trigger("connect-parameters-resolve-success",s),s)).catch(s=>{throw this.dependencies.events.trigger("connect-parameters-resolve-failed",s),s}).then(async s=>this.connectWithDuplicatedCalls(s,n)).then(s=>(this.dependencies.events.trigger("connect-succeeded",{...s}),s)).catch(s=>{const r=s??new Error("Failed to connect to server");throw Z.isCanceledError(r)||this.dependencies.events.trigger("connect-failed",r),r}));disconnect=async({cancelRequests:e=!0}={})=>{e&&this.cancelRequests(),this.dependencies.events.trigger("disconnecting",{});const n=new Promise(r=>{this.dependencies.events.once("disconnected",()=>{r()})}),s=this.dependencies.getUa();return s?s.stop():this.dependencies.events.trigger("disconnected",{socket:{},error:!1}),n.finally(()=>{s?.removeAllListeners(),this.dependencies.setUa(void 0),this.dependencies.stateMachine.reset()})};cancelRequests(){this.resolveParametersRequester.cancelRequest(),this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{numberOfConnectionAttempts:n=this.numberOfConnectionAttempts}={})=>{const s=async()=>this.connectInner(e),r=i=>{const c=this.dependencies.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),E=i!=null&&!fn(i);return c||E};return this.cancelableConnectWithRepeatedCalls=Ne.repeatedCallsAsync({targetFunction:s,isComplete:r,callLimit:n,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(i=>{if(typeof i=="object"&&i!==null&&"authorizationUser"in i)return i;throw i})};hasEqualConnectionConfiguration(e){const{configuration:n}=this.dependencies.uaFactory.createConfiguration(e),r=this.dependencies.getUa()?.configuration;return r?r.password===n.password&&r.register===n.register&&r.uri.toString()===n.uri&&r.display_name===n.display_name&&r.user_agent===n.user_agent&&r.sockets===n.sockets&&r.session_timers===n.session_timers&&r.register_expires===n.register_expires&&r.connection_recovery_min_interval===n.connection_recovery_min_interval&&r.connection_recovery_max_interval===n.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async({configuration:n})=>this.start(n));initUa=async({user:e,password:n,sipServerIp:s,sipServerUrl:r,remoteAddress:i,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:E,userAgent:p,displayName:A="",register:b=!1,extraHeaders:M=[]})=>{this.dependencies.getUa()&&await this.disconnect({cancelRequests:!1});const{ua:G,helpers:z}=this.dependencies.uaFactory.createUAWithConfiguration({user:e,password:n,sipServerIp:s,sipServerUrl:r,displayName:A,register:b,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:E,userAgent:p,remoteAddress:i,extraHeaders:M},this.dependencies.events);this.dependencies.setUa(G),this.dependencies.setGetUri(z.getUri),this.dependencies.setSocket(z.socket);const ne=G.configuration.uri.user;return{ua:G,configuration:{sipServerIp:s,sipServerUrl:r,displayName:A,authorizationUser:ne,register:b,user:e,password:n}}};start=async e=>new Promise((n,s)=>{const r=this.dependencies.getUa();if(!r){s(new Error("this.ua is not initialized"));return}let i;i=((E,p)=>{if(e.register===!0)return this.dependencies.registrationManager.subscribeToStartEvents(E,p);const A="connected",b=["disconnected"];return this.dependencies.events.on(A,E),b.forEach(M=>{this.dependencies.events.on(M,p)}),()=>{this.dependencies.events.off(A,E),b.forEach(M=>{this.dependencies.events.off(M,p)})}})(()=>{i?.(),n(e)},E=>{i?.(),s(E)}),this.dependencies.stateMachine.toStartUa(e),r.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}proxyEvents(){this.dependencies.events.on("connected",()=>{const e=this.dependencies.stateMachine.getConnectionConfiguration();e!==void 0&&this.dependencies.events.trigger("connected-with-configuration",e)})}}var d=(t=>(t.IDLE="connection:idle",t.PREPARING="connection:preparing",t.CONNECTING="connection:connecting",t.CONNECTED="connection:connected",t.REGISTERED="connection:registered",t.ESTABLISHED="connection:established",t.DISCONNECTING="connection:disconnecting",t.DISCONNECTED="connection:disconnected",t))(d||{}),I=(t=>(t.LOG_TRANSITION="logTransition",t.LOG_STATE_CHANGE="logStateChange",t.SET_CONNECTION_CONFIGURATION="setConnectionConfiguration",t.CLEAR_CONNECTION_CONFIGURATION="clearConnectionConfiguration",t))(I||{}),T=(t=>(t.START_CONNECT="START_CONNECT",t.START_UA="START_UA",t.START_DISCONNECT="START_DISCONNECT",t.UA_CONNECTED="UA_CONNECTED",t.UA_CONNECTING="UA_CONNECTING",t.UA_REGISTERED="UA_REGISTERED",t.UA_UNREGISTERED="UA_UNREGISTERED",t.UA_DISCONNECTED="UA_DISCONNECTED",t.RESET="RESET",t))(T||{});const Rt={connectionConfiguration:void 0},ze=v("ConnectionStateMachine"),Xn=()=>N.setup({types:{context:Rt,events:{}},guards:{canAutoEstablish:({context:t})=>t.connectionConfiguration?.register!==!0},actions:{[I.SET_CONNECTION_CONFIGURATION]:N.assign(({event:t})=>({connectionConfiguration:{...t.configuration}})),[I.CLEAR_CONNECTION_CONFIGURATION]:N.assign(()=>({connectionConfiguration:void 0})),[I.LOG_TRANSITION]:(t,e)=>{ze(`State transition: ${e.from} -> ${e.to} (${e.event})`)},[I.LOG_STATE_CHANGE]:(t,e)=>{ze("ConnectionStateMachine state changed",e.state)}}}),Zn=()=>Xn().createMachine({id:"connection",initial:d.IDLE,context:Rt,states:{[d.IDLE]:{entry:[{type:I.LOG_STATE_CHANGE,params:{state:d.IDLE}},{type:I.CLEAR_CONNECTION_CONFIGURATION}],on:{[T.START_CONNECT]:{target:d.PREPARING,actions:{type:I.LOG_TRANSITION,params:{from:d.IDLE,to:d.PREPARING,event:T.START_CONNECT}}}}},[d.PREPARING]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.PREPARING}},on:{[T.START_UA]:{target:d.CONNECTING,actions:[I.SET_CONNECTION_CONFIGURATION,{type:I.LOG_TRANSITION,params:{from:d.PREPARING,to:d.CONNECTING,event:T.START_UA}}]},[T.UA_DISCONNECTED]:{target:d.DISCONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.PREPARING,to:d.DISCONNECTED,event:T.UA_DISCONNECTED}}}}},[d.CONNECTING]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.CONNECTING}},on:{[T.UA_CONNECTED]:{target:d.CONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTING,to:d.CONNECTED,event:T.UA_CONNECTED}}},[T.UA_REGISTERED]:{target:d.REGISTERED,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTING,to:d.REGISTERED,event:T.UA_REGISTERED}}},[T.START_DISCONNECT]:{target:d.DISCONNECTING,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTING,to:d.DISCONNECTING,event:T.START_DISCONNECT}}},[T.UA_DISCONNECTED]:{target:d.DISCONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTING,to:d.DISCONNECTED,event:T.UA_DISCONNECTED}}}}},[d.CONNECTED]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.CONNECTED}},always:{target:d.ESTABLISHED,guard:"canAutoEstablish",actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTED,to:d.ESTABLISHED,event:"always"}}},on:{[T.UA_REGISTERED]:{target:d.REGISTERED,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTED,to:d.REGISTERED,event:T.UA_REGISTERED}}},[T.START_DISCONNECT]:{target:d.DISCONNECTING,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTED,to:d.DISCONNECTING,event:T.START_DISCONNECT}}},[T.UA_DISCONNECTED]:{target:d.DISCONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.CONNECTED,to:d.DISCONNECTED,event:T.UA_DISCONNECTED}}}}},[d.REGISTERED]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.REGISTERED}},always:{target:d.ESTABLISHED,actions:{type:I.LOG_TRANSITION,params:{from:d.REGISTERED,to:d.ESTABLISHED,event:"always"}}},on:{[T.UA_UNREGISTERED]:{target:d.CONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.REGISTERED,to:d.CONNECTED,event:T.UA_UNREGISTERED}}},[T.START_DISCONNECT]:{target:d.DISCONNECTING,actions:{type:I.LOG_TRANSITION,params:{from:d.REGISTERED,to:d.DISCONNECTING,event:T.START_DISCONNECT}}},[T.UA_DISCONNECTED]:{target:d.DISCONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.REGISTERED,to:d.DISCONNECTED,event:T.UA_DISCONNECTED}}}}},[d.ESTABLISHED]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.ESTABLISHED}},on:{[T.START_DISCONNECT]:{target:d.DISCONNECTING,actions:{type:I.LOG_TRANSITION,params:{from:d.ESTABLISHED,to:d.DISCONNECTING,event:T.START_DISCONNECT}}},[T.UA_DISCONNECTED]:{target:d.DISCONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.ESTABLISHED,to:d.DISCONNECTED,event:T.UA_DISCONNECTED}}},[T.RESET]:{target:d.IDLE,actions:{type:I.LOG_TRANSITION,params:{from:d.ESTABLISHED,to:d.IDLE,event:T.RESET}}}}},[d.DISCONNECTING]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.DISCONNECTING}},on:{[T.UA_DISCONNECTED]:{target:d.DISCONNECTED,actions:{type:I.LOG_TRANSITION,params:{from:d.DISCONNECTING,to:d.DISCONNECTED,event:T.UA_DISCONNECTED}}}}},[d.DISCONNECTED]:{entry:{type:I.LOG_STATE_CHANGE,params:{state:d.DISCONNECTED}},on:{[T.RESET]:{target:d.IDLE,actions:[{type:I.LOG_TRANSITION,params:{from:d.DISCONNECTED,to:d.IDLE,event:T.RESET}}]},[T.START_CONNECT]:{target:d.PREPARING,actions:{type:I.LOG_TRANSITION,params:{from:d.DISCONNECTED,to:d.PREPARING,event:T.START_CONNECT}}},[T.UA_CONNECTING]:{target:d.CONNECTING,actions:{type:I.LOG_TRANSITION,params:{from:d.DISCONNECTED,to:d.CONNECTING,event:T.UA_CONNECTING}}}}}}}),es=Zn(),ts=v("ConnectionStateMachine");class Nt extends te{events;unsubscribeFromEvents;constructor(e){super(es),this.events=e,this.subscribeToEvents()}get isIdle(){return this.hasState(d.IDLE)}get isPreparing(){return this.hasState(d.PREPARING)}get isConnecting(){return this.hasState(d.CONNECTING)}get isConnected(){return this.hasState(d.CONNECTED)}get isRegistered(){return this.hasState(d.REGISTERED)}get isEstablished(){return this.hasState(d.ESTABLISHED)}get isDisconnecting(){return this.hasState(d.DISCONNECTING)}get isDisconnected(){return this.hasState(d.DISCONNECTED)}get isPending(){return this.isPreparing||this.isConnecting}get isPendingConnect(){return this.isPreparing}get isPendingInitUa(){return this.isConnecting}get isActiveConnection(){return this.isEstablished||this.isConnected||this.isRegistered}toStartConnect=()=>{this.sendEvent({type:T.START_CONNECT})};toStartUa=e=>{this.sendEvent({type:T.START_UA,configuration:e})};reset(){this.toIdle()}getConnectionConfiguration(){if(this.context.connectionConfiguration!==void 0)return{...this.context.connectionConfiguration}}isRegisterEnabled(){return this.context.connectionConfiguration?.register===!0}destroy(){this.unsubscribeFromEvents?.(),this.stop()}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){ts(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartDisconnect=()=>{this.sendEvent({type:T.START_DISCONNECT})};toConnecting=()=>{this.sendEvent({type:T.UA_CONNECTING})};toConnected=()=>{this.sendEvent({type:T.UA_CONNECTED})};toRegistered=()=>{this.sendEvent({type:T.UA_REGISTERED})};toUnregistered=()=>{this.sendEvent({type:T.UA_UNREGISTERED})};toDisconnected=()=>{this.sendEvent({type:T.UA_DISCONNECTED})};toIdle=()=>{this.sendEvent({type:T.RESET})};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("connecting",this.toConnecting),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnecting",this.toStartDisconnect),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toDisconnected),this.events.on("connect-failed",this.toDisconnected),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("connecting",this.toConnecting),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnecting",this.toStartDisconnect),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toDisconnected),this.events.off("connect-failed",this.toDisconnected)}}}const It=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],ns=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-success","connect-parameters-resolve-failed","connected-with-configuration"],At=[...It,...ns],vt=()=>new _.TypedEvents(At),ss=v("RegistrationManager");class rs{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((n,s)=>{e.on("registered",n),e.on("registrationFailed",s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(n=>{e.on("unregistered",n),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){ss("tryRegister",e)}return this.register()}subscribeToStartEvents(e,n){const s="registered",r=["registrationFailed","disconnected"];return this.events.on(s,e),r.forEach(i=>{this.events.on(i,n)}),()=>{this.events.off(s,e),r.forEach(i=>{this.events.off(i,n)})}}}class is{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,n,s){const r=this.getUaProtected();return new Promise((i,a)=>{try{r.sendOptions(e,n,{extraHeaders:s,eventHandlers:{succeeded:()=>{i()},failed:a}})}catch(o){a(o)}})}async ping(e,n){const r=this.getUaProtected().configuration.uri;return this.sendOptions(r,e,n)}async checkTelephony({userAgent:e,displayName:n,sipServerIp:s,sipServerUrl:r,remoteAddress:i,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:E}=this.uaFactory.createConfiguration({sipServerUrl:r,displayName:n,userAgent:e,sipServerIp:s}),p=this.uaFactory.createUA({...E,remoteAddress:i,extraHeaders:a}),A=()=>{const M=new Error("Telephony is not available");c(M)};p.once("disconnected",A);const b=()=>{p.removeAllListeners(),p.once("disconnected",()=>{o()}),p.stop()};p.once("connected",b),p.start()})}}function as(t){return e=>`sip:${e}@${t}`}const os=(t,e)=>()=>Math.floor(Math.random()*(e-t))+t,cs=t=>t.trim().replaceAll(" ","_"),ds=os(1e5,99999999),ls=t=>{const e=[];return t!==void 0&&t!==""&&e.push(`X-Vinteo-Remote: ${t}`),e};class X{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:n,user:s,sipServerIp:r,sipServerUrl:i}){if(!r)throw new Error("sipServerIp is required");if(!i)throw new Error("sipServerUrl is required");if(e&&(n===void 0||n===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,n){return e&&n!==void 0&&n.trim()!==""?n.trim():`${ds()}`}static buildExtraHeaders(e,n){const s=e!==void 0&&e!==""?ls(e):[];return n===void 0?s:[...s,...n]}createConfiguration({user:e,password:n,sipServerUrl:s,displayName:r="",sipServerIp:i,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:E=2,connectionRecoveryMaxInterval:p=6,userAgent:A}){X.validateParametersConnection({register:a,password:n,user:e,sipServerIp:i,sipServerUrl:s});const b=X.resolveAuthorizationUser(a,e),M=as(i),H=M(b),G=new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);return{configuration:{password:n,register:a,uri:H,display_name:cs(r),user_agent:A,sdpSemantics:"unified-plan",sockets:[G],session_timers:o,register_expires:c,connection_recovery_min_interval:E,connection_recovery_max_interval:p},helpers:{socket:G,getUri:M}}}createUA({remoteAddress:e,extraHeaders:n,...s}){const r=new this.JsSIP.UA(s),i=X.buildExtraHeaders(e,n);return i.length>0&&r.registrator().setExtraHeaders(i),r}createUAWithConfiguration(e,n){const{configuration:s,helpers:r}=this.createConfiguration(e),i=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return n.eachTriggers((a,o)=>{const c=It.find(E=>E===o);c&&i.on(c,a)}),{ua:i,helpers:r}}}const hs=v("ConnectionManager");class us extends _.EventEmitterProxy{stateMachine;ua;socket;uaFactory;registrationManager;connectionFlow;sipOperations;constructor({JsSIP:e},{numberOfConnectionAttempts:n}={}){super(vt()),this.uaFactory=new X(e),this.registrationManager=new rs({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new Nt(this.events),this.sipOperations=new is({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new Kn({events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,setUa:s=>{this.ua=s},setGetUri:s=>{this.getUri=s},setSocket:s=>{this.socket=s}},{numberOfConnectionAttempts:n})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get isIdle(){return this.stateMachine.isIdle}get isDisconnected(){return this.stateMachine.isDisconnected}get isDisconnecting(){return this.stateMachine.isDisconnecting}get connectionState(){return this.stateMachine.state}get isRegistered(){return X.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.stateMachine.isRegisterEnabled()}connect=async(e,n)=>this.disconnect().catch(s=>{hs("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,n));disconnect=async()=>{if(this.isConfigured()||this.requested)return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,n,s)=>this.sipOperations.sendOptions(e,n,s);ping=async(e,n)=>this.sipOperations.ping(e,n);checkTelephony=async e=>this.sipOperations.checkTelephony(e);isConfigured(){return this.ua!==void 0}getConnectionConfiguration=()=>this.stateMachine.getConnectionConfiguration();destroy(){this.stateMachine.destroy()}getUri=e=>e;getUser(){try{return this.getUaProtected().configuration.uri.user}catch{return}}getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,n)=>{if(!(n?.hasReadyForConnection?.()??!0))throw jn();return this.connectionFlow.connect(e,n).catch(async r=>{const i=r;return this.disconnect().then(()=>{throw i}).catch(()=>{throw i})})}}class Es{connectionManager;stackPromises=Ie.createStackPromises({noRunIsNotActual:!0});constructor({connectionManager:e}){this.connectionManager=e}connect=async(...e)=>this.stackPromises.run(async()=>this.connectionManager.connect(...e));disconnect=async()=>this.stackPromises.run(async()=>this.connectionManager.disconnect());stop(){this.stackPromises.stop()}}const Q=t=>{if(t!==null&&typeof t=="object"&&"error"in t)return t.error},P=v("AutoConnectorMachine"),Je=t=>t.parameters,gs=t=>N.setup({types:{context:{},events:{}},actors:{stopConnectionFlow:N.fromPromise(async()=>{P("stopConnectionFlow"),await t.stopConnectionFlow()}),connect:N.fromPromise(async({input:e})=>{if(P("connect",e),!e)throw new Error("Auto connector parameters are missing in attemptingConnect state");await t.connect(e)}),waitBeforeRetry:N.fromPromise(async()=>{P("waitBeforeRetry"),await t.delayBetweenAttempts()})},guards:{shouldDisconnectBeforeAttempt:()=>{const e=t.shouldDisconnectBeforeAttempt();return P("shouldDisconnectBeforeAttempt:",e),e},shouldGoIdleAfterDisconnect:({context:e})=>{const n=e.afterDisconnect==="idle";return P("shouldGoIdleAfterDisconnect:",n),n},shouldAttemptAfterDisconnect:({context:e})=>{const n=e.afterDisconnect==="attempt";return P("shouldAttemptAfterDisconnect:",n),n},isLimitReached:()=>{const e=t.hasLimitReached();return P("isLimitReached:",e),e},isNotReadyForConnection:({event:e})=>{const n=pt(Q(e));return P("isNotReadyForConnection:",n),n},isNoRetryPolicy:({event:e})=>{const n=!t.canRetryOnError(Q(e));return P("isNoRetryPolicy:",n),n},isNotActualPromise:({event:e})=>{const n=Ie.isPromiseIsNotActualError(Q(e));return P("isNotActualPromise:",n),n},isWaitRetryCancelled:({event:e})=>{const n=Q(e),s=Z.isCanceledError(n)||ee.hasCanceledError(n);return P("isWaitRetryCancelled:",s),s}},actions:{logRestartFailed:({event:e})=>{P("auto connector failed to restart connection attempts:",Q(e))},assignRestart:N.assign(({event:e})=>({parameters:e.parameters,afterDisconnect:"attempt",stopReason:void 0,lastError:void 0})),assignStop:N.assign({afterDisconnect:"idle",stopReason:()=>{},lastError:()=>{}}),entryAttemptingGate:()=>{P("entryAttemptingGate"),t.beforeAttempt()},entryAttemptingConnect:()=>{P("entryAttemptingConnect"),t.beforeConnectAttempt()},onLimitReachedTransition:({context:e})=>{P("onLimitReachedTransition"),t.onLimitReached(Je(e))},onConnectDone:({context:e})=>{P("onConnectDone"),t.onConnectSucceeded(Je(e))},assignHaltedError:N.assign({stopReason:()=>"halted",lastError:({event:e})=>{const n=Q(e);return P("assignHaltedError",n),n}}),assignCancelledNotActualError:N.assign({stopReason:()=>"cancelled",lastError:({event:e})=>{const n=Q(e);return P("assignCancelledNotActualError",n),n}}),assignWaitRetryCancelledError:N.assign({stopReason:()=>"cancelled",lastError:({event:e})=>{const n=Q(e);return P("assignWaitRetryCancelledError",n),n}}),assignWaitRetryFailedError:N.assign({stopReason:()=>"failed",lastError:({event:e})=>{const n=Q(e);return P("assignWaitRetryFailedError",n),n}}),emitTerminalOutcome:({context:e})=>{P("emitTerminalOutcome"),t.emitTerminalOutcome({stopReason:e.stopReason,lastError:e.lastError})},onTelephonyStillConnected:()=>{P("onTelephonyStillConnected"),t.onTelephonyStillConnected()}}});var O=(t=>(t.IDLE="idle",t.DISCONNECTING="disconnecting",t.ATTEMPTING_GATE="attemptingGate",t.ATTEMPTING_CONNECT="attemptingConnect",t.WAITING_BEFORE_RETRY="waitingBeforeRetry",t.CONNECTED_MONITORING="connectedMonitoring",t.TELEPHONY_CHECKING="telephonyChecking",t.ERROR_TERMINAL="errorTerminal",t))(O||{});const Ts=()=>({parameters:void 0,afterDisconnect:"idle",stopReason:void 0,lastError:void 0}),se=()=>({"AUTO.STOP":{target:O.DISCONNECTING,actions:"assignStop"},"AUTO.RESTART":{target:O.DISCONNECTING,actions:"assignRestart"}}),ms=t=>gs(t).createMachine({id:"autoConnector",initial:O.IDLE,context:Ts,states:{[O.IDLE]:{on:{"AUTO.STOP":{target:O.IDLE},"AUTO.RESTART":[{guard:"shouldDisconnectBeforeAttempt",target:O.DISCONNECTING,actions:"assignRestart"},{target:O.ATTEMPTING_GATE,actions:"assignRestart"}]}},[O.DISCONNECTING]:{invoke:{id:"stopConnectionFlow",src:"stopConnectionFlow",onDone:[{guard:"shouldGoIdleAfterDisconnect",target:O.IDLE},{guard:"shouldAttemptAfterDisconnect",target:O.ATTEMPTING_GATE}],onError:{actions:"logRestartFailed",target:O.IDLE}},on:{"AUTO.STOP":{target:O.DISCONNECTING,reenter:!0,actions:"assignStop"},"AUTO.RESTART":{actions:"assignRestart"}}},[O.ATTEMPTING_GATE]:{entry:"entryAttemptingGate",always:[{guard:"isLimitReached",target:O.TELEPHONY_CHECKING,actions:"onLimitReachedTransition"},{target:O.ATTEMPTING_CONNECT}],on:se()},[O.ATTEMPTING_CONNECT]:{entry:"entryAttemptingConnect",invoke:{id:"connect",src:"connect",input:({context:e})=>e.parameters,onDone:{target:O.CONNECTED_MONITORING,actions:"onConnectDone"},onError:[{guard:"isNotReadyForConnection",target:"errorTerminal",actions:"assignHaltedError"},{guard:"isNoRetryPolicy",target:"errorTerminal",actions:"assignHaltedError"},{guard:"isNotActualPromise",target:"errorTerminal",actions:"assignCancelledNotActualError"},{target:O.WAITING_BEFORE_RETRY}]},on:se()},[O.WAITING_BEFORE_RETRY]:{invoke:{id:"waitBeforeRetry",src:"waitBeforeRetry",onDone:{target:O.ATTEMPTING_GATE},onError:[{guard:"isWaitRetryCancelled",target:"errorTerminal",actions:"assignWaitRetryCancelledError"},{target:"errorTerminal",actions:"assignWaitRetryFailedError"}]},on:se()},[O.CONNECTED_MONITORING]:{on:se()},[O.TELEPHONY_CHECKING]:{on:{"AUTO.STOP":{target:O.DISCONNECTING,actions:"assignStop"},"AUTO.RESTART":{target:O.DISCONNECTING,actions:"assignRestart"},"TELEPHONY.RESULT":{target:O.CONNECTED_MONITORING,actions:"onTelephonyStillConnected"}}},[O.ERROR_TERMINAL]:{entry:"emitTerminalOutcome",on:se()}}}),Ss=v("AutoConnectorStateMachine");class Cs extends te{constructor(e){super(e)}send(e){if(!this.actor.getSnapshot().can(e)){Ss(`[AutoConnectorStateMachine] Invalid transition: ${e.type} from ${String(this.state)}. Event cannot be processed in current state.`);return}super.send(e)}toStop(){this.send({type:"AUTO.STOP"})}toRestart(e){this.send({type:"AUTO.RESTART",parameters:e})}toTelephonyResult(e){this.send({type:"TELEPHONY.RESULT",outcome:e})}toTelephonyResultStillConnected(){this.toTelephonyResult("stillConnected")}}const ft=t=>new Cs(ms(t)),ps="Failed to reconnect",Ke=t=>t instanceof Error?t:new Error(ps),Rs=t=>{const e=({stopReason:n,lastError:s})=>n==="cancelled"&&!Ie.isPromiseIsNotActualError(s)||n==="failed"?Ke(s):s;return{canRetryOnError:t.canRetryOnError,shouldDisconnectBeforeAttempt:()=>t.runtime.shouldDisconnectBeforeAttempt(),stopConnectionFlow:async()=>{await t.runtime.stopConnectionFlow()},connect:async n=>{await t.runtime.connect(n)},delayBetweenAttempts:async()=>{await t.runtime.delayBeforeRetry()},hasLimitReached:()=>t.runtime.hasLimitReached(),beforeAttempt:()=>{t.runtime.beforeAttempt()},beforeConnectAttempt:()=>{t.runtime.beforeConnectAttempt()},onLimitReached:n=>{t.runtime.onLimitReached(n)},onConnectSucceeded:n=>{t.runtime.onConnectSucceeded(n)},emitTerminalOutcome:({stopReason:n,lastError:s})=>{t.runtime.emitTerminalOutcome({stopReason:n,lastError:e({stopReason:n,lastError:s})})},onTelephonyStillConnected:()=>{t.runtime.onTelephonyStillConnected()}}},Ot=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts","telephony-check-failure","telephony-check-escalated"],Ns=()=>new _.TypedEvents(Ot),re={START:"start",MANUAL_RESTART:"manual-restart",REGISTRATION_FAILED_OUT_OF_CALL:"registration-failed-out-of-call",TELEPHONY_DISCONNECTED:"telephony-disconnected",TELEPHONY_CHECK_FAILED:"telephony-check-failed"},Is={[re.START]:0,[re.TELEPHONY_DISCONNECTED]:1,[re.TELEPHONY_CHECK_FAILED]:1,[re.REGISTRATION_FAILED_OUT_OF_CALL]:3,[re.MANUAL_RESTART]:4},Xe=t=>Is[t];class As{generation=0;lastRequest;coalesceWindowMs;constructor({coalesceWindowMs:e}){this.coalesceWindowMs=e}register(e){const n=Date.now(),s=Xe(e),{lastRequest:r}=this;if(r!==void 0&&n-r.timestamp<this.coalesceWindowMs){const a=Xe(r.reason);if(s<=a)return{shouldRequest:!1,generation:this.generation,currentPriority:s,coalescedBy:r.reason,coalescedByPriority:a}}return this.generation+=1,this.lastRequest={reason:e,timestamp:n},{shouldRequest:!0,generation:this.generation,currentPriority:s}}reset(){this.lastRequest=void 0}}const vs=250,fs={LIMIT_REACHED:"Limit reached"},Os=t=>!0,Y=v("AutoConnectorManager"),Ms="start",_s="manual-restart";class Ps extends _.EventEmitterProxy{stateMachine;runtime;reconnectCoalescer=new As({coalesceWindowMs:vs});constructor({connectionQueueManager:e,connectionManager:n,callManager:s},r){super(Ns()),this.runtime=new Yn({connectionManager:n,connectionQueueManager:e,callManager:s,options:r,emitters:{emitBeforeAttempt:()=>{this.events.trigger("before-attempt",{})},emitLimitReachedAttempts:()=>{this.events.trigger("limit-reached-attempts",new Error(fs.LIMIT_REACHED))},emitSuccess:()=>{Y("handleSucceededAttempt"),this.events.trigger("success")},emitStopAttemptsByError:i=>{this.events.trigger("stop-attempts-by-error",i)},emitCancelledAttempts:i=>{this.events.trigger("cancelled-attempts",i)},emitFailedAllAttempts:i=>{this.events.trigger("failed-all-attempts",i)},emitTelephonyCheckFailure:i=>{this.events.trigger("telephony-check-failure",i)},emitTelephonyCheckEscalated:i=>{this.events.trigger("telephony-check-escalated",i)},emitStatusChange:({isInProgress:i})=>{this.events.trigger("changed-attempt-status",{isInProgress:i})}},reconnectActions:{requestReconnect:this.requestReconnect,notifyTelephonyStillConnected:()=>{this.stateMachine.toTelephonyResultStillConnected()}}}),this.stateMachine=ft(Rs({runtime:this.runtime,canRetryOnError:r?.canRetryOnError??Os}))}start(e){Y("auto connector start"),this.requestReconnect(e,Ms)}restart(){Y("auto connector restart");const{parameters:e}=this.stateMachine.context;if(!e){Y("auto connector restart skipped: no parameters in context");return}this.requestReconnect(e,_s)}stop(){Y("auto connector stop"),this.resetReconnectCoalescingState(),this.stateMachine.toStop()}cancelPendingRetry(){this.runtime.cancelPendingRetry()}requestReconnect=(e,n)=>{const s=this.shouldRequestReconnect(n);Y("auto connector requestReconnect",{isAvailableToRestart:s,reason:n}),s&&this.stateMachine.toRestart(e)};shouldRequestReconnect(e){const n=this.reconnectCoalescer.register(e);return n.shouldRequest?(Y(`auto connector reconnect requested: ${e}`,{state:String(this.stateMachine.state),generation:n.generation}),!0):(Y(`auto connector reconnect coalesced: ${e}`,{state:String(this.stateMachine.state),coalescedBy:n.coalescedBy,currentPriority:n.currentPriority,coalescedByPriority:n.coalescedByPriority}),!1)}resetReconnectCoalescingState(){this.reconnectCoalescer.reset()}}const ys="incomingCall",bs="declinedIncomingCall",Ds="failedIncomingCall",Ls="terminatedIncomingCall",Mt="connecting",ws="connected",Gs="disconnected",ks="newRTCSession",Us="registered",Fs="unregistered",Bs="registrationFailed",$s="newMessage",xs="sipEvent",qs="availableSecondRemoteStream",Vs="notAvailableSecondRemoteStream",Hs="mustStopPresentation",Ws="enterRoom",Qs="useLicense",Ys="peerconnection:confirmed",js="peerconnection:ontrack",zs="channels",Js="channels:notify",Ks="ended:fromserver",Xs="main-cam-control",Zs="admin:stop-main-cam",er="admin:start-main-cam",tr="admin:stop-mic",nr="admin:start-mic",sr="admin:force-sync-media-state",rr="participant:added-to-list-moderators",ir="participant:removed-from-list-moderators",ar="participant:move-request-to-stream",or="participant:move-request-to-spectators",cr="participant:move-request-to-participants",dr="participation:accepting-word-request",lr="participation:cancelling-word-request",hr="webcast:started",ur="webcast:stopped",Er="account:changed",gr="account:deleted",Tr="conference:participant-token-issued",mr="ended",Sr="sending",Cr="reinvite",pr="replaces",Rr="refer",Nr="progress",Ir="accepted",Ar="confirmed",vr="peerconnection",fr="failed",Or="muted",Mr="unmuted",_r="newDTMF",Pr="newInfo",yr="hold",br="unhold",Dr="update",Lr="sdp",wr="icecandidate",Gr="getusermediafailed",kr="peerconnection:createofferfailed",Ur="peerconnection:createanswerfailed",Fr="peerconnection:setlocaldescriptionfailed",Br="peerconnection:setremotedescriptionfailed",$r="presentation:start",xr="presentation:started",qr="presentation:end",Vr="presentation:ended",Hr="presentation:failed",Wr=[ys,bs,Ls,Ds,dr,lr,ar,Js,Tr,Er,gr,hr,ur,rr,ir],_t=[Mt,ws,Gs,ks,Us,Fs,Bs,$s,xs],Qr=[qs,Vs,Hs,Ws,Qs,Ys,js,zs,Ks,Xs,er,Zs,tr,nr,sr,or,cr],be=[mr,Mt,Sr,Cr,pr,Rr,Nr,Ir,Ar,vr,fr,Or,Mr,_r,Pr,yr,br,Dr,Lr,wr,Gr,kr,Ur,Fr,Br,$r,xr,qr,Vr,Hr];[..._t,...Wr];[...be,...Qr];const Yr=v("BaseSession.mock");class jr{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};addTransceiver=jest.fn(async(e,n,s)=>({}));constructor({originator:e="local",eventHandlers:n,remoteIdentity:s}){this.originator=e,this.events=new _.Events(be),this.initEvents(n),this.remote_identity=s}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,n,s){throw new Error("Method not implemented.")}hold(e,n){throw new Error("Method not implemented.")}unhold(e,n){throw new Error("Method not implemented.")}async renegotiate(e,n){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,n){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,n){throw new Error("Method not implemented.")}addListener(e,n){throw new Error("Method not implemented.")}once(e,n){throw new Error("Method not implemented.")}removeListener(e,n){throw new Error("Method not implemented.")}off(e,n){return this.events.off(e,n),this}removeAllListeners(e){return Yr("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...n){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,n){throw new Error("Method not implemented.")}prependOnceListener(e,n){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([n,s])=>{this.on(n,s)})}on=(e,n)=>(be.includes(e)&&this.events.on(e,n),this);trigger(e,n){this.events.trigger(e,n)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class Ze{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:n}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(n)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class et{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}class zr extends EventTarget{senders=[];receivers=[];canTrickleIceCandidates;connectionState="new";currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState="stable";close=jest.fn();setLocalDescription=jest.fn(async e=>{this.signalingState=e.type==="rollback"?"stable":"have-local-offer",this.dispatchEvent(new Event("signalingstatechange"))});setRemoteDescription=jest.fn(async e=>{this.signalingState="stable",this.connectionState="connected",this.dispatchEvent(new Event("signalingstatechange")),this.dispatchEvent(new Event("connectionstatechange"))});addTransceiver=jest.fn((e,n)=>({}));createOffer=jest.fn(async(e,n,s)=>({type:"offer",sdp:"offer-sdp"}));constructor(e,n){super(),this.receivers=n?.map(s=>({track:s}))??[]}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,n){throw new Error("Method not implemented.")}createDataChannel(e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...n)=>{const s=new Ze({track:e}),r=new et(s);return r.mid=e.kind==="audio"?"0":"1",this.senders.push(s),this.dispatchTrackInternal(e,...n),s};addTrackWithMid=(e,n)=>{const s=new Ze({track:e}),r=new et(s);return n===void 0?r.mid=e.kind==="audio"?"0":"1":r.mid=n,this.senders.push(s),this.dispatchTrackInternal(e),s};dispatchTrack(e){this.dispatchTrackInternal(new ye.MediaStreamTrackMock(e))}dispatchTrackInternal(e,...n){const s=new Event("track");Object.defineProperty(s,"track",{value:e}),Object.defineProperty(s,"streams",{value:n.length===0?[new MediaStream([e])]:n}),this.dispatchEvent(s)}}function Jr(t){const e=t.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}var Pt=(t=>(t.LOCAL="local",t.REMOTE="remote",t.SYSTEM="system",t))(Pt||{});const yt=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","hold","unhold","muted","unmuted","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],Kr=["start-call","end-call","peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed","remote-tracks-changed","remote-streams-changed","recv-session-started","recv-session-ended","recv-quality-changed"],bt=[...yt,...Kr],Dt=()=>new _.TypedEvents(bt),tt=400,Lt="777",Xr=t=>t.getVideoTracks().length>0;class F extends jr{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;renegotiate=jest.fn(async()=>!0);answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},tt)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:n,remoteIdentity:s=new j.NameAddrHeader(new j.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:r=0}){super({originator:n,eventHandlers:e,remoteIdentity:s}),this.delayStartPresentation=r}static get C(){return j.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(F.countStartsPresentation+=1,new Promise((n,s)=>{this.timeoutStartPresentation=setTimeout(()=>{if(F.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),s(F.presentationError);return}if(F.startPresentationError&&F.countStartsPresentation<F.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),s(F.startPresentationError);return}n(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(F.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),F.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=ye.createAudioMediaStreamTrackMock();n.id="mainaudio1";const s=[n];if(Xr(e)){const i=ye.createVideoMediaStreamTrackMock();i.id="mainvideo1",s.push(i)}this.connection=new zr(void 0,s),this.trigger("peerconnection",{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:n}={}){const s=Jr(e);return this.initPeerconnection(n),this.timeoutConnect=setTimeout(()=>{e.includes(Lt)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:Pt.REMOTE,request:{getHeader:r=>r==="content-type"?"application/vinteo.webrtc.roomname":r==="x-webrtc-enter-room"?s:r==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},tt),this.connection}terminate({status_code:e,cause:n}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:n,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:n}={}){this.terminate({status_code:e,cause:n})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,n="getTracks"){e[n]().forEach(s=>this.connection.addTrack(s,e))}forEachSenders(e){const n=this.connection.getSenders();for(const s of n)e(s);return n}toggleMuteAudio(e){this.forEachSenders(({track:n})=>{n?.kind==="audio"&&(n.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:n})=>{n?.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}const Zr=(t,e)=>{const n=e.major===t.major,s=e.minor===t.minor,r=e.major>t.major,i=n&&e.minor>t.minor,a=n&&s&&e.patch>t.patch;return r||i||a},ei=t=>t.major!==void 0&&t.minor!==void 0&&t.patch!==void 0,ti=t=>e=>ei(t)&&Zr(t,e),ni=(t="")=>{const e=t.split(".");if(e.length<=1)return{major:void 0,minor:void 0,patch:void 0};const[n,s,r]=e.map(i=>Number.parseInt(i,10));return{major:n,minor:s,patch:r}},si=()=>globalThis.process?.versions?.electron!==void 0,Fe=()=>{const t=new Cn.UAParser,{name:e,version:n}=t.getBrowser(),{name:s}=t.getOS(),{type:r}=t.getDevice(),i=si(),a=r==="mobile",o=ni(n);return{hasGreaterThanBrowserVersion:ti(o),isMobileDevice:a,isChrome:e==="Chrome"||i,isYandexBrowser:e==="Yandex",isSafari:e==="Safari",isOpera:e==="Opera",isWindows:s==="Windows"}},ri=v("stringifyMessage"),ii=t=>{let e="";try{e=JSON.stringify(t)}catch(n){ri("failed to stringify message",n)}return e},ai=/^p2p.+to.+$/i,Ce=t=>t!==void 0&&t.length>0&&ai.test(t),wt="purgatory",he=t=>t===wt,oi=(t,e)=>{t.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},de=(t,{directionVideo:e,directionAudio:n,contentHint:s}={})=>{if(!t||e==="recvonly"&&n==="recvonly")return;const r=n==="recvonly"?[]:t.getAudioTracks(),i=e==="recvonly"?[]:t.getVideoTracks(),a=[...r,...i],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&oi(o,s),o},ci="api/v2/rtp2webrtc/offer",Gt=async({serverUrl:t,conferenceNumber:e,quality:n,audio:s,offer:r,token:i})=>{const a=new URL(`https://${t.replace(/\/$/,"")}/${ci}/${encodeURIComponent(e)}`);a.searchParams.set("quality",n),a.searchParams.set("audio",String(s));const o={"Content-Type":"application/json",Authorization:`Bearer ${i}`},c=await fetch(a.toString(),{method:"POST",headers:o,credentials:"same-origin",body:JSON.stringify(r)});if(!c.ok)throw new Error(`sendOffer failed with status ${c.status}`);const E=await c.json();return{type:E.type,sdp:E.sdp,toJSON(){return E}}},di=(t,e)=>(t.degradationPreference=e.degradationPreference,t),li=(t,e)=>{t.encodings??=[];for(let n=t.encodings.length;n<e;n+=1)t.encodings.push({});return t},kt=t=>(e,n)=>n!==void 0&&e!==n||n===void 0&&e!==t,hi=kt(),ui=(t,e)=>{if(hi(t,e))return t},Ei=(t,e,{isResetAllowed:n=!1}={})=>{const s=t.maxBitrate,r=ui(e,s);return(r!==void 0||n)&&(t.maxBitrate=r??e),t},Ut=1,gi=kt(Ut),Ti=(t,e)=>{const n=t===void 0?void 0:Math.max(t,Ut);if(n!==void 0&&gi(n,e))return n},mi=(t,e)=>{const n=t.scaleResolutionDownBy,s=Ti(e,n);return s!==void 0&&(t.scaleResolutionDownBy=s),t},Si=(t,e,{isResetAllowed:n}={})=>{const s=e.encodings?.length??0;return li(t,s),t.encodings.forEach((r,i)=>{const a=(e?.encodings??[])[i],o=a?.maxBitrate,c=a?.scaleResolutionDownBy;Ei(r,o,{isResetAllowed:n}),mi(r,c)}),t},Ci=(t,e)=>{if(t.codecs?.length!==e.codecs?.length)return!0;for(let n=0;n<(t.codecs?.length??0);n++)if(JSON.stringify(t.codecs[n])!==JSON.stringify(e.codecs[n]))return!0;if(t.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let n=0;n<(t.headerExtensions?.length??0);n++)if(JSON.stringify(t.headerExtensions[n])!==JSON.stringify(e.headerExtensions[n]))return!0;if(t.encodings?.length!==e.encodings?.length)return!0;for(let n=0;n<(t.encodings?.length??0);n++)if(JSON.stringify(t.encodings[n])!==JSON.stringify(e.encodings[n]))return!0;return t.rtcp?.cname!==e.rtcp?.cname||t.rtcp?.reducedSize!==e.rtcp?.reducedSize||t.degradationPreference!==e.degradationPreference},pe=async(t,e,{isResetAllowed:n}={})=>{const s=t.getParameters(),r=JSON.parse(JSON.stringify(s));Si(s,e,{isResetAllowed:n}),di(s,e);const i=Ci(r,s);return i&&await t.setParameters(s),{parameters:s,isChanged:i}},Be=async(t,e,n)=>{const{isChanged:s,parameters:r}=await pe(t,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&n&&n(r),{isChanged:s,parameters:r}},pi=(t,e)=>t.find(n=>n.track!==null&&e.getTracks().includes(n.track)),Ri=async(t,e,n)=>{const s=pi(t,e);if(s)return Be(s,{maxBitrate:n})},Ni=v("resolveOnStartMainCam"),Ii=t=>n=>(Ni("onStartMainCam"),t.on("api:admin:start-main-cam",n)),Ai=v("resolveOnStartMic"),vi=t=>n=>(Ai("onStartMic"),t.on("api:admin:start-mic",n)),fi=v("resolveOnStopMainCam"),Oi=t=>n=>(fi("onStopMainCam"),t.on("api:admin:stop-main-cam",n)),Mi=v("resolveOnStopMic"),_i=t=>n=>(Mi("onStopMic"),t.on("api:admin:stop-mic",n));class Ft{command=void 0;unsubscribe;options;constructor(e){this.options=e}set(e){this.cancel(),this.command=e,this.unsubscribe=this.options.subscribe(n=>{this.options.isReady(n)?(this.command!==void 0&&this.options.onExecute(this.command),this.cancel()):this.options.isCancelled(n)&&this.cancel()})}cancel(){this.unsubscribe?.(),this.unsubscribe=void 0,this.command=void 0}}const f="evaluate";var u=(t=>(t.IDLE="call:idle",t.CONNECTING="call:connecting",t.PRESENTATION_CALL="call:presentationCall",t.ROOM_PENDING_AUTH="call:roomPendingAuth",t.PURGATORY="call:purgatory",t.P2P_ROOM="call:p2pRoom",t.DIRECT_P2P_ROOM="call:directP2pRoom",t.IN_ROOM="call:inRoom",t.DISCONNECTING="call:disconnecting",t))(u||{});const Bt={raw:{},state:{}},$t=t=>"number"in t&&$(t.number)&&Tt(t.answer),xt=t=>"room"in t&&$(t.room)&&$(t.participantName),Pi=t=>"token"in t&&$(t.token),qt=t=>Pi(t)&&"conferenceForToken"in t&&$(t.conferenceForToken),oe=t=>$t(t)&&xt(t),Vt=t=>!qt(t)||!xt(t)?!1:t.conferenceForToken===t.room,Ht=({isDirectPeerToPeer:t})=>t===!0,ve=t=>"isDirectPeerToPeer"in t&&Ht(t),yi="x-vinteo-presentation-call: yes",bi=t=>_n(t)&&t.some(e=>e.trim().toLowerCase()===yi),Di=t=>"extraHeaders"in t&&bi(t.extraHeaders)&&"isConfirmed"in t&&t.isConfirmed===!0,Ee=t=>oe(t)&&!he(t.room)&&qt(t)&&Vt(t),ie=t=>{const e=t;return{number:e.number,answer:e.answer,room:e.room,participantName:e.participantName}},w={[u.IDLE]:{guard:()=>!0,buildContext:()=>({})},[u.CONNECTING]:{guard:$t,buildContext:t=>{const{number:e,answer:n,extraHeaders:s}=t;return{number:e,answer:n,extraHeaders:s}}},[u.PRESENTATION_CALL]:{guard:Di,buildContext:t=>{const{number:e,answer:n}=t;return{number:e,answer:n}}},[u.ROOM_PENDING_AUTH]:{guard:t=>oe(t)&&!he(t.room)&&!Ce(t.room)&&!ve(t)&&!Vt(t),buildContext:ie},[u.PURGATORY]:{guard:t=>oe(t)&&he(t.room)&&!Ee(t),buildContext:ie},[u.P2P_ROOM]:{guard:t=>oe(t)&&Ce(t.room)&&!ve(t)&&!Ee(t),buildContext:ie},[u.DIRECT_P2P_ROOM]:{guard:t=>oe(t)&&ve(t)&&!Ee(t),buildContext:t=>({...ie(t),isDirectPeerToPeer:!0})},[u.IN_ROOM]:{guard:Ee,buildContext:t=>{const{token:e,conferenceForToken:n}=t;return{...ie(t),token:e,conferenceForToken:n}}},[u.DISCONNECTING]:{guard:t=>t.pendingDisconnect===!0,buildContext:()=>({})}},Li=t=>he(t.room)||Ce(t.room)||Ht(t),fe=()=>({}),wi=()=>N.setup({types:{context:Bt,events:{}},actions:{setConnecting:N.assign(({event:t,context:e})=>t.type!=="CALL.CONNECTING"?e:{raw:{...fe(),number:t.number,answer:t.answer,extraHeaders:t.extraHeaders}}),setRoomInfo:N.assign(({event:t,context:e})=>{if(t.type!=="CALL.ENTER_ROOM")return e;const n={room:t.room,participantName:t.participantName};return $(t.token)?(n.token=t.token,n.conferenceForToken=t.room):Li(t)&&(n.token=void 0,n.conferenceForToken=void 0),Tt(t.isDirectPeerToPeer)&&(n.isDirectPeerToPeer=t.isDirectPeerToPeer),{raw:{...e.raw,...n}}}),setTokenInfo:N.assign(({event:t,context:e})=>t.type!=="CALL.TOKEN_ISSUED"?e:{raw:{...e.raw,token:t.token,conferenceForToken:t.conferenceForToken,participantName:t.participantName}}),setConfirmed:N.assign(({event:t,context:e})=>t.type!=="CALL.PRESENTATION_CALL"?e:{raw:{...e.raw,isConfirmed:!0}}),reset:N.assign(()=>({raw:fe()})),prepareDisconnect:N.assign(()=>({raw:{...fe(),pendingDisconnect:!0}}))}}),Gi=()=>wi().createMachine({id:"call",initial:u.IDLE,context:Bt,states:{[u.IDLE]:{entry:N.assign(()=>({state:w[u.IDLE].buildContext()})),on:{"CALL.CONNECTING":{target:f,actions:"setConnecting"}}},[u.CONNECTING]:{entry:N.assign(({context:t})=>({state:w[u.CONNECTING].buildContext(t.raw)})),on:{"CALL.PRESENTATION_CALL":{target:f,actions:"setConfirmed"},"CALL.ENTER_ROOM":{target:f,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:f,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[u.ROOM_PENDING_AUTH]:{entry:N.assign(({context:t})=>({state:w[u.ROOM_PENDING_AUTH].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:f,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:f,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[u.IN_ROOM]:{entry:N.assign(t=>({state:w[u.IN_ROOM].buildContext(t.context.raw)})),on:{"CALL.ENTER_ROOM":{target:f,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:f,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[f]:{always:[{target:u.DISCONNECTING,guard:({context:t})=>w[u.DISCONNECTING].guard(t.raw)},{target:u.PRESENTATION_CALL,guard:({context:t})=>w[u.PRESENTATION_CALL].guard(t.raw)},{target:u.IN_ROOM,guard:({context:t})=>w[u.IN_ROOM].guard(t.raw)},{target:u.DIRECT_P2P_ROOM,guard:({context:t})=>w[u.DIRECT_P2P_ROOM].guard(t.raw)},{target:u.P2P_ROOM,guard:({context:t})=>w[u.P2P_ROOM].guard(t.raw)},{target:u.PURGATORY,guard:({context:t})=>w[u.PURGATORY].guard(t.raw)},{target:u.ROOM_PENDING_AUTH,guard:({context:t})=>w[u.ROOM_PENDING_AUTH].guard(t.raw)},{target:u.CONNECTING,guard:({context:t})=>w[u.CONNECTING].guard(t.raw)},{target:u.IDLE}]},[u.PURGATORY]:{entry:N.assign(({context:t})=>({state:w[u.PURGATORY].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:f,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:f,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[u.P2P_ROOM]:{entry:N.assign(({context:t})=>({state:w[u.P2P_ROOM].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:f,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:f,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[u.PRESENTATION_CALL]:{entry:N.assign(({context:t})=>({state:w[u.PRESENTATION_CALL].buildContext(t.raw)})),on:{"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[u.DIRECT_P2P_ROOM]:{entry:N.assign(({context:t})=>({state:w[u.DIRECT_P2P_ROOM].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:f,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:f,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:f,actions:"prepareDisconnect"},"CALL.RESET":{target:f,actions:"reset"}}},[u.DISCONNECTING]:{entry:N.assign(()=>({state:w[u.DISCONNECTING].buildContext()})),on:{"CALL.RESET":{target:f,actions:"reset"}}}}});function ki(t){return t!==f}const Ui=v("CallStateMachine");class Fi extends te{constructor(e,n){super(e),this.subscribeToEvents(n)}get isIdle(){return this.state===u.IDLE}get isConnecting(){return this.state===u.CONNECTING}get isPresentationCall(){return this.state===u.PRESENTATION_CALL}get isRoomPendingAuth(){return this.state===u.ROOM_PENDING_AUTH}get isInPurgatory(){return this.state===u.PURGATORY}get isP2PRoom(){return this.state===u.P2P_ROOM}get isDirectP2PRoom(){return this.state===u.DIRECT_P2P_ROOM}get isInRoom(){return this.state===u.IN_ROOM}get isDisconnecting(){return this.state===u.DISCONNECTING}get idleContext(){if(this.state===u.IDLE)return this.context.state}get connectingContext(){if(this.state===u.CONNECTING)return this.context.state}get roomPendingAuthContext(){if(this.state===u.ROOM_PENDING_AUTH)return this.context.state}get purgatoryContext(){if(this.state===u.PURGATORY)return this.context.state}get p2pRoomContext(){if(this.state===u.P2P_ROOM)return this.context.state}get directP2pRoomContext(){if(this.state===u.DIRECT_P2P_ROOM)return this.context.state}get inRoomContext(){if(this.state===u.IN_ROOM)return this.context.state}get disconnectingContext(){if(this.state===u.DISCONNECTING)return this.context.state}get isActive(){return this.isInRoom||this.isPresentationCall||this.isRoomPendingAuth||this.isInPurgatory||this.isP2PRoom||this.isDirectP2PRoom}get number(){const{raw:e}=this.context;if("number"in e)return e.number}get token(){return this.inRoomContext?.token}get isCallInitiator(){return!this.isCallAnswerer}get isCallAnswerer(){return this.connectingContext?.answer??!1}getInRoomCredentials(){const e=this.inRoomContext;if(e!==void 0)return{token:e.token,conferenceForToken:e.conferenceForToken}}onInRoomCredentialsChange(e){let n;const s=this.subscribe(r=>{if(r.value===u.IN_ROOM){const i=r.context.state,a={token:i.token,conferenceForToken:i.conferenceForToken},o=n?.token,c=n?.conferenceForToken;(o!==a.token||c!==a.conferenceForToken)&&(n=a,e(a));return}ki(r.value)&&(n=void 0)});return()=>{s.unsubscribe()}}reset(){this.send({type:"CALL.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){Ui(`[CallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on("enter-room",({room:n,participantName:s,bearerToken:r,isDirectPeerToPeer:i})=>{this.send({room:n,participantName:s,isDirectPeerToPeer:i,type:"CALL.ENTER_ROOM",token:r})})),this.addSubscription(e.on("conference:participant-token-issued",({jwt:n,conference:s,participant:r})=>{this.send({token:n,type:"CALL.TOKEN_ISSUED",conferenceForToken:s,participantName:r})}))}subscribeToEvents(e){this.addSubscription(e.on("start-call",({number:n,answer:s,extraHeaders:r})=>{this.send({type:"CALL.CONNECTING",number:n,answer:s,extraHeaders:r})})),this.addSubscription(e.on("confirmed",()=>{this.send({type:"CALL.PRESENTATION_CALL"})})),this.addSubscription(e.on("end-call",()=>{this.send({type:"CALL.START_DISCONNECT"})})),this.addSubscription(e.on("ended",()=>{this.send({type:"CALL.RESET"})})),this.addSubscription(e.on("failed",()=>{this.send({type:"CALL.RESET"})}))}}const Wt=t=>new Fi(Gi(),t),Bi=t=>[...t.keys()].map(e=>t.get(e)),$i=(t,e)=>Bi(t).find(n=>n?.type===e),$e=async t=>t.getStats().then(e=>$i(e,"codec")?.mimeType);class xi{async getCodecFromSender(e){return await $e(e)??""}}const qi=v("TaskQueue");class Vi{stackPromises=Ie.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{qi("TaskQueue: error",e)})}}class Hi{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Vi}async setEncodingsToSender(e,n){return this.taskQueue.add(async()=>Be(e,n,this.onSetParameters))}stop(){this.taskQueue.stop()}}const De=(t,e)=>t!==void 0&&e!==void 0&&t.toLowerCase().includes(e.toLowerCase()),Wi=1e6,V=t=>t*Wi,Qt=V(.06),Yt=V(4),Qi=t=>t<=64?Qt:t<=128?V(.12):t<=256?V(.25):t<=384?V(.32):t<=426?V(.38):t<=640?V(.5):t<=848?V(.7):t<=1280?V(1):t<=1920?V(2):Yt,Yi="av1",ji=t=>De(t,Yi),zi=.6,xe=(t,e)=>ji(e)?t*zi:t,jt=t=>xe(Qt,t),zt=t=>xe(Yt,t),nt=(t,e)=>{const n=Qi(t);return xe(n,e)},Oe=1,Ji=({videoTrack:t,targetSize:e})=>{const n=t.getSettings(),s=n.width,r=n.height,i=s===void 0?Oe:s/e.width,a=r===void 0?Oe:r/e.height;return Math.max(i,a,Oe)};class Ki{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:n,parametersSetter:s},r){this.senderFinder=e,this.codecProvider=n,this.parametersSetter=s,this.ignoreForCodec=r.ignoreForCodec}async balance(e,n){const s=e.getSenders(),r=this.senderFinder.findVideoSender(s);if(!r?.track)return{...this.resultNoChanged,sender:r};const i=await this.codecProvider.getCodecFromSender(r);if(De(i,this.ignoreForCodec))return{...this.resultNoChanged,sender:r};const{mainCam:a,resolutionMainCam:o}=n??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:r,codec:i,videoTrack:r.track}).then(c=>({...c,sender:r}))}async reset(e){const n=e.getSenders(),s=this.senderFinder.findVideoSender(n);if(!s?.track)return{...this.resultNoChanged,sender:s};const r=await this.codecProvider.getCodecFromSender(s);if(De(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:s};const i={sender:s,codec:r,videoTrack:s.track};return{...await this.setBitrateByTrackResolution(i),sender:s}}async processSender(e,n){const{mainCam:s,resolutionMainCam:r}=e;switch(s){case B.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(n);case B.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(n);case B.MAX_MAIN_CAM_RESOLUTION:return r!==void 0?this.setResolutionSender(r,n):this.setBitrateByTrackResolution(n);case B.ADMIN_STOP_MAIN_CAM:case B.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(n);default:return this.setBitrateByTrackResolution(n)}}async downgradeResolutionSender(e){const{sender:n,codec:s}=e,r={scaleResolutionDownBy:200,maxBitrate:jt(s)};return this.parametersSetter.setEncodingsToSender(n,r)}async setBitrateByTrackResolution(e){const{sender:n,videoTrack:s,codec:r}=e,a=s.getSettings().width,o=a===void 0?zt(r):nt(a,r);return this.parametersSetter.setEncodingsToSender(n,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,n){const[s,r]=e.split("x"),{sender:i,videoTrack:a,codec:o}=n,c={width:Number(s),height:Number(r)},E=Ji({videoTrack:a,targetSize:c}),p=nt(c.width,o),A={scaleResolutionDownBy:E,maxBitrate:p};return this.parametersSetter.setEncodingsToSender(i,A)}}const Xi=t=>t.find(e=>e.track?.kind==="video");class Zi{findVideoSender(e){return Xi(e)}}class ea{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:n}){this.pollIntervalMs=e,this.maxPollIntervalMs=n??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new ee.SetTimeoutRequest}subscribe(e,n){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,n))}unsubscribe(){this.detachSender()}attachSender(e,n){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async r=>{await s(r),this.attachTrack(n,r??void 0),n()},this.attachTrack(n,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,n){if(this.detachTrack(),!n)return;const{width:s,height:r}=n.getSettings();this.lastWidth=s,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(n,e)}schedulePoll(e,n){const s=()=>{const{width:r,height:i}=e.getSettings();r!==this.lastWidth||i!==this.lastHeight?(this.lastWidth=r,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,n()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class ta{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}const Me=v("VideoSendingBalancer");class na{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,n,{ignoreForCodec:s,onSetParameters:r,pollIntervalMs:i}={}){this.getConnection=n,this.eventHandler=new ta(e),this.parametersSetterWithQueue=new Hi(r),this.senderBalancer=new Ki({senderFinder:new Zi,codecProvider:new xi,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new ea({pollIntervalMs:i})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.reset()}reset(){this.clearState();const e=this.getConnection();e?this.senderBalancer.reset(e).catch(n=>{Me("reset sender encodings: error",n)}).finally(()=>{this.parametersSetterWithQueue.stop()}):this.parametersSetterWithQueue.stop()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const n=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(n.sender,()=>{this.balance().catch(s=>{Me("balance on track change: error",s)})}),n}clearState(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(n=>{Me("handleMainCamControl: error",n)})}}const sa=6e3,ra=52e4,ge=(t,e)=>t.getSenders().filter(n=>n.track?.kind===e),ia=(t,e)=>t==="audio"?sa:jt(e),aa=t=>t.track!==null;class oa{previousBitrates=new Map;async setMinBitrateForSenders(e,n="all"){const s=[];if(!e)return;(n==="audio"||n==="all")&&s.push(...ge(e,"audio")),(n==="video"||n==="all")&&s.push(...ge(e,"video"));const r=s.filter(aa).map(async i=>{const a=i.getParameters();this.saveCurrentBitrate(i,a);const o={...a,encodings:a.encodings.map(c=>({...c,maxBitrate:ia(i.track.kind)}))};await pe(i,o)});await Promise.all(r)}async restoreBitrateForSenders(e,n="all"){const s=[];if(!e)return;(n==="audio"||n==="all")&&s.push(...ge(e,"audio")),(n==="video"||n==="all")&&s.push(...ge(e,"video"));const r=s.map(async i=>{const a=this.getSavedBitrate(i);if(a){const o=i.getParameters(),c=i.track?.kind==="video",E=c?await $e(i):void 0,p={...o,encodings:a.map(A=>{const b=c?zt(E):ra;return{...A,maxBitrate:A.maxBitrate??b}})};await pe(i,p,{isResetAllowed:!0}),this.clearSavedBitrate(i)}});await Promise.all(r)}getSavedBitrate(e){return this.previousBitrates.get(e)}clearSavedBitrate(e){this.previousBitrates.delete(e)}clearAll(){this.previousBitrates.clear()}hasSavedBitrate(e){return this.previousBitrates.has(e)}getSavedCount(){return this.previousBitrates.size}saveCurrentBitrate(e,n){const s=n.encodings.map(r=>({...r}));this.previousBitrates.set(e,s)}}var qe=(t=>(t.BYE="Terminated",t.WEBRTC_ERROR="WebRTC Error",t.CANCELED="Canceled",t.REQUEST_TIMEOUT="Request Timeout",t.REJECTED="Rejected",t.REDIRECTED="Redirected",t.UNAVAILABLE="Unavailable",t.NOT_FOUND="Not Found",t.ADDRESS_INCOMPLETE="Address Incomplete",t.INCOMPATIBLE_SDP="Incompatible SDP",t.BAD_MEDIA_DESCRIPTION="Bad Media Description",t))(qe||{});const st=v("MCUSession");class ca{events;rtcSession;disposers=new Set;onReset;pcConfig;bitrateStateManager=new oa;constructor(e,{onReset:n}){this.events=e,this.onReset=n,e.on("failed",this.handleEnded),e.on("ended",this.handleEnded)}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}getEstablishedRTCSession=()=>this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0;getPcConfig(){return this.pcConfig}async renegotiate(){if(this.rtcSession===void 0)throw new Error("No rtcSession established");return this.rtcSession.renegotiate()}startCall=async(e,n,{number:s,mediaStream:r,extraHeaders:i=[],iceServers:a,directionVideo:o,directionAudio:c,contentHint:E,offerToReceiveAudio:p=!0,offerToReceiveVideo:A=!0,degradationPreference:b,sendEncodings:M,onAddedTransceiver:H})=>new Promise((G,z)=>{this.handleCall().then(G).catch(ne=>{z(ne)}),this.pcConfig={iceServers:a},this.rtcSession=e.call(n(s),{mediaStream:de(r,{directionVideo:o,directionAudio:c,contentHint:E}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:p,offerToReceiveVideo:A},eventHandlers:this.events.triggers,extraHeaders:i,directionVideo:o,directionAudio:c,degradationPreference:b,sendEncodings:M,onAddedTransceiver:H})});async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:qe.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:n,extraHeaders:s=[],iceServers:r,directionVideo:i,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:c,contentHint:E,degradationPreference:p,sendEncodings:A,onAddedTransceiver:b})=>new Promise((M,H)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(M).catch(G=>{H(G)}),this.pcConfig={iceServers:r},e.answer({pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:c},mediaStream:de(n,{directionVideo:i,directionAudio:a,contentHint:E}),extraHeaders:s,directionVideo:i,directionAudio:a,degradationPreference:p,sendEncodings:A,onAddedTransceiver:b})}catch(G){H(G)}});async replaceMediaStream(e,n){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=n??{},r=de(e,{contentHint:s});if(r===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(r,n)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}setMinBitrateForSenders(e="all"){this.bitrateStateManager.setMinBitrateForSenders(this.connection,e).catch(n=>{st("setMinBitrateForSenders",n)})}restoreBitrateForSenders(e="all"){this.bitrateStateManager.restoreBitrateForSenders(this.connection,e).catch(n=>{st("restoreBitrateForSenders",n)})}handleCall=async()=>new Promise((e,n)=>{const s=()=>{this.events.on("peerconnection",E),this.events.on("confirmed",p)},r=()=>{this.events.off("peerconnection",E),this.events.off("confirmed",p)},i=()=>{this.events.on("failed",o),this.events.on("ended",o)},a=()=>{this.events.off("failed",o),this.events.off("ended",o)},o=A=>{r(),a(),n(A)};let c;const E=({peerconnection:A})=>{c=A;const b=M=>{this.events.trigger("peerconnection:ontrack",M)};A.addEventListener("track",b),this.disposers.add(()=>{A.removeEventListener("track",b)})},p=()=>{c!==void 0&&this.events.trigger("peerconnection:confirmed",c),r(),a(),e(c)};s(),i()});subscribeToSessionEvents(e){this.events.eachTriggers((n,s)=>{const r=yt.find(i=>i===s);r&&(e.on(r,n),this.disposers.add(()=>{e.off(r,n)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:n}=e;n==="remote"&&this.events.trigger("ended:fromserver",e),this.reset()};reset=()=>{delete this.rtcSession,delete this.pcConfig,this.unsubscribeFromSessionEvents(),this.bitrateStateManager.clearAll(),this.onReset()}}const Le=t=>t==="auto"?"high":t,da=10,la=500,ha=5e3;class ua{cancelableSendOfferWithRepeatedCalls;currentRenegotiation;config;tools;connection;lastCallParams;constructor(e,n){const s=e.quality??"auto";this.config={...e,quality:s,effectiveQuality:Le(s)},this.tools=n,this.connection=new RTCPeerConnection(e.pcConfig),this.addTransceivers()}get settings(){return this.config}get peerConnection(){return this.connection}getAudioChannel(){return this.config.audioChannel}getQuality(){return this.config.quality}getEffectiveQuality(){return this.config.effectiveQuality}async setQuality(e){if(!this.lastCallParams)return!1;const n=this.config.effectiveQuality,s=this.config.quality,r=Le(e);return e===s&&r===n?!1:(this.config.quality=e,this.config.effectiveQuality=r,r!==n&&await this.renegotiate(this.lastCallParams),!0)}async applyQuality(e){const n=await this.setQuality(e),s=this.getEffectiveQuality();return{applied:n,effectiveQuality:s}}close(){this.cancelSendOfferWithRepeatedCalls(),this.connection.close()}async call({conferenceNumber:e,token:n}){const s=this.waitForTracks(),r=await this.renegotiate({conferenceNumber:e,token:n});return await s,r}async renegotiate({conferenceNumber:e,token:n}){this.lastCallParams={conferenceNumber:e,token:n},this.cancelSendOfferWithRepeatedCalls();const s=this.currentRenegotiation;s&&await s.catch(()=>{});const r=this.performRenegotiate({conferenceNumber:e,token:n});this.currentRenegotiation=r;try{return await r}finally{this.currentRenegotiation===r&&(this.currentRenegotiation=void 0)}}async performRenegotiate({conferenceNumber:e,token:n}){this.hasHaveLocalOfferSignalingState()&&await this.connection.setLocalDescription({type:"rollback"}),await this.waitForPeerConnectionReady();const s=await this.createOffer(),r=async()=>this.tools.sendOffer({conferenceNumber:e,token:n,quality:this.config.effectiveQuality,audioChannel:this.config.audioChannel},s),i=o=>!(o instanceof Error);this.cancelableSendOfferWithRepeatedCalls=Ne.repeatedCallsAsync({targetFunction:r,isComplete:i,callLimit:da,delay:la,isRejectAsValid:!0,isCheckBeforeCall:!1});const a=await this.cancelableSendOfferWithRepeatedCalls.then(o=>o).finally(()=>{this.cancelableSendOfferWithRepeatedCalls=void 0});return await this.setRemoteDescription(a),await this.waitForPeerConnectionReady(),!0}async createOffer(){const e=await this.connection.createOffer();return await this.connection.setLocalDescription(e),e}async setRemoteDescription(e){return this.connection.setRemoteDescription(e)}hasStableSignalingState(){return this.connection.signalingState==="stable"}hasReadyConnectionState(){const e=this.connection.connectionState;return e==="connected"||e==="new"}hasTerminalConnectionState(){const e=this.connection.connectionState;return e==="failed"||e==="closed"}isStableAndReady(){return this.hasStableSignalingState()&&this.hasReadyConnectionState()}hasHaveLocalOfferSignalingState(){return this.connection.signalingState==="have-local-offer"}async waitForPeerConnectionReady(){if(this.isStableAndReady())return;const e=()=>{const s=this.connection.connectionState;return new Error(`Peer connection in terminal state: ${s}. Recovery is not possible.`)},n=()=>this.hasTerminalConnectionState()?"error":this.isStableAndReady()?"success":"loading";if(n()==="error")throw e();return new Promise((s,r)=>{let i,a=!1;const o=()=>{a||(a=!0,clearTimeout(i),this.connection.removeEventListener("signalingstatechange",E),this.connection.removeEventListener("connectionstatechange",E),s())},c=p=>{a||(a=!0,clearTimeout(i),this.connection.removeEventListener("signalingstatechange",E),this.connection.removeEventListener("connectionstatechange",E),r(p))};function E(){const p=n();if(p==="error"){c(e());return}p==="success"&&o()}i=setTimeout(()=>{c(new Error("Timed out waiting for stable signaling state and ready connection state"))},ha),this.connection.addEventListener("signalingstatechange",E),this.connection.addEventListener("connectionstatechange",E),E()})}async waitForTracks(){return new Promise(e=>{const n=new Set,s=r=>{const{track:i}=r;n.add(i.kind),n.has("audio")&&n.has("video")&&(this.connection.removeEventListener("track",s),e())};this.connection.addEventListener("track",s)})}addTransceivers(){this.addRecvOnlyTransceiver("audio"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video")}addRecvOnlyTransceiver(e){const n={direction:"recvonly"};return this.connection.addTransceiver(e,n)}cancelSendOfferWithRepeatedCalls(){this.cancelableSendOfferWithRepeatedCalls?.cancel()}}const Jt=t=>t.getSettings(),Ea=(t,e)=>{const n=Jt(t);let s=e;s??=t.label;let r=n?.msid;return r??=s,r??=t.id,r},ga=(t,e)=>{const n=Jt(t);let s=e;return s??=n?.msid,s??=t.label,(s&&s.length>0?s:void 0)??t.id};class rt{participantGroups=new Map;trackToGroup=new Map;trackDisposers=new Map;get mainStream(){const e=this.getStreams(),[n]=e;return n}reset(){this.participantGroups.clear(),this.trackToGroup.clear(),this.trackDisposers.forEach(e=>{e()}),this.trackDisposers.clear()}addTrack(e,{onRemoved:n,streamHint:s}={}){const r=ga(e,s),i=Ea(e,s);if(this.trackToGroup.has(e.id))return{isAddedTrack:!1,isAddedStream:!1};const a=this.getParticipantGroups(r),o=a.get(i),c=!o;let E=o;E||(E={participantId:r,groupId:i,stream:new MediaStream,trackIds:new Set},a.set(i,E)),E.stream.addTrack(e),E.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:r,groupId:i});const p=()=>{this.disposeTrackListener(e.id);const A=this.removeTrack(e.id);A.isRemovedTrack&&n?.({participantId:r,trackId:e.id,isRemovedStream:A.isRemovedStream})};return e.addEventListener("ended",p),this.trackDisposers.set(e.id,()=>{e.removeEventListener("ended",p)}),{isAddedTrack:!0,isAddedStream:c,participantId:r}}removeTrack(e){this.disposeTrackListener(e);const n=this.trackToGroup.get(e);if(!n)return{isRemovedTrack:!1,isRemovedStream:!1};const{participantId:s,groupId:r}=n,i=this.participantGroups.get(s),a=i?.get(r);if(!a)return this.trackToGroup.delete(e),{isRemovedTrack:!1,isRemovedStream:!1};const o=a.stream.getTracks().find(E=>E.id===e);o&&a.stream.removeTrack(o),a.trackIds.delete(e),this.trackToGroup.delete(e);const c=a.trackIds.size===0;return c&&(i?.delete(r),i?.size===0&&this.participantGroups.delete(s)),{isRemovedTrack:!0,isRemovedStream:c}}removeStaleTracks(e,n){const s=this.participantGroups.get(e);if(!s)return!1;let r=!1;return[...s.values()].forEach(a=>{[...a.trackIds].filter(c=>!n.includes(c)).forEach(c=>{const E=this.removeTrack(c);r||=E.isRemovedTrack})}),r}getStreams(e){if(e!==void 0){const n=this.participantGroups.get(e);return n?[...n.values()].map(s=>s.stream):[]}return[...this.participantGroups.values()].flatMap(n=>[...n.values()]).map(n=>n.stream)}disposeTrackListener(e){const n=this.trackDisposers.get(e);n&&(n(),this.trackDisposers.delete(e))}getParticipantGroups(e){const n=this.participantGroups.get(e);if(n)return n;const s=new Map;return this.participantGroups.set(e,s),s}}const _e={type:"participant"},Ta={type:"spectator_synthetic"},ma=t=>({type:"spectator",recvParams:t});class y{role=_e;onRoleChanged;constructor(e){this.onRoleChanged=e}static hasParticipant(e){return e.type==="participant"}static hasSpectatorSynthetic(e){return e.type==="spectator_synthetic"}static hasSpectator(e){return e.type==="spectator"}static isExitingSpectatorRole(e,n){return y.hasSpectator(e)&&!y.hasSpectator(n)}static isEnteringSpectatorRole(e,n){return y.hasSpectator(n)}static isExitingAnySpectatorRole(e,n){const s=y.hasSpectator(e)||y.hasSpectatorSynthetic(e),r=y.hasSpectator(n)||y.hasSpectatorSynthetic(n);return s&&!r}static isEnteringAnySpectatorRole(e,n){const s=y.hasSpectator(e)||y.hasSpectatorSynthetic(e),r=y.hasSpectator(n)||y.hasSpectatorSynthetic(n);return!s&&r}getRole(){return this.role}setCallRoleParticipant(){this.changeRole(_e)}setCallRoleSpectatorSynthetic(){this.changeRole(Ta)}setCallRoleSpectator(e){this.changeRole(ma(e))}changeRole(e){const n=this.role;if(n.type!==e.type){this.setRole(e);return}y.hasSpectator(e)&&y.hasSpectator(n)&&n.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=_e}hasParticipant(){return y.hasParticipant(this.role)}hasSpectatorSynthetic(){return y.hasSpectatorSynthetic(this.role)}hasSpectator(){return y.hasSpectator(this.role)}setRole(e){const n=this.role;this.role=e,this.onRoleChanged?.({previous:n,next:e})}}const Sa=(t,e)=>{if(!t||!e)return t===e;const n=t.mainStream?.id,s=e.mainStream?.id,r=t.contentedStream?.id,i=e.contentedStream?.id;return n===s&&r===i};class Ca{lastEmittedStreams;hasChanged(e){return!Sa(this.lastEmittedStreams,e)}updateLastEmittedStreams(e){this.lastEmittedStreams=e}getLastEmittedStreams(){return this.lastEmittedStreams}reset(){this.lastEmittedStreams=void 0}}const pa="default",Ra="dual",Na="content_",Ia=t=>`${Na}${t.toLowerCase()}`,Aa=t=>[...t.getTracks()].some(e=>e.label.includes(Ra));class va{mainRemoteStreamsManager;recvRemoteStreamsManager;constructor(e,n){this.mainRemoteStreamsManager=e,this.recvRemoteStreamsManager=n}getActiveStreamsManagerTools({isSpectator:e,stateInfo:n}){return e?this.getRecvRemoteStreamsManagerTools({stateInfo:n}):this.getMainRemoteStreamsManagerTools({stateInfo:n})}getMainRemoteStreamsManagerTools({stateInfo:e}){const n=this.mainRemoteStreamsManager;return{manager:n,getRemoteStreams:()=>{const r=n.getStreams(),i=r.find(o=>!Aa(o)),a=e.isAvailable?r.find(o=>o!==i):void 0;return{mainStream:i,contentedStream:a}}}}getRecvRemoteStreamsManagerTools({stateInfo:e}){const n=this.recvRemoteStreamsManager;return{manager:n,getRemoteStreams:()=>{const i=n.getStreams(pa)[0],a=this.getRecvRemoteContentedStream({stateInfo:e});return{mainStream:i,contentedStream:a}}}}getRecvRemoteContentedStream({stateInfo:e}){if(!e.isAvailable||e.codec===void 0)return;const n=Ia(e.codec);return this.recvRemoteStreamsManager.getStreams(n)[0]}}const fa="udp",Oa=t=>t.transport?.iceTransport?t.transport.iceTransport.getLocalCandidates():[],Ma=t=>t.getReceivers().flatMap(Oa),_a=t=>{const s=Ma(t).filter(({protocol:r,port:i})=>i!==null&&fa===r).map(({port:r})=>r);return[...new Set(s)]},it=t=>t.streams[0]?.id;class Pa extends _.EventEmitterProxy{stateMachine;isPendingCall=!1;isPendingAnswer=!1;mainRemoteStreamsManager=new rt;recvRemoteStreamsManager=new rt;streamsManagerProvider;contentedStreamManager;tools;roleManager=new y(e=>{this.onRoleChanged(e)});mcuSession;recvSession;disposeRecvSessionTrackListener;disposeInRoomCredentialsListener;deferredStartRecvSessionRunner;streamsChangeTracker=new Ca;constructor({contentedStreamManager:e},n){super(Dt()),this.contentedStreamManager=e,this.tools=n,this.mcuSession=new ca(this.events,{onReset:this.reset}),this.stateMachine=Wt(this.events),this.streamsManagerProvider=new va(this.mainRemoteStreamsManager,this.recvRemoteStreamsManager),this.deferredStartRecvSessionRunner=new Ft({subscribe:s=>this.stateMachine.onStateChange(s),isReady:s=>s===u.IN_ROOM,isCancelled:s=>s===u.IDLE,onExecute:s=>{this.startRecvSessionForced({audioChannel:s.audioId}).catch(()=>{})}}),this.subscribeCallStatusChange(),this.subscribeMcuRemoteTrackEvents(),this.subscribeContentedStreamEvents()}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.mcuSession.connection}get isCallActive(){return this.mcuSession.isCallActive}get number(){return this.stateMachine.number}get isCallInitiator(){return this.stateMachine.isCallInitiator}get isDirectP2PRoom(){return this.stateMachine.isDirectP2PRoom}get isPresentationCall(){return this.stateMachine.isPresentationCall}get isDisconnecting(){return this.stateMachine.isDisconnecting}get localPorts(){const e=this.getActivePeerConnection();return e?_a(e):[]}getStreamsManagerProvider(){return this.streamsManagerProvider}getContentedStreamManager(){return this.contentedStreamManager}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}startCall=async(e,n,s)=>(this.isPendingCall=!0,this.events.emit("start-call",{extraHeaders:s.extraHeaders,number:s.number,answer:!1}),this.mcuSession.startCall(e,n,s).finally(()=>{this.isPendingCall=!1}));async endCall(){return this.events.emit("end-call"),this.mcuSession.endCall()}async renegotiate(){return this.hasSpectator()?this.renegotiateRecvSession():this.renegotiateMcuSession()}answerToIncomingCall=async(e,n)=>{this.isPendingAnswer=!0;const s=e();return this.events.emit("start-call",{answer:!0,extraHeaders:n.extraHeaders,number:s.remote_identity.uri.user}),this.mcuSession.answerToIncomingCall(s,n).finally(()=>{this.isPendingAnswer=!1})};getMainRemoteStream(){const{mainStream:e}=this.getRemoteStreams();return e}getRemoteStreams(){const{getRemoteStreams:e}=this.getActiveStreamsManagerTools();return e()}getToken(){return this.stateMachine.token}getRecvQuality(){const{recvSession:e}=this;if(e===void 0)return;const n=e.getEffectiveQuality();return{quality:e.getQuality(),effectiveQuality:n}}getActivePeerConnection=()=>this.hasSpectator()?this.recvSession?.peerConnection:this.mcuSession.connection;hasSpectator(){return this.roleManager.hasSpectator()}setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(){this.roleManager.setCallRoleSpectatorSynthetic()}setCallRoleSpectator(e){this.roleManager.setCallRoleSpectator(e)}async replaceMediaStream(e,n){return this.mcuSession.replaceMediaStream(e,n)}async restartIce(e){return this.mcuSession.restartIce(e)}async restartRecvSession(){const{recvSession:e}=this;if(!this.hasSpectator()||!e)return!1;const n=e.getAudioChannel(),s=e.getQuality(),{callResult:r}=await this.startRecvSessionForced({audioChannel:n,quality:s},{silent:!0});return r}async setRecvQuality(e){const{recvSession:n}=this;if(!this.hasSpectator()||!n)return!1;const s=n.getQuality(),r=n.getEffectiveQuality(),i=n.getAudioChannel(),a=Le(e);if(e===s&&a===r)return!1;if(a===r)return await n.setQuality(e),this.events.trigger("recv-quality-changed",{previousQuality:s,quality:e,effectiveQuality:r}),!0;const{session:o,callResult:c}=await this.startRecvSessionForced({audioChannel:i,quality:e},{silent:!0});if(c){const E=o.getEffectiveQuality();this.events.trigger("recv-quality-changed",{previousQuality:s,quality:e,effectiveQuality:E})}return c}async applyQuality(e){const{recvSession:n}=this;if(!this.hasSpectator()||!n)return!1;const s=n.getQuality(),r=await n.applyQuality(e);return r.applied&&this.events.trigger("recv-quality-changed",{previousQuality:s,quality:e,effectiveQuality:r.effectiveQuality}),r.applied}async failed(e,n){this.emitFailedCall(e,n),await this.endCall()}emitFailedCall(e,n){this.events.trigger("failed",{message:e,cause:n,originator:"local"})}reset=()=>{this.mainRemoteStreamsManager.reset(),this.roleManager.reset(),this.recvRemoteStreamsManager.reset(),this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.streamsChangeTracker.reset()};subscribeCallStatusChange(){const e=this.createCallStatusChangeListener();this.onRace(["accepted","confirmed","ended","failed"],e)}createCallStatusChangeListener(){let e=this.isCallActive;return()=>{const n=this.isCallActive;n!==e&&this.events.trigger("call-status-changed",{isCallActive:n}),e=n}}subscribeMcuRemoteTrackEvents(){this.on("peerconnection:ontrack",e=>{this.addRemoteTrack(this.mainRemoteStreamsManager,e.track,it(e))})}addRemoteTrack(e,n,s){const r=e.addTrack(n,{streamHint:s,onRemoved:i=>{this.handleChangedRemoteTracks(e,"removed",{isRemovedStream:i.isRemovedStream,isAddedStream:!1,trackId:i.trackId,participantId:i.participantId})}});r.isAddedTrack&&this.handleChangedRemoteTracks(e,"added",{isRemovedStream:!1,isAddedStream:r.isAddedStream,trackId:n.id,participantId:r.participantId})}handleChangedRemoteTracks(e,n,{trackId:s,participantId:r,isRemovedStream:i,isAddedStream:a}){const o=this.getActiveStreamsManagerTools();if(e!==o.manager)return;const c=o.getRemoteStreams();this.emitEventChangedRemoteTracks(c,n,{trackId:s,participantId:r}),(a||i)&&this.emitEventChangedRemoteStreams(c)}emitEventChangedRemoteTracks(e,n,{trackId:s,participantId:r}){this.events.trigger("remote-tracks-changed",{streams:e,changeType:n,trackId:s,participantId:r})}emitEventChangedRemoteStreamsConnected=()=>{this.emitEventChangedRemoteStreams(this.getRemoteStreams())};emitEventChangedRemoteStreams(e){this.streamsChangeTracker.hasChanged(e)&&(this.streamsChangeTracker.updateLastEmittedStreams(e),this.events.trigger("remote-streams-changed",{streams:e}))}getActiveStreamsManagerTools(){return this.streamsManagerProvider.getActiveStreamsManagerTools({isSpectator:this.hasSpectator(),stateInfo:this.contentedStreamManager.getStateInfo()})}attachRecvSessionTracks(e){const{peerConnection:n}=e,s=r=>{this.addRemoteTrack(this.recvRemoteStreamsManager,r.track,it(r))};n.addEventListener("track",s),this.disposeRecvSessionTrackListener=()=>{n.removeEventListener("track",s)}}async startRecvSessionForced(e,{silent:n}={}){return this.startRecvSession({audioChannel:e.audioChannel,quality:e.quality},{silent:n})}async startRecvSession({audioChannel:e,quality:n},{silent:s}={}){this.disposeInRoomCredentialsListener?.();const r=this.stateMachine.getInRoomCredentials();if(r===void 0)return{session:void 0,callResult:!1};this.stopRecvSession({silent:s});const i={audioChannel:e,quality:n,pcConfig:this.mcuSession.getPcConfig()},a=new ua(i,{sendOffer:this.tools.sendOffer});return this.recvSession=a,this.recvRemoteStreamsManager.reset(),this.attachRecvSessionTracks(a),a.call({conferenceNumber:r.conferenceForToken,token:r.token}).then(c=>(s!==!0&&this.events.emit("recv-session-started"),c&&(this.disposeInRoomCredentialsListener=this.stateMachine.onInRoomCredentialsChange(()=>{this.renegotiateRecvSession().catch(()=>{})})),{session:a,callResult:c})).catch(async c=>{this.stopRecvSession();const E=new j.IncomingResponse;E.body=c instanceof Error?c.message:String(c);const p=j.C.causes.INTERNAL_ERROR;throw await this.failed(E,p),c})}stopRecvSession({silent:e}={}){const n=!!this.recvSession;this.disposeInRoomCredentialsListener?.(),this.disposeInRoomCredentialsListener=void 0,this.recvSession?.close(),this.recvSession=void 0,this.disposeRecvSessionTrackListener?.(),this.disposeRecvSessionTrackListener=void 0,this.recvRemoteStreamsManager.reset(),n&&e!==!0&&this.events.emit("recv-session-ended")}onRoleChanged=({previous:e,next:n})=>{if(y.isExitingSpectatorRole(e,n)&&(this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.emitEventChangedRemoteStreamsConnected()),y.isEnteringSpectatorRole(e,n)){const s=n.recvParams;this.stateMachine.getInRoomCredentials()===void 0?this.deferredStartRecvSessionRunner.set({audioId:s.audioId}):this.startRecvSession({audioChannel:s.audioId}).catch(()=>{})}y.isExitingAnySpectatorRole(e,n)&&this.mcuSession.restoreBitrateForSenders(),y.isEnteringAnySpectatorRole(e,n)&&this.mcuSession.setMinBitrateForSenders()};subscribeContentedStreamEvents(){this.contentedStreamManager.on("available",this.emitEventChangedRemoteStreamsConnected),this.contentedStreamManager.on("not-available",this.emitEventChangedRemoteStreamsConnected)}async renegotiateRecvSession(){const e=this.stateMachine.getInRoomCredentials();return e===void 0||this.recvSession===void 0?!1:this.recvSession.renegotiate({conferenceNumber:e.conferenceForToken,token:e.token})}async renegotiateMcuSession(){return this.mcuSession.renegotiate()}}const Kt=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],ya=()=>new _.TypedEvents(Kt);var h=(t=>(t.IDLE="presentation:idle",t.STARTING="presentation:starting",t.ACTIVE="presentation:active",t.STOPPING="presentation:stopping",t.FAILED="presentation:failed",t))(h||{}),S=(t=>(t.LOG_TRANSITION="logTransition",t.LOG_STATE_CHANGE="logStateChange",t.SET_ERROR="setError",t.CLEAR_ERROR="clearError",t))(S||{}),m=(t=>(t.SCREEN_STARTING="SCREEN.STARTING",t.SCREEN_STARTED="SCREEN.STARTED",t.SCREEN_ENDING="SCREEN.ENDING",t.SCREEN_ENDED="SCREEN.ENDED",t.SCREEN_FAILED="SCREEN.FAILED",t.CALL_ENDED="CALL.ENDED",t.CALL_FAILED="CALL.FAILED",t.PRESENTATION_RESET="PRESENTATION.RESET",t))(m||{});const Xt={lastError:void 0},at=v("PresentationStateMachine"),ba=t=>t instanceof Error?t:new Error(JSON.stringify(t)),Da=()=>N.setup({types:{context:Xt,events:{}},actions:{[S.LOG_TRANSITION]:(t,e)=>{at(`State transition: ${e.from} -> ${e.to} (${e.event})`)},[S.LOG_STATE_CHANGE]:(t,e)=>{at("PresentationStateMachine state changed",e.state)},[S.SET_ERROR]:N.assign(({event:t})=>"error"in t&&t.error!==void 0?{lastError:ba(t.error)}:{lastError:void 0}),[S.CLEAR_ERROR]:N.assign(()=>({lastError:void 0}))}}),La=()=>Da().createMachine({id:"presentation",initial:h.IDLE,context:Xt,states:{[h.IDLE]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.IDLE}},on:{[m.SCREEN_STARTING]:{target:h.STARTING,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.IDLE,to:h.STARTING,event:m.SCREEN_STARTING}}]}}},[h.STARTING]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.STARTING}},on:{[m.SCREEN_STARTED]:{target:h.ACTIVE,actions:{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.ACTIVE,event:m.SCREEN_STARTED}}},[m.SCREEN_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.FAILED,event:m.SCREEN_FAILED}}]},[m.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.IDLE,event:m.SCREEN_ENDED}}]},[m.CALL_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.IDLE,event:m.CALL_ENDED}}]},[m.CALL_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.FAILED,event:m.CALL_FAILED}}]}}},[h.ACTIVE]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.ACTIVE}},on:{[m.SCREEN_ENDING]:{target:h.STOPPING,actions:{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.STOPPING,event:m.SCREEN_ENDING}}},[m.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.IDLE,event:m.SCREEN_ENDED}}]},[m.SCREEN_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.FAILED,event:m.SCREEN_FAILED}}]},[m.CALL_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.IDLE,event:m.CALL_ENDED}}]},[m.CALL_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.FAILED,event:m.CALL_FAILED}}]}}},[h.STOPPING]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.STOPPING}},on:{[m.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.IDLE,event:m.SCREEN_ENDED}}]},[m.SCREEN_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.FAILED,event:m.SCREEN_FAILED}}]},[m.CALL_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.IDLE,event:m.CALL_ENDED}}]},[m.CALL_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.FAILED,event:m.CALL_FAILED}}]}}},[h.FAILED]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.FAILED}},on:{[m.SCREEN_STARTING]:{target:h.STARTING,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.FAILED,to:h.STARTING,event:m.SCREEN_STARTING}}]},[m.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.FAILED,to:h.IDLE,event:m.SCREEN_ENDED}}]},[m.PRESENTATION_RESET]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.FAILED,to:h.IDLE,event:m.PRESENTATION_RESET}}]}}}}}),wa=La(),Ga=v("PresentationStateMachine");class Zt extends te{constructor(e){super(wa),this.subscribeCallEvents(e)}get isIdle(){return this.hasState(h.IDLE)}get isStarting(){return this.hasState(h.STARTING)}get isActive(){return this.hasState(h.ACTIVE)}get isStopping(){return this.hasState(h.STOPPING)}get isFailed(){return this.hasState(h.FAILED)}get isPending(){return this.isStarting||this.isStopping}get isActiveOrPending(){return this.isActive||this.isPending}get lastError(){return this.context.lastError}reset(){this.sendEvent({type:m.PRESENTATION_RESET})}send(e){this.sendEvent(e)}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){Ga(`[PresentationStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeCallEvents(e){this.addSubscription(e.on("presentation:start",()=>{this.sendEvent({type:m.SCREEN_STARTING})})),this.addSubscription(e.on("presentation:started",()=>{this.sendEvent({type:m.SCREEN_STARTED})})),this.addSubscription(e.on("presentation:end",()=>{this.sendEvent({type:m.SCREEN_ENDING})})),this.addSubscription(e.on("presentation:ended",()=>{this.sendEvent({type:m.SCREEN_ENDED})})),this.addSubscription(e.on("presentation:failed",n=>{this.sendEvent({type:m.SCREEN_FAILED,error:n})})),this.addSubscription(e.on("ended",()=>{this.sendEvent({type:m.CALL_ENDED})})),this.addSubscription(e.on("failed",n=>{this.sendEvent({type:m.CALL_FAILED,error:n})}))}}const ka=1,Ua=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],Fa=t=>t instanceof Error?t:new Error(String(t)),Ba=t=>Ne.hasCanceledError(t);class $a extends _.EventEmitterProxy{stateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:n}){super(ya()),this.callManager=e,this.maxBitrate=n,this.stateMachine=new Zt(this.callManager.events),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}get isPresentationInProcess(){return!!this.streamPresentationCurrent||this.isPendingPresentation}async startPresentation(e,n,{isNeedReinvite:s,contentHint:r,sendEncodings:i,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:n,presentationOptions:{isNeedReinvite:s,contentHint:r,sendEncodings:i,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const n=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const r=this.callManager.getEstablishedRTCSession();return r&&n?s=e().then(async()=>r.stopPresentation(n)).catch(i=>{throw this.notifyPresentationFailed(i),i}):n&&this.events.trigger("presentation:ended",n),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,n,{contentHint:s,sendEncodings:r,onAddedTransceiver:i}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,n,{contentHint:s,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:i}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}subscribe(){Ua.forEach(e=>{this.callManager.on(e,n=>{this.events.trigger(e,n)})}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:n,stream:s,presentationOptions:r,options:i={callLimit:ka}}){const a=async()=>this.sendPresentation(e,n,s,r),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=Ne.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,n,s,{isNeedReinvite:r=!0,contentHint:i="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const E=de(s,{contentHint:i});if(E===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=E;const p=e().then(async()=>n.startPresentation(E,r,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(A=>{throw this.removeStreamPresentationCurrent(),this.notifyPresentationFailed(A),A});return this.promisePendingStartPresentation=p,p.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:n}=this,{maxBitrate:s}=this;if(!e||!n||s===void 0)return;const r=e.getSenders();await Ri(r,n,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}notifyPresentationFailed(e){this.events.trigger("presentation:failed",Fa(e))}}const xa=v("ContentedStreamStateMachine"),qa=N.setup({types:{context:{},events:{}},actions:{setCodec:N.assign(({event:t})=>"codec"in t?{codec:t.codec}:{}),clearCodec:N.assign({codec:void 0})}}).createMachine({id:"contented-stream",initial:"contented-stream:not-available",context:{},states:{"contented-stream:not-available":{on:{"CONTENTED_STREAM.AVAILABLE":{target:"contented-stream:available",actions:"setCodec"}}},"contented-stream:available":{on:{"CONTENTED_STREAM.NOT_AVAILABLE":{target:"contented-stream:not-available",actions:"clearCodec"},"CONTENTED_STREAM.AVAILABLE":{target:"contented-stream:available",actions:"setCodec",reenter:!0},"CONTENTED_STREAM.RESET":{target:"contented-stream:not-available",actions:"clearCodec"}}}}});class Va extends te{constructor(){super(qa)}get isAvailable(){return this.state==="contented-stream:available"}get isNotAvailable(){return this.state==="contented-stream:not-available"}get codec(){return this.getSnapshot().context.codec}getStateInfo(){return{isAvailable:this.isAvailable,codec:this.codec}}reset(){this.send({type:"CONTENTED_STREAM.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){xa(`[ContentedStreamStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on("contented-stream:available",n=>{this.send({type:"CONTENTED_STREAM.AVAILABLE",codec:n.codec})})),this.addSubscription(e.on("contented-stream:not-available",()=>{this.send({type:"CONTENTED_STREAM.NOT_AVAILABLE"})}))}}const Ha=["available","not-available"],Wa=()=>new _.TypedEvents(Ha);class Qa extends _.EventEmitterProxy{stateMachine;constructor(){super(Wa()),this.stateMachine=new Va,this.proxyEvents()}get isAvailable(){return this.stateMachine.isAvailable}get codec(){return this.stateMachine.codec}getStateInfo(){return this.stateMachine.getStateInfo()}reset(){this.stateMachine.reset()}subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}proxyEvents(){this.stateMachine.onStateChange(()=>{const e=this.getStateInfo();e.isAvailable?this.events.trigger("available",{codec:e.codec}):this.events.trigger("not-available",{})})}}const en=["ringing","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],tn=()=>new _.TypedEvents(en);var l=(t=>(t.IDLE="incoming:idle",t.RINGING="incoming:ringing",t.CONSUMED="incoming:consumed",t.DECLINED="incoming:declined",t.TERMINATED="incoming:terminated",t.FAILED="incoming:failed",t))(l||{}),C=(t=>(t.LOG_TRANSITION="logTransition",t.LOG_STATE_CHANGE="logStateChange",t.REMEMBER_INCOMING="rememberIncoming",t.REMEMBER_REASON="rememberReason",t.CLEAR_INCOMING="clearIncoming",t))(C||{}),R=(t=>(t.RINGING="INCOMING.RINGING",t.CONSUMED="INCOMING.CONSUMED",t.DECLINED="INCOMING.DECLINED",t.TERMINATED="INCOMING.TERMINATED",t.FAILED="INCOMING.FAILED",t.CLEAR="INCOMING.CLEAR",t))(R||{});const nn={remoteCallerData:void 0,lastReason:void 0},ot=v("IncomingCallStateMachine"),Ya=()=>N.setup({types:{context:nn,events:{}},actions:{[C.LOG_TRANSITION]:(t,e)=>{ot(`State transition: ${e.from} -> ${e.to} (${e.event})`)},[C.LOG_STATE_CHANGE]:(t,e)=>{ot("IncomingCallStateMachine state changed",e.state)},[C.REMEMBER_INCOMING]:N.assign(({event:t})=>({remoteCallerData:t.data,lastReason:void 0})),[C.REMEMBER_REASON]:N.assign(({event:t,context:e})=>t.type===R.CONSUMED?{remoteCallerData:e.remoteCallerData,lastReason:l.CONSUMED}:t.type===R.DECLINED?{remoteCallerData:t.data,lastReason:l.DECLINED}:t.type===R.TERMINATED?{remoteCallerData:t.data,lastReason:l.TERMINATED}:{remoteCallerData:t.data,lastReason:l.FAILED}),[C.CLEAR_INCOMING]:N.assign(()=>({remoteCallerData:void 0,lastReason:void 0}))}}),ja=()=>Ya().createMachine({id:"incoming",initial:l.IDLE,context:nn,states:{[l.IDLE]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:l.IDLE}},on:{[R.RINGING]:{target:l.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.IDLE,to:l.RINGING,event:R.RINGING}}]},[R.CLEAR]:{target:l.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.IDLE,to:l.IDLE,event:R.CLEAR}}]}}},[l.RINGING]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:l.RINGING}},on:{[R.RINGING]:{target:l.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.RINGING,to:l.RINGING,event:R.RINGING}}]},[R.CONSUMED]:{target:l.CONSUMED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:l.RINGING,to:l.CONSUMED,event:R.CONSUMED}}]},[R.DECLINED]:{target:l.DECLINED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:l.RINGING,to:l.DECLINED,event:R.DECLINED}}]},[R.TERMINATED]:{target:l.TERMINATED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:l.RINGING,to:l.TERMINATED,event:R.TERMINATED}}]},[R.FAILED]:{target:l.FAILED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:l.RINGING,to:l.FAILED,event:R.FAILED}}]},[R.CLEAR]:{target:l.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.RINGING,to:l.IDLE,event:R.CLEAR}}]}}},[l.CONSUMED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:l.CONSUMED}},on:{[R.CLEAR]:{target:l.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.CONSUMED,to:l.IDLE,event:R.CLEAR}}]},[R.RINGING]:{target:l.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.CONSUMED,to:l.RINGING,event:R.RINGING}}]}}},[l.DECLINED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:l.DECLINED}},on:{[R.CLEAR]:{target:l.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.DECLINED,to:l.IDLE,event:R.CLEAR}}]},[R.RINGING]:{target:l.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.DECLINED,to:l.RINGING,event:R.RINGING}}]}}},[l.TERMINATED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:l.TERMINATED}},on:{[R.CLEAR]:{target:l.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.TERMINATED,to:l.IDLE,event:R.CLEAR}}]},[R.RINGING]:{target:l.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.TERMINATED,to:l.RINGING,event:R.RINGING}}]}}},[l.FAILED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:l.FAILED}},on:{[R.CLEAR]:{target:l.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.FAILED,to:l.IDLE,event:R.CLEAR}}]},[R.RINGING]:{target:l.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:l.FAILED,to:l.RINGING,event:R.RINGING}}]}}}}}),za=ja(),Ja=v("IncomingCallStateMachine");class sn extends te{constructor({incomingEvents:e,connectionEvents:n}){super(za),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(n)}get isIdle(){return this.hasState(l.IDLE)}get isRinging(){return this.hasState(l.RINGING)}get isConsumed(){return this.hasState(l.CONSUMED)}get isDeclined(){return this.hasState(l.DECLINED)}get isTerminated(){return this.hasState(l.TERMINATED)}get isFailed(){return this.hasState(l.FAILED)}get isActive(){return this.isRinging}get isFinished(){return this.isConsumed||this.isDeclined||this.isTerminated||this.isFailed}get remoteCallerData(){return this.context.remoteCallerData}get lastReason(){return this.context.lastReason}toConsumed=()=>{this.sendEvent({type:R.CONSUMED})};reset(){this.toClearIncoming()}send(e){this.sendEvent(e)}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){Ja(`[IncomingCallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeIncomingEvents(e){this.addSubscription(e.on("ringing",n=>{this.sendEvent({type:R.RINGING,data:n})})),this.addSubscription(e.on("declinedIncomingCall",n=>{this.sendEvent({type:R.DECLINED,data:n})})),this.addSubscription(e.on("terminatedIncomingCall",n=>{this.sendEvent({type:R.TERMINATED,data:n})})),this.addSubscription(e.on("failedIncomingCall",n=>{this.sendEvent({type:R.FAILED,data:n})}))}subscribeConnectionEvents(e){this.addSubscription(e.on("disconnected",()=>{this.toClearIncoming()})),this.addSubscription(e.on("registrationFailed",()=>{this.toClearIncoming()})),this.addSubscription(e.on("connect-failed",()=>{this.toClearIncoming()}))}toClearIncoming=()=>{this.sendEvent({type:R.CLEAR})}}const Ka=486,Xa=487,Pe=t=>({displayName:t.remote_identity.display_name,host:t.remote_identity.uri.host,incomingNumber:t.remote_identity.uri.user,rtcSession:t});class Za extends _.EventEmitterProxy{stateMachine;incomingRTCSession;connectionManager;constructor(e){super(tn()),this.connectionManager=e,this.stateMachine=new sn({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get remoteCallerData(){if(this.incomingRTCSession)return Pe(this.incomingRTCSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.stateMachine.toConsumed(),this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=Xa}={}){return new Promise((n,s)=>{try{const r=this.getIncomingRTCSession(),i=Pe(r);this.removeIncomingSession(),this.events.trigger("declinedIncomingCall",i),r.terminate({status_code:e}),n()}catch(r){s(r)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Ka})}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:n})=>{e==="remote"&&this.setIncomingSession(n)};setIncomingSession(e){this.incomingRTCSession=e;const n=Pe(e);e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger("terminatedIncomingCall",n):this.events.trigger("failedIncomingCall",n)}),this.events.trigger("ringing",n)}removeIncomingSession(){delete this.incomingRTCSession}}class eo{apiManager;connectionManager;callManager;get user(){return this.connectionManager?.getUser()}get number(){return this.callManager?.number}get isCallInitiator(){return!!this.callManager?.isCallInitiator}get peerToPeerRoom(){if(!(this.user===void 0||this.number===void 0))return this.isCallInitiator?`p2p${this.user}to${this.number}`:`p2p${this.number}to${this.user}`}subscribe({apiManager:e,connectionManager:n,callManager:s}){this.apiManager=e,this.connectionManager=n,this.callManager=s,s.on("confirmed",this.maybeSendDirectPeerToPeerRoom)}maybeSendDirectPeerToPeerRoom=()=>{const{peerToPeerRoom:e,number:n,apiManager:s}=this;if(e===void 0||n===void 0||s===void 0)return;const r=[`${g.CONTENT_ENTER_ROOM}: ${this.peerToPeerRoom}`,`${g.PARTICIPANT_NAME}: ${this.number}`,`${g.IS_DIRECT_PEER_TO_PEER}: true`];s.sendEnterRoom(r)}}const rn=["snapshot-changed"],to=()=>new _.TypedEvents(rn),no=(t,e)=>Object.is(t,e),ct=(t,e)=>t.connection.value===e.connection.value&&t.call.value===e.call.value&&t.incoming.value===e.incoming.value&&t.presentation.value===e.presentation.value&&t.autoConnector.value===e.autoConnector.value,dt=t=>({connection:t.connection.getSnapshot(),call:t.call.getSnapshot(),incoming:t.incoming.getSnapshot(),presentation:t.presentation.getSnapshot(),autoConnector:t.autoConnector.getSnapshot()});class an extends _.EventEmitterProxy{machines;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){super(to()),this.machines={connection:e.connectionManager.stateMachine,call:e.callManager.stateMachine,incoming:e.incomingCallManager.stateMachine,presentation:e.presentationManager.stateMachine,autoConnector:e.autoConnectorManager.stateMachine},this.currentSnapshot=dt(this.machines),this.actorSubscriptions.push(this.machines.connection.subscribe(this.notifySubscribers),this.machines.call.subscribe(this.notifySubscribers),this.machines.incoming.subscribe(this.notifySubscribers),this.machines.presentation.subscribe(this.notifySubscribers),this.machines.autoConnector.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,n,s){const r=typeof n=="function",i=r?e:A=>A,a=r?n:e,c=r?s??no:ct,E=i(this.currentSnapshot),p={selector:i,listener:a,equals:c,current:E};return this.subscribers.add(p),()=>{this.subscribers.delete(p)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}notifySubscribers=()=>{const e=this.currentSnapshot;this.currentSnapshot=dt(this.machines);const n=ct(e,this.currentSnapshot);for(const s of this.subscribers){const r=s.selector(this.currentSnapshot);s.equals(s.current,r)||(s.current=r,s.listener(r))}n||this.events.trigger("snapshot-changed",{previous:e,current:this.currentSnapshot})}}const ae=1e3;var D=(t=>(t.INBOUND_RTP="inbound-rtp",t.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",t.MEDIA_SOURCE="media-source",t.OUTBOUND_RTP="outbound-rtp",t.REMOTE_INBOUND_RTP="remote-inbound-rtp",t.CODEC="codec",t.CANDIDATE_PAIR="candidate-pair",t.CERTIFICATE="certificate",t.TRANSPORT="transport",t.LOCAL_CANDIDATE="local-candidate",t.REMOTE_CANDIDATE="remote-candidate",t))(D||{});const on=["collected","stopped"],so=()=>new _.TypedEvents(on),lt=()=>"performance"in window?performance.now():Date.now(),ue=t=>[...t.keys()].reduce((e,n)=>{const s=t.get(n);return s===void 0?e:{...e,[s.type]:s}},{}),ro=t=>{if(!t)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=ue(t);return{outboundRtp:e[D.OUTBOUND_RTP],codec:e[D.CODEC],mediaSource:e[D.MEDIA_SOURCE],remoteInboundRtp:e[D.REMOTE_INBOUND_RTP]}},ht=t=>{if(!t)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=ue(t);return{outboundRtp:e[D.OUTBOUND_RTP],codec:e[D.CODEC],mediaSource:e[D.MEDIA_SOURCE],remoteInboundRtp:e[D.REMOTE_INBOUND_RTP]}},ut=({videoReceiversStats:t,synchronizationSourcesVideo:e})=>{if(!t)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const n=ue(t);return{inboundRtp:n[D.INBOUND_RTP],codec:n[D.CODEC],synchronizationSources:e}},io=({audioReceiverStats:t,synchronizationSourcesAudio:e})=>{if(!t)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const n=ue(t);return{inboundRtp:n[D.INBOUND_RTP],codec:n[D.CODEC],remoteOutboundRtp:n[D.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},cn=t=>{if(!t)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=ue(t);return{candidatePair:e[D.CANDIDATE_PAIR],certificate:e[D.CERTIFICATE],localCandidate:e[D.LOCAL_CANDIDATE],remoteCandidate:e[D.REMOTE_CANDIDATE],transport:e[D.TRANSPORT]}},ao=({audioSenderStats:t,videoSenderFirstStats:e,videoSenderSecondStats:n})=>({video:ht(e),secondVideo:ht(n),audio:ro(t),additional:cn(t??e??n)}),oo=({audioReceiverStats:t,videoReceiverFirstStats:e,videoReceiverSecondStats:n,synchronizationSources:s})=>({video:ut({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:ut({videoReceiversStats:n,synchronizationSourcesVideo:s.secondVideo??s.video}),audio:io({audioReceiverStats:t,synchronizationSourcesAudio:s.audio}),additional:cn(t??e??n)}),co=({audioSenderStats:t,videoSenderFirstStats:e,videoSenderSecondStats:n,audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a})=>{const o=ao({audioSenderStats:t,videoSenderFirstStats:e,videoSenderSecondStats:n}),c=oo({audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a});return{outbound:o,inbound:c}},lo=async t=>{const e="audio",n="video",s=t.getSenders(),r=s.find(M=>M.track?.kind===e),i=s.filter(M=>M.track?.kind===n),a=t.getReceivers(),o=a.find(M=>M.track.kind===e),c=a.filter(M=>M.track.kind===n),E={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},p={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},A={trackIdentifier:c[1]?.track.id,item:c[1]?.getSynchronizationSources()[0]},b={audio:E,video:p,secondVideo:A};return Promise.all([r?.getStats()??Promise.resolve(void 0),i[0]?.getStats()??Promise.resolve(void 0),i[1]?.getStats()??Promise.resolve(void 0),o?.getStats()??Promise.resolve(void 0),c[0]?.getStats()??Promise.resolve(void 0),c[1]?.getStats()??Promise.resolve(void 0)]).then(M=>{const[H,G,z,ne,He,Sn]=M;return{synchronizationSources:b,audioSenderStats:H,videoSenderFirstStats:G,videoSenderSecondStats:z,audioReceiverStats:ne,videoReceiverFirstStats:He,videoReceiverSecondStats:Sn}})},ho=v("StatsPeerConnection");class dn extends _.EventEmitterProxy{setTimeoutRequest;requesterAllStatistics=new Z.CancelableRequest(lo);constructor(){super(so()),this.setTimeoutRequest=new ee.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:n=ae,onError:s=ho}={}){this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s,onSuccess:r=>{this.start(e,{onError:s,interval:r.interval})}})},n)}stop({reason:e}){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest(),this.events.trigger("stopped",{reason:e})}collectStatistics=(e,{onError:n,onSuccess:s})=>{const r=lt();this.requestAllStatistics(e).then(i=>{this.events.trigger("collected",co(i));const o=lt()-r;let c=ae;o>48?c=ae*4:o>32?c=ae*3:o>16&&(c=ae*2),s({interval:c})}).catch(i=>{n&&n(i)})};requestAllStatistics=async e=>{const n=e();if(n===void 0)throw new Error("failed to collect statistics: peerConnection is not defined");return this.requesterAllStatistics.request(n)}}const uo=500,Eo=v("StatsManager");class go extends _.EventEmitterProxy{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:n}){const s=new dn;super(s.events),this.statsPeerConnection=s,this.callManager=e,this.apiManager=n,this.subscribe()}get availableIncomingBitrate(){return this.availableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get isInvalidInboundFrames(){return this.isEmptyInboundFrames&&this.isReceivingPackets}get isNoInboundVideoTraffic(){return this.packetsReceived===0&&this.bytesReceived===0}get isInboundVideoStalled(){if(this.packetsReceived===void 0||this.previousPacketsReceived===void 0||this.bytesReceived===void 0||this.previousBytesReceived===void 0)return!1;const e=this.previousPacketsReceived>0||this.previousBytesReceived>0,n=this.packetsReceived===this.previousPacketsReceived,s=this.bytesReceived===this.previousBytesReceived;return e&&n&&s}get isEmptyInboundFrames(){return!this.isFramesReceived||!this.isFramesDecoded}get previousAvailableIncomingBitrate(){return this.previousAvailableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get previousInboundRtp(){return this.previousAvailableStats?.inbound.video.inboundRtp}get previousFramesReceived(){return this.previousInboundRtp?.framesReceived}get previousFramesDecoded(){return this.previousInboundRtp?.framesDecoded}get inboundRtp(){return this.availableStats?.inbound.video.inboundRtp}get framesReceived(){return this.inboundRtp?.framesReceived}get framesDecoded(){return this.inboundRtp?.framesDecoded}get isFramesReceived(){const e=this.framesReceived!==void 0&&this.framesReceived>0,n=this.framesReceived!==this.previousFramesReceived;return e&&n}get isFramesDecoded(){const e=this.framesDecoded!==void 0&&this.framesDecoded>0,n=this.framesDecoded!==this.previousFramesDecoded;return e&&n}get packetsReceived(){return this.inboundRtp?.packetsReceived}get previousPacketsReceived(){return this.previousInboundRtp?.packetsReceived}get bytesReceived(){return this.inboundRtp?.bytesReceived}get previousBytesReceived(){return this.previousInboundRtp?.bytesReceived}get isReceivingPackets(){const e=this.packetsReceived!==void 0&&this.packetsReceived>=uo,n=this.packetsReceived!==this.previousPacketsReceived;return e&&n}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,n=this.availableIncomingBitrate;return e===void 0||n===void 0?!1:e===0?n>0:Math.abs(n-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.start),this.callManager.on("recv-session-started",this.handleRecvSessionStarted),this.callManager.on("recv-session-ended",this.handleRecvSessionEnded),this.callManager.on("recv-quality-changed",this.handleRecvQualityChanged),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableStats=this.availableStats,this.availableStats=e,this.maybeSendStats()};start=()=>{this.statsPeerConnection.start(this.callManager.getActivePeerConnection)};stop=e=>{this.statsPeerConnection.stop({reason:e}),this.availableStats=void 0,this.previousAvailableStats=void 0};restart(e){this.stop(e),this.statsPeerConnection.start(this.callManager.getActivePeerConnection)}handleRecvSessionStarted=()=>{this.restart("recv-session-started")};handleRecvSessionEnded=()=>{this.restart("recv-session-ended")};handleRecvQualityChanged=()=>{this.restart("recv-quality-changed")};handleEnded=()=>{this.stop("call-ended")};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{Eo("Failed to send stats",e)})}}const To=v("setCodecPreferences"),mo=(t,e)=>t.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),So=t=>{const e=RTCRtpSender.getCapabilities(t),n=RTCRtpReceiver.getCapabilities(t),s=e===null?[]:e.codecs,r=n===null?[]:n.codecs;return mo(s,r)},Co=(t,e)=>e===void 0||e.length===0?t:t.sort((n,s)=>{const r=e.indexOf(n.mimeType),i=e.indexOf(s.mimeType),a=r===-1?Number.MAX_VALUE:r,o=i===-1?Number.MAX_VALUE:i;return a-o}),po=(t,e)=>e===void 0||e.length===0?t:t.filter(n=>!e.includes(n.mimeType)),Ro=(t,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:n})=>{try{if(typeof t.setCodecPreferences=="function"&&t.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||n!==void 0&&n.length>0)){const s=So("video"),r=po(s,n),i=Co(r,e);t.setCodecPreferences(i)}}catch(s){To("setCodecPreferences error",s)}},ln=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"],No=()=>new _.TypedEvents(ln),Io=v("VideoSendingBalancerManager");class Ao extends _.EventEmitterProxy{isBalancingActive=!1;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,n,s={}){super(No()),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new na(n,()=>e.connection,{...s,onSetParameters:r=>{this.events.trigger("parameters-updated",r),s.onSetParameters?.(r)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("recv-session-started",this.handleRecvSessionStarted),this.callManager.on("recv-session-ended",this.handleRecvSessionEnded),this.callManager.on("recv-quality-changed",this.handleRecvQualityChanged),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};handleRecvSessionStarted=()=>{this.stopBalancing()};handleRecvSessionEnded=()=>{this.scheduleBalancingStart()};handleRecvQualityChanged=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{Io("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const hn="health-snapshot",un="inbound-video-problem-detected",En="inbound-video-problem-resolved",gn="inbound-video-problem-reset",Tn=[hn,un,En,gn],vo=()=>new _.TypedEvents(Tn),fo=3;class le extends _.EventEmitterProxy{statsManager;callManager;minConsecutiveProblemSamplesCount;consecutiveProblemSamplesCount=0;currentProblemReason;hasEmittedCurrentProblem=!1;constructor(e,n,s=fo){super(vo()),this.statsManager=e,this.callManager=n,le.assertValidMinConsecutiveProblemSamplesCount(s),this.minConsecutiveProblemSamplesCount=s,this.subscribe()}get mainVideoTrack(){return this.callManager.getMainRemoteStream()?.getVideoTracks()[0]}get isMutedMainVideoTrack(){const{mainVideoTrack:e}=this;return e===void 0?!1:e.muted}get isInvalidInboundFrames(){return this.statsManager.isInvalidInboundFrames}get isNoInboundVideoTraffic(){return this.statsManager.isNoInboundVideoTraffic}get isInboundVideoStalled(){return this.statsManager.isInboundVideoStalled}get healthSnapshot(){return{isMutedMainVideoTrack:this.isMutedMainVideoTrack,isInvalidInboundFrames:this.isInvalidInboundFrames,isNoInboundVideoTraffic:this.isNoInboundVideoTraffic,isInboundVideoStalled:this.isInboundVideoStalled}}static resolveProblemReason(e){if(e.isInboundVideoStalled)return"inbound-video-stalled";if(e.isNoInboundVideoTraffic)return"no-inbound-video-traffic";if(e.isMutedMainVideoTrack&&e.isInvalidInboundFrames)return"invalid-inbound-frames"}static assertValidMinConsecutiveProblemSamplesCount(e){if(!Number.isInteger(e)||e<1)throw new Error("minConsecutiveProblemSamplesCount should be a positive integer")}setMinConsecutiveProblemSamplesCount(e){le.assertValidMinConsecutiveProblemSamplesCount(e),this.minConsecutiveProblemSamplesCount=e,this.resetProblemDetectionState()}handleStatsCollected=()=>{const{healthSnapshot:e}=this;this.events.trigger(hn,e);const n=le.resolveProblemReason(e);if(n===void 0){this.maybeEmitResolvedProblem(e),this.resetProblemDetectionState();return}this.updateProblemDetectionState(n),this.consecutiveProblemSamplesCount>=this.minConsecutiveProblemSamplesCount&&!this.hasEmittedCurrentProblem&&(this.events.trigger(un,{...e,consecutiveProblemSamplesCount:this.consecutiveProblemSamplesCount,reason:n}),this.hasEmittedCurrentProblem=!0)};subscribe(){this.statsManager.on("collected",this.handleStatsCollected),this.callManager.on("peerconnection:confirmed",this.handleProblemReset("peerconnection:confirmed")),this.callManager.on("recv-session-started",this.handleProblemReset("recv-session-started")),this.callManager.on("recv-session-ended",this.handleProblemReset("recv-session-ended")),this.callManager.on("recv-quality-changed",this.handleProblemReset("recv-quality-changed")),this.callManager.on("failed",this.handleProblemReset("failed")),this.callManager.on("ended",this.handleProblemReset("ended"))}updateProblemDetectionState=e=>{if(this.currentProblemReason===e){this.consecutiveProblemSamplesCount+=1;return}this.currentProblemReason=e,this.consecutiveProblemSamplesCount=1,this.hasEmittedCurrentProblem=!1};maybeEmitResolvedProblem=e=>{!this.hasEmittedCurrentProblem||this.currentProblemReason===void 0||this.events.trigger(En,{...e,reason:this.currentProblemReason})};handleProblemReset=e=>()=>{this.maybeEmitResetProblem(e),this.resetProblemDetectionState()};maybeEmitResetProblem=e=>{!this.hasEmittedCurrentProblem||this.currentProblemReason===void 0||this.events.trigger(gn,{reason:this.currentProblemReason,resetCause:e})};resetProblemDetectionState=()=>{this.currentProblemReason=void 0,this.consecutiveProblemSamplesCount=0,this.hasEmittedCurrentProblem=!1}}const J=v("MainStreamRecovery"),Oo=4e3;class Re{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,n=Oo){this.callManager=e,this.renegotiateRequester=new Z.CancelableRequest(e.renegotiate.bind(e)),this.renegotiateThrottled=this.createRenegotiateThrottled(n),this.subscribe()}static assertValidThrottleRecoveryTimeout(e){if(!Number.isInteger(e)||e<1)throw new Error("throttleRecoveryTimeout should be a positive integer")}setThrottleRecoveryTimeout(e){Re.assertValidThrottleRecoveryTimeout(e),this.renegotiateThrottled.cancel(),this.renegotiateThrottled=this.createRenegotiateThrottled(e)}recover(){J("trying to recover main stream"),this.renegotiateThrottled()}requestRenegotiate=()=>{if(J("trying to renegotiate"),this.renegotiateRequester.requested){J("previous renegotiate is not finished yet");return}this.renegotiateRequester.request().then(()=>{J("renegotiate has successful")}).catch(e=>{J("failed to renegotiate main media stream",e)})};createRenegotiateThrottled(e){return Re.assertValidThrottleRecoveryTimeout(e),pn.throttle(this.requestRenegotiate.bind(this),e)}subscribe(){this.callManager.on("ended",()=>{this.cancel()})}cancel(){J("cancel recover main stream"),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}}var Ve=(t=>(t.VP8="video/VP8",t.VP9="video/VP9",t.H264="video/H264",t.AV1="video/AV1",t.rtx="video/rtx",t.red="video/red",t.flexfec03="video/flexfec-03",t))(Ve||{});const Mo={major:25,minor:8,patch:0},_o=({isYandexBrowser:t,hasGreaterThanBrowserVersion:e})=>{const n=e(Mo);return t&&n},Po=()=>{const t=Fe();if(_o(t))return[Ve.VP8]},yo=()=>{const{isMobileDevice:t,isSafari:e,isOpera:n,isWindows:s}=Fe();return t||e||n&&s};let mn;yo()&&(mn="h264");const bo={ignoreForCodec:mn},Do=Po(),Lo=1e6,wo=Ot.map(t=>`auto-connect:${t}`),Go=At.map(t=>`connection:${t}`),ko=bt.map(t=>`call:${t}`),Uo=mt.map(t=>`api:${t}`),Fo=en.map(t=>`incoming-call:${t}`),Bo=Kt.map(t=>`presentation:${t}`),$o=on.map(t=>`stats:${t}`),xo=ln.map(t=>`video-balancer:${t}`),qo=Tn.map(t=>`main-stream-health:${t}`),Vo=rn.map(t=>`session:${t}`),Ho=["disconnected-from-out-of-call","connected-with-configuration-from-out-of-call","stopped-presentation-by-server-command"],Wo=[...wo,...Go,...ko,...Uo,...Fo,...Bo,...$o,...xo,...qo,...Vo,...Ho],Qo=()=>new _.TypedEvents(Wo),Et=v("SipConnector");class Yo extends _.EventEmitterProxy{connectionManager;connectionQueueManager;contentedStreamManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;peerToPeerManager;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:n,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:r,autoConnectorOptions:i,numberOfConnectionAttempts:a,minConsecutiveProblemSamplesCount:o,throttleRecoveryTimeout:c}={}){super(Qo()),this.preferredMimeTypesVideoCodecs=n??Do,this.excludeMimeTypesVideoCodecs=s,this.apiManager=new wn,this.connectionManager=new us({JsSIP:e},{numberOfConnectionAttempts:a}),this.connectionQueueManager=new Es({connectionManager:this.connectionManager}),this.contentedStreamManager=new Qa,this.callManager=new Pa({contentedStreamManager:this.contentedStreamManager},{sendOffer:this.sendOffer}),this.incomingCallManager=new Za(this.connectionManager),this.presentationManager=new $a({callManager:this.callManager,maxBitrate:Lo}),this.statsManager=new go({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new Ps({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},i),this.videoSendingBalancerManager=new Ao(this.callManager,this.apiManager,r??bo),this.mainStreamHealthMonitor=new le(this.statsManager,this.callManager,o),this.mainStreamRecovery=new Re(this.callManager,c),this.sessionManager=new an({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager,autoConnectorManager:this.autoConnectorManager}),this.callManager.subscribeToApiEvents(this.apiManager),this.contentedStreamManager.subscribeToApiEvents(this.apiManager),this.apiManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager}),this.peerToPeerManager=new eo,this.peerToPeerManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager,apiManager:this.apiManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get isCallActive(){return this.callManager.isCallActive}get localPorts(){return this.callManager.localPorts}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}get isDirectP2PRoom(){return this.callManager.isDirectP2PRoom}get isPresentationCall(){return this.callManager.isPresentationCall}get isOptionalPresentationPermission(){return this.isDirectP2PRoom||this.isPresentationCall}connect=async(...e)=>this.connectionQueueManager.connect(...e);disconnect=async()=>this.connectionQueueManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();sendOptions=async(e,n,s)=>this.connectionManager.sendOptions(e,n,s);ping=async(e,n)=>this.connectionManager.ping(e,n);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getUri=e=>this.connectionManager.getUri(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:n,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(n)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:n,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(n)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getRemoteStreams=()=>this.callManager.getRemoteStreams();getRecvQuality=()=>this.callManager.getRecvQuality();setRecvQuality=async e=>this.callManager.setRecvQuality(e);applyQuality=async e=>this.callManager.applyQuality(e);replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,n={}){const{callLimit:s,onAddedTransceiver:r,...i}=n;return this.presentationManager.startPresentation(async()=>{await(this.isOptionalPresentationPermission?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...i,onAddedTransceiver:this.resolveHandleAddTransceiver(r)},s===void 0?void 0:{callLimit:s})}async stopPresentation(){return this.presentationManager.stopPresentation(async()=>{await(this.isOptionalPresentationPermission?this.apiManager.sendNotAvailableContentedStream():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,n={}){const{onAddedTransceiver:s,...r}=n;return this.presentationManager.updatePresentation(async()=>{await(this.isOptionalPresentationPermission?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...r,onAddedTransceiver:this.resolveHandleAddTransceiver(s)})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}setMinConsecutiveProblemSamplesCount=e=>{this.mainStreamHealthMonitor.setMinConsecutiveProblemSamplesCount(e)};setThrottleRecoveryTimeout=e=>{this.mainStreamRecovery.setThrottleRecoveryTimeout(e)};subscribeDisconnectedFromOutOfCall(){this.connectionManager.on("disconnected",()=>{this.isCallActive||this.events.trigger("disconnected-from-out-of-call",{})})}subscribeConnectedWithConfigurationFromOutOfCall(){this.connectionManager.on("connected-with-configuration",e=>{this.isCallActive||this.events.trigger("connected-with-configuration-from-out-of-call",e)})}mayBeStopPresentationAndNotify(){this.presentationManager.isPresentationInProcess&&(this.stopPresentation().catch(()=>{}),this.events.trigger("stopped-presentation-by-server-command",{}))}subscribeToApiEvents(){this.apiManager.on("participant:move-request-to-participants",()=>{this.callManager.setCallRoleParticipant()}),this.apiManager.on("participant:move-request-to-spectators-synthetic",()=>{this.callManager.setCallRoleSpectatorSynthetic(),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("participant:move-request-to-spectators-with-audio-id",({audioId:e})=>{this.callManager.setCallRoleSpectator({audioId:e}),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("presentation:must-stop",()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on("failed-send-room-direct-p2p",({error:e})=>{const n=new j.IncomingResponse;n.body=e instanceof Error?e.message:String(e);const s=j.C.causes.INTERNAL_ERROR;this.callManager.failed(n,s).catch(r=>{Et("Failed to end call after failed:",r)})})}sendOffer=async(e,n)=>{const r=this.connectionManager.getConnectionConfiguration()?.sipServerUrl;if(r===void 0)throw new Error("No sipServerUrl for sendOffer");return Gt({serverUrl:r,offer:n,token:e.token,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){Ro(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents("auto-connect",this.autoConnectorManager),this.bridgeEvents("connection",this.connectionManager),this.bridgeEvents("call",this.callManager),this.bridgeEvents("api",this.apiManager),this.bridgeEvents("incoming-call",this.incomingCallManager),this.bridgeEvents("presentation",this.presentationManager),this.bridgeEvents("stats",this.statsManager),this.bridgeEvents("video-balancer",this.videoSendingBalancerManager),this.bridgeEvents("main-stream-health",this.mainStreamHealthMonitor),this.bridgeEvents("session",this.sessionManager),this.subscribeToApiEvents(),this.subscribeDisconnectedFromOutOfCall(),this.subscribeConnectedWithConfigurationFromOutOfCall(),this.subscribeToMainStreamHealthMonitorEvents()}subscribeToMainStreamHealthMonitorEvents(){this.mainStreamHealthMonitor.on("inbound-video-problem-detected",({reason:e})=>{Et("detected inbound video problem",{reason:e}),this.mainStreamRecovery.recover()})}bridgeEvents=(e,n)=>{n.events.eachTriggers((s,r)=>{n.on(r,i=>{this.events.trigger(`${e}:${r}`,i)})})};resolveHandleAddTransceiver=e=>async(n,s,r)=>{this.setCodecPreferences(n),await e?.(n,s,r)}}exports.ConnectionStateMachine=Nt;exports.DeferredCommandRunner=Ft;exports.ECallCause=qe;exports.EContentUseLicense=Ue;exports.EEvents=T;exports.EEvents$1=R;exports.EEvents$2=m;exports.EMimeTypesVideoCodecs=Ve;exports.EState=u;exports.EState$1=d;exports.EState$2=O;exports.EState$3=l;exports.EState$4=h;exports.EStatsTypes=D;exports.FAILED_CONFERENCE_NUMBER=Lt;exports.IncomingCallStateMachine=sn;exports.PURGATORY_CONFERENCE_NUMBER=wt;exports.PresentationStateMachine=Zt;exports.RTCSessionMock=F;exports.SessionManager=an;exports.SipConnector=Yo;exports.StatsPeerConnection=dn;exports.UA_JSSIP_EVENT_NAMES=_t;exports.createAutoConnectorStateMachine=ft;exports.createCallStateMachine=Wt;exports.createEvents=Dt;exports.createEvents$1=vt;exports.createEvents$2=tn;exports.createUaParser=Fe;exports.disableDebug=In;exports.enableDebug=Nn;exports.getCodecFromSender=$e;exports.hasCanceledStartPresentationError=Ba;exports.hasNotReadyForConnectionError=pt;exports.hasPeerToPeer=Ce;exports.hasPurgatory=he;exports.prepareMediaStream=de;exports.resolveDebug=v;exports.resolveOnStartMainCam=Ii;exports.resolveOnStartMic=vi;exports.resolveOnStopMainCam=Oi;exports.resolveOnStopMic=_i;exports.sendOffer=Gt;exports.setEncodingsToSender=Be;exports.setParametersToSender=pe;exports.stringifyMessage=ii;