sip-connector 28.9.2 → 28.10.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.
- package/dist/@SipConnector-BRT5jt1Y.cjs +1 -0
- package/dist/{@SipConnector-CqTjOCB3.js → @SipConnector-DYHoL5kV.js} +650 -604
- package/dist/AutoConnectorManager/@AutoConnectorManager.d.ts +2 -2
- package/dist/AutoConnectorManager/PingServerRequester.d.ts +4 -1
- package/dist/AutoConnectorManager/index.d.ts +1 -1
- package/dist/AutoConnectorManager/types.d.ts +10 -0
- package/dist/SipConnector/@SipConnector.d.ts +1 -1
- package/dist/SipConnector/events.d.ts +2 -2
- package/dist/doMock.cjs +1 -1
- package/dist/doMock.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
- package/dist/@SipConnector-lXAjX378.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const U=require("@krivega/jssip"),Ue=require("webrtc-mock"),_=require("events-constructor"),He=require("debug"),X=require("@krivega/timeout-requester"),K=require("@krivega/cancelable-promise"),T=require("xstate"),Me=require("repeated-calls"),Oe=require("stack-promises"),Bn=require("ua-parser-js");require("sequent-promises");const Be=require("lodash"),We="sip-connector",$n=He(We),xn=()=>{He.enable(`${We}:*`)},qn=()=>{He.enable(`-${We}:*`)},I=t=>$n.extend(t),Vn="Error decline with 603",Hn=1006,Wn=t=>typeof t=="object"&&t!==null&&"code"in t&&t.code===Hn,Qn=t=>t.message===Vn;var Re=(t=>(t.SPECTATOR="SPECTATOR",t.PARTICIPANT="PARTICIPANT",t))(Re||{}),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||{}),W=(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))(W||{}),x=(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))(x||{}),Ne=(t=>(t.ADMIN_STOP_MIC="ADMINSTOPMIC",t.ADMIN_START_MIC="ADMINSTARTMIC",t))(Ne||{}),yt=(t=>(t.H264="H264",t.VP8="VP8",t.VP9="VP9",t.AV1="AV1",t))(yt||{}),E=(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))(E||{}),ue=(t=>(t.AVAILABLE_CONTENTED_STREAM="YOUCANRECEIVECONTENT",t.NOT_AVAILABLE_CONTENTED_STREAM="CONTENTEND",t.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",t))(ue||{}),ie=(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))(ie||{}),Ae=(t=>(t.ADMIN_SYNC_FORCED="1",t.ADMIN_SYNC_NOT_FORCED="0",t))(Ae||{}),Qe=(t=>(t.SPECTATOR_MANUAL="0",t.BY_STATE_CAM="1",t.SPECTATOR_FORCED="2",t))(Qe||{}),_e=(t=>(t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",t))(_e||{});const q=t=>typeof t=="string"&&t.trim().length>0,$e=t=>typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t),Yn=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Pt=t=>typeof t=="boolean",jn=t=>Array.isArray(t)&&t.every(q),Dt=["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"],zn=()=>new _.TypedEvents(Dt),Jn=t=>!(!Yn(t)||!q(t.conference)||!q(t.participant)||!q(t.jwt)),j=(t,e)=>{const n=e.toLowerCase(),s=Object.entries(t).find(([,r])=>typeof r=="string"&&r.toLowerCase()===n);return s?s[1]:void 0},Kn=t=>typeof t=="string"&&!Number.isNaN(Number(t))&&Number.isFinite(Number(t)),Xn=t=>{if(Kn(t))return Number(t)},Zn=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(!q(n))return;const s=n.toLowerCase();switch(e){case E.BEARER_TOKEN:return n;case E.CONTENT_ENTER_ROOM:case E.PARTICIPANT_NAME:case E.INPUT_CHANNELS:case E.OUTPUT_CHANNELS:case E.TRACKS_DIRECTION:case E.AUDIO_ID:case E.MAIN_CAM_RESOLUTION:case E.MEDIA_STATE:case E.NOTIFY:case E.CONTENT_ENABLE_MEDIA_DEVICE:return s;case E.MEDIA_TYPE:case E.MAIN_CAM_STATE:case E.MIC_STATE:case E.AVAILABLE_INCOMING_BITRATE:case E.AUDIO_TRACK_COUNT:case E.VIDEO_TRACK_COUNT:return Xn(s);case E.CONTENTED_STREAM_CODEC:return j(yt,s);case E.CONTENT_TYPE:return j(Q,s);case E.CONTENT_USE_LICENSE:return j(_e,s);case E.MAIN_CAM:return j(x,s);case E.MIC:return j(Ne,s);case E.MEDIA_SYNC:return j(Ae,s);case E.CONTENT_PARTICIPANT_STATE:return j(Re,s);case E.SPECTATOR_MODE:return j(Qe,s);case E.CONTENTED_STREAM_STATE:return j(ue,s);case E.IS_DIRECT_PEER_TO_PEER:return Zn(s);default:return}};var F=(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))(F||{});const tt=I("ApiManager");class es extends _.EventEmitterProxy{callManager;constructor(){super(zn())}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=`${E.INPUT_CHANNELS}: ${e}`,i=`${E.OUTPUT_CHANNELS}: ${n}`,a=[r,i];return s.sendInfo(W.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=`${E.MEDIA_STATE}: currentstate`,a=`${E.MAIN_CAM_STATE}: ${Number(e)}`,o=`${E.MIC_STATE}: ${Number(n)}`,c=[i,a,o];return r.sendInfo(W.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const n=this.getEstablishedRTCSessionProtected(),r=[`${E.AVAILABLE_INCOMING_BITRATE}: ${e}`];return n.sendInfo(W.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:r})}async sendRefusalToTurnOn(e,n={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${E.MEDIA_TYPE}: ${a}`];return s.sendInfo(W.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(W.SHARE_STATE,void 0,{extraHeaders:[ie.AVAILABLE_CONTENTED_STREAM]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(W.SHARE_STATE,void 0,{extraHeaders:[ie.ACK_PERMISSION_TO_START_PRESENTATION]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(W.SHARE_STATE,void 0,{extraHeaders:[ie.STOPPED_CLIENT_PRESENTATION]})}async sendNotAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(W.SHARE_STATE,void 0,{extraHeaders:[ie.NOT_AVAILABLE_CONTENTED_STREAM]})}async askPermissionToEnableCam(e={}){const n=this.getEstablishedRTCSessionProtected(),s=[ie.ENABLE_MAIN_CAM];return n.sendInfo(W.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(r=>{if(Qn(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(E.NOTIFY);if(n){const s=JSON.parse(n);this.handleNotify(s)}}catch(n){tt("error parse notify",n)}};handleNotify=e=>{switch(e.cmd){case F.CHANNELS:{this.triggerChannelsNotify(e);break}case F.WEBCAST_STARTED:{this.triggerWebcastStartedNotify(e);break}case F.WEBCAST_STOPPED:{this.triggerWebcastStoppedNotify(e);break}case F.ADDED_TO_LIST_MODERATORS:{this.triggerAddedToListModeratorsNotify(e);break}case F.REMOVED_FROM_LIST_MODERATORS:{this.triggerRemovedFromListModeratorsNotify(e);break}case F.ACCEPTING_WORD_REQUEST:{this.triggerParticipationAcceptingWordRequest(e);break}case F.CANCELLING_WORD_REQUEST:{this.triggerParticipationCancellingWordRequest(e);break}case F.MOVE_REQUEST_TO_STREAM:{this.triggerParticipantMoveRequestToStream(e);break}case F.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case F.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case F.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{this.maybeTriggerConferenceParticipantTokenIssued(e);break}default:tt("unknown cmd",e)}};handleNewInfo=e=>{const{originator:n}=e;if(n!=="remote")return;const{request:s}=e,r=s,i=L(r,E.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};Jn(r)&&this.events.trigger("conference:participant-token-issued",r)};maybeTriggerChannels=e=>{const n=L(e,E.INPUT_CHANNELS),s=L(e,E.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,E.CONTENT_ENTER_ROOM),s=L(e,E.PARTICIPANT_NAME),r=L(e,E.BEARER_TOKEN),i=L(e,E.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,E.CONTENTED_STREAM_STATE);if(n!==void 0)switch(n){case ue.AVAILABLE_CONTENTED_STREAM:{const s=L(e,E.CONTENTED_STREAM_CODEC);this.events.trigger("contented-stream:available",{codec:s});break}case ue.NOT_AVAILABLE_CONTENTED_STREAM:{this.events.trigger("contented-stream:not-available");break}case ue.MUST_STOP_PRESENTATION:{this.events.trigger("presentation:must-stop");break}}};maybeTriggerParticipantMoveRequest=e=>{const n=L(e,E.CONTENT_PARTICIPANT_STATE),s=L(e,E.AUDIO_ID),r=L(e,E.SPECTATOR_MODE);if(n===Re.SPECTATOR){const i=r===Qe.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===Re.PARTICIPANT&&this.events.trigger("participant:move-request-to-participants")};triggerMainCamControl=e=>{const n=L(e,E.MAIN_CAM),s=L(e,E.MEDIA_SYNC),r=s===Ae.ADMIN_SYNC_FORCED;if(n===x.ADMIN_START_MAIN_CAM){this.events.trigger("admin:start-main-cam",{isSyncForced:r});return}if(n===x.ADMIN_STOP_MAIN_CAM){this.events.trigger("admin:stop-main-cam",{isSyncForced:r});return}(n===x.RESUME_MAIN_CAM||n===x.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger("admin:force-sync-media-state",{isSyncForced:r});const i=L(e,E.MAIN_CAM_RESOLUTION);this.events.trigger("main-cam-control",{mainCam:n,resolutionMainCam:i})};triggerMicControl=e=>{const n=L(e,E.MIC),r=L(e,E.MEDIA_SYNC)===Ae.ADMIN_SYNC_FORCED;n===Ne.ADMIN_START_MIC?this.events.trigger("admin:start-mic",{isSyncForced:r}):n===Ne.ADMIN_STOP_MIC&&this.events.trigger("admin:stop-mic",{isSyncForced:r})};triggerUseLicense=e=>{const n=L(e,E.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 nt=0,ts=30;let ns=class{countInner=nt;initialCount=nt;limitInner=ts;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 ss{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 K.CancelableRequest(e),this.checkTelephonyByTimeout=X.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}}const rs=15e3,is=2,st=I("AutoConnectorManager: PingServerRequester");class as{connectionManager;pingServerByTimeout=void 0;failRequestsCount=0;isFailRequestReported=!1;constructor({connectionManager:e}){this.connectionManager=e}start({onFailRequest:e}){this.stop(),this.pingServerByTimeout=X.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:rs,request:async()=>(st("ping"),this.connectionManager.ping().then(()=>{st("ping success")}))}),this.pingServerByTimeout.start(void 0,{onSuccessRequest:()=>{this.resetFailRequests()},onFailRequest:()=>{this.failRequestsCount+=1,!(this.failRequestsCount<is||this.isFailRequestReported)&&(this.isFailRequestReported=!0,e())}})}stop(){this.pingServerByTimeout?.stop(),this.pingServerByTimeout=void 0,this.resetFailRequests()}resetFailRequests(){this.failRequestsCount=0,this.isFailRequestReported=!1}}class os{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()}}class cs{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:n}){this.connectionManager=e,this.notActiveCallSubscriber=new os({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 ls={baseRetryDelayMs:1e3,maxRetryDelayMs:3e4,warningThreshold:3,criticalThreshold:5},rt={none:0,warning:1,critical:2};class ds{failCount=0;nextRetryAtMs=0;escalationLevel="none";options;constructor(e){this.options={...ls,...e}}registerFailure(){this.failCount+=1;const e=this.resolveEscalationLevel(this.failCount),n=rt[e]>rt[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=I("AutoConnectorManager: AutoConnectorRuntime"),hs=3e3,us=15e3;class gs{connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerRequester;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 ss({connectionManager:this.connectionManager,interval:e.options?.checkTelephonyRequestInterval??us}),this.pingServerRequester=new as({connectionManager:this.connectionManager}),this.registrationFailedOutOfCallSubscriber=new cs({connectionManager:this.connectionManager,callManager:e.callManager}),this.delayBetweenAttempts=new X.DelayRequester(e.options?.timeoutBetweenAttempts??hs),this.telephonyFailPolicy=new ds(e.options?.telephonyFailPolicy),this.attemptsState=new ns({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.pingServerRequester.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.pingServerRequester.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=T.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 Lt="Not ready for connection",wt=t=>t instanceof Error&&t.message===Lt,Es=()=>new Error(Lt),ms=async t=>typeof t=="function"?t():t,Ts=3;class ps{resolveParametersRequester=new K.CancelableRequest(ms);cancelableConnectWithRepeatedCalls;numberOfConnectionAttempts;dependencies;constructor(e,{numberOfConnectionAttempts:n=Ts}={}){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 K.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),g=i!=null&&!Wn(i);return c||g};return this.cancelableConnectWithRepeatedCalls=Me.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,iceServers:a,sessionTimers:o,registerExpires:c,connectionRecoveryMinInterval:g,connectionRecoveryMaxInterval:R,userAgent:f,displayName:P="",register:b=!1,extraHeaders:H=[]})=>{this.dependencies.getUa()&&await this.disconnect({cancelRequests:!1});const{ua:Z,helpers:ne}=this.dependencies.uaFactory.createUAWithConfiguration({user:e,password:n,sipServerIp:s,sipServerUrl:r,displayName:P,register:b,sessionTimers:o,registerExpires:c,connectionRecoveryMinInterval:g,connectionRecoveryMaxInterval:R,userAgent:f,remoteAddress:i,extraHeaders:H},this.dependencies.events);this.dependencies.setUa(Z),this.dependencies.setGetUri(ne.getUri),this.dependencies.setSocket(ne.socket);const be=Z.configuration.uri.user;return{ua:Z,configuration:{sipServerIp:s,sipServerUrl:r,remoteAddress:i,iceServers:a,displayName:P,authorizationUser:be,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=((g,R)=>{if(e.register===!0)return this.dependencies.registrationManager.subscribeToStartEvents(g,R);const f="connected",P=["disconnected"];return this.dependencies.events.on(f,g),P.forEach(b=>{this.dependencies.events.on(b,R)}),()=>{this.dependencies.events.off(f,g),P.forEach(b=>{this.dependencies.events.off(b,R)})}})(()=>{i?.(),n(e)},g=>{i?.(),s(g)}),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 l=(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))(l||{}),A=(t=>(t.LOG_TRANSITION="logTransition",t.LOG_STATE_CHANGE="logStateChange",t.SET_CONNECTION_CONFIGURATION="setConnectionConfiguration",t.CLEAR_CONNECTION_CONFIGURATION="clearConnectionConfiguration",t))(A||{}),m=(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))(m||{});const Gt={connectionConfiguration:void 0},it=I("ConnectionManager: createConnectionMachineSetup"),Ss=()=>T.setup({types:{context:Gt,events:{}},guards:{canAutoEstablish:({context:t})=>t.connectionConfiguration?.register!==!0},actions:{[A.SET_CONNECTION_CONFIGURATION]:T.assign(({event:t})=>({connectionConfiguration:{...t.configuration}})),[A.CLEAR_CONNECTION_CONFIGURATION]:T.assign(()=>({connectionConfiguration:void 0})),[A.LOG_TRANSITION]:(t,e)=>{it(`State transition: ${e.from} -> ${e.to} (${e.event})`)},[A.LOG_STATE_CHANGE]:(t,e)=>{it("ConnectionStateMachine state changed",e.state)}}}),Cs=()=>Ss().createMachine({id:"connection",initial:l.IDLE,context:Gt,states:{[l.IDLE]:{entry:[{type:A.LOG_STATE_CHANGE,params:{state:l.IDLE}},{type:A.CLEAR_CONNECTION_CONFIGURATION}],on:{[m.START_CONNECT]:{target:l.PREPARING,actions:{type:A.LOG_TRANSITION,params:{from:l.IDLE,to:l.PREPARING,event:m.START_CONNECT}}}}},[l.PREPARING]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.PREPARING}},on:{[m.START_UA]:{target:l.CONNECTING,actions:[A.SET_CONNECTION_CONFIGURATION,{type:A.LOG_TRANSITION,params:{from:l.PREPARING,to:l.CONNECTING,event:m.START_UA}}]},[m.UA_DISCONNECTED]:{target:l.DISCONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.PREPARING,to:l.DISCONNECTED,event:m.UA_DISCONNECTED}}}}},[l.CONNECTING]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.CONNECTING}},on:{[m.UA_CONNECTED]:{target:l.CONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTING,to:l.CONNECTED,event:m.UA_CONNECTED}}},[m.UA_REGISTERED]:{target:l.REGISTERED,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTING,to:l.REGISTERED,event:m.UA_REGISTERED}}},[m.START_DISCONNECT]:{target:l.DISCONNECTING,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTING,to:l.DISCONNECTING,event:m.START_DISCONNECT}}},[m.UA_DISCONNECTED]:{target:l.DISCONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTING,to:l.DISCONNECTED,event:m.UA_DISCONNECTED}}}}},[l.CONNECTED]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.CONNECTED}},always:{target:l.ESTABLISHED,guard:"canAutoEstablish",actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTED,to:l.ESTABLISHED,event:"always"}}},on:{[m.UA_REGISTERED]:{target:l.REGISTERED,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTED,to:l.REGISTERED,event:m.UA_REGISTERED}}},[m.START_DISCONNECT]:{target:l.DISCONNECTING,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTED,to:l.DISCONNECTING,event:m.START_DISCONNECT}}},[m.UA_DISCONNECTED]:{target:l.DISCONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.CONNECTED,to:l.DISCONNECTED,event:m.UA_DISCONNECTED}}}}},[l.REGISTERED]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.REGISTERED}},always:{target:l.ESTABLISHED,actions:{type:A.LOG_TRANSITION,params:{from:l.REGISTERED,to:l.ESTABLISHED,event:"always"}}},on:{[m.UA_UNREGISTERED]:{target:l.CONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.REGISTERED,to:l.CONNECTED,event:m.UA_UNREGISTERED}}},[m.START_DISCONNECT]:{target:l.DISCONNECTING,actions:{type:A.LOG_TRANSITION,params:{from:l.REGISTERED,to:l.DISCONNECTING,event:m.START_DISCONNECT}}},[m.UA_DISCONNECTED]:{target:l.DISCONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.REGISTERED,to:l.DISCONNECTED,event:m.UA_DISCONNECTED}}}}},[l.ESTABLISHED]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.ESTABLISHED}},on:{[m.START_DISCONNECT]:{target:l.DISCONNECTING,actions:{type:A.LOG_TRANSITION,params:{from:l.ESTABLISHED,to:l.DISCONNECTING,event:m.START_DISCONNECT}}},[m.UA_DISCONNECTED]:{target:l.DISCONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.ESTABLISHED,to:l.DISCONNECTED,event:m.UA_DISCONNECTED}}},[m.RESET]:{target:l.IDLE,actions:{type:A.LOG_TRANSITION,params:{from:l.ESTABLISHED,to:l.IDLE,event:m.RESET}}}}},[l.DISCONNECTING]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.DISCONNECTING}},on:{[m.UA_DISCONNECTED]:{target:l.DISCONNECTED,actions:{type:A.LOG_TRANSITION,params:{from:l.DISCONNECTING,to:l.DISCONNECTED,event:m.UA_DISCONNECTED}}}}},[l.DISCONNECTED]:{entry:{type:A.LOG_STATE_CHANGE,params:{state:l.DISCONNECTED}},on:{[m.RESET]:{target:l.IDLE,actions:[{type:A.LOG_TRANSITION,params:{from:l.DISCONNECTED,to:l.IDLE,event:m.RESET}}]},[m.START_CONNECT]:{target:l.PREPARING,actions:{type:A.LOG_TRANSITION,params:{from:l.DISCONNECTED,to:l.PREPARING,event:m.START_CONNECT}}},[m.UA_CONNECTING]:{target:l.CONNECTING,actions:{type:A.LOG_TRANSITION,params:{from:l.DISCONNECTED,to:l.CONNECTING,event:m.UA_CONNECTING}}}}}}}),Rs=Cs(),Ns=I("ConnectionManager: ConnectionStateMachine");class kt extends te{events;unsubscribeFromEvents;constructor(e){super(Rs),this.events=e,this.subscribeToEvents()}get isIdle(){return this.hasState(l.IDLE)}get isPreparing(){return this.hasState(l.PREPARING)}get isConnecting(){return this.hasState(l.CONNECTING)}get isConnected(){return this.hasState(l.CONNECTED)}get isRegistered(){return this.hasState(l.REGISTERED)}get isEstablished(){return this.hasState(l.ESTABLISHED)}get isDisconnecting(){return this.hasState(l.DISCONNECTING)}get isDisconnected(){return this.hasState(l.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:m.START_CONNECT})};toStartUa=e=>{this.sendEvent({type:m.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)){Ns(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartDisconnect=()=>{this.sendEvent({type:m.START_DISCONNECT})};toConnecting=()=>{this.sendEvent({type:m.UA_CONNECTING})};toConnected=()=>{this.sendEvent({type:m.UA_CONNECTED})};toRegistered=()=>{this.sendEvent({type:m.UA_REGISTERED})};toUnregistered=()=>{this.sendEvent({type:m.UA_UNREGISTERED})};toDisconnected=()=>{this.sendEvent({type:m.UA_DISCONNECTED})};toIdle=()=>{this.sendEvent({type:m.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 Ft=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],As=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-success","connect-parameters-resolve-failed","connected-with-configuration"],Ut=[...Ft,...As],Bt=()=>new _.TypedEvents(Ut),Is=I("ConnectionManager: RegistrationManager");class fs{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){Is("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)})}}}const vs=1e4;class Ms{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,n,s,r){const i=this.getUaProtected();return new Promise((a,o)=>{try{i.sendOptions(e,n,{extraHeaders:s,eventHandlers:{succeeded:()=>{a()},failed:o},timeout:r})}catch(c){o(c)}})}async ping(e,n){const r=this.getUaProtected().configuration.uri;return this.sendOptions(r,e,n,vs)}async checkTelephony({userAgent:e,displayName:n,sipServerIp:s,sipServerUrl:r,remoteAddress:i,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:g}=this.uaFactory.createConfiguration({sipServerUrl:r,displayName:n,userAgent:e,sipServerIp:s}),R=this.uaFactory.createUA({...g,remoteAddress:i,extraHeaders:a}),f=()=>{const b=new Error("Telephony is not available");c(b)};R.once("disconnected",f);const P=()=>{R.removeAllListeners(),R.once("disconnected",()=>{o()}),R.stop()};R.once("connected",P),R.start()})}}function Os(t){return e=>`sip:${e}@${t}`}const _s=(t,e)=>()=>Math.floor(Math.random()*(e-t))+t,bs=t=>t.trim().replaceAll(" ","_"),ys=_s(1e5,99999999),Ps=t=>{const e=[];return t!==void 0&&t!==""&&e.push(`X-Vinteo-Remote: ${t}`),e};class ae{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():`${ys()}`}static buildExtraHeaders(e,n){const s=e!==void 0&&e!==""?Ps(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:g=2,connectionRecoveryMaxInterval:R=6,userAgent:f}){ae.validateParametersConnection({register:a,password:n,user:e,sipServerIp:i,sipServerUrl:s});const P=ae.resolveAuthorizationUser(a,e),b=Os(i),H=b(P),B=new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);return{configuration:{password:n,register:a,uri:H,display_name:bs(r),user_agent:f,sockets:[B],session_timers:o,register_expires:c,connection_recovery_min_interval:g,connection_recovery_max_interval:R},helpers:{socket:B,getUri:b}}}createUA({remoteAddress:e,extraHeaders:n,...s}){const r=new this.JsSIP.UA(s),i=ae.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=Ft.find(g=>g===o);c&&i.on(c,a)}),{ua:i,helpers:r}}}const Ds=I("ConnectionManager");class Ls extends _.EventEmitterProxy{stateMachine;ua;socket;uaFactory;registrationManager;connectionFlow;sipOperations;constructor({JsSIP:e},{numberOfConnectionAttempts:n}={}){super(Bt()),this.uaFactory=new ae(e),this.registrationManager=new fs({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new kt(this.events),this.sipOperations=new Ms({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new ps({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 ae.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.stateMachine.isRegisterEnabled()}connect=async(e,n)=>this.disconnect().catch(s=>{Ds("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 Es();return this.connectionFlow.connect(e,n).catch(async r=>{const i=r;return this.disconnect().then(()=>{throw i}).catch(()=>{throw i})})}}class ws{connectionManager;stackPromises=Oe.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 z=t=>{if(t!==null&&typeof t=="object"&&"error"in t)return t.error},y=I("AutoConnectorManager: createAutoConnectorMachineSetup"),at=t=>t.parameters,Gs=t=>T.setup({types:{context:{},events:{}},actors:{stopConnectionFlow:T.fromPromise(async()=>{y("stopConnectionFlow"),await t.stopConnectionFlow()}),connect:T.fromPromise(async({input:e})=>{if(y("connect",e),!e)throw new Error("Auto connector parameters are missing in attemptingConnect state");await t.connect(e)}),waitBeforeRetry:T.fromPromise(async()=>{y("waitBeforeRetry"),await t.delayBetweenAttempts()})},guards:{shouldDisconnectBeforeAttempt:()=>{const e=t.shouldDisconnectBeforeAttempt();return y("shouldDisconnectBeforeAttempt:",e),e},shouldGoIdleAfterDisconnect:({context:e})=>{const n=e.afterDisconnect==="idle";return y("shouldGoIdleAfterDisconnect:",n),n},shouldAttemptAfterDisconnect:({context:e})=>{const n=e.afterDisconnect==="attempt";return y("shouldAttemptAfterDisconnect:",n),n},isLimitReached:()=>{const e=t.hasLimitReached();return y("isLimitReached:",e),e},isNotReadyForConnection:({event:e})=>{const n=wt(z(e));return y("isNotReadyForConnection:",n),n},isNoRetryPolicy:({event:e})=>{const n=!t.canRetryOnError(z(e));return y("isNoRetryPolicy:",n),n},isNotActualPromise:({event:e})=>{const n=Oe.isPromiseIsNotActualError(z(e));return y("isNotActualPromise:",n),n},isWaitRetryCancelled:({event:e})=>{const n=z(e),s=K.isCanceledError(n)||X.hasCanceledError(n);return y("isWaitRetryCancelled:",s),s}},actions:{logRestartFailed:({event:e})=>{y("auto connector failed to restart connection attempts:",z(e))},assignRestart:T.assign(({event:e})=>({parameters:e.parameters,afterDisconnect:"attempt",stopReason:void 0,lastError:void 0})),assignStop:T.assign({afterDisconnect:"idle",stopReason:()=>{},lastError:()=>{}}),entryAttemptingGate:()=>{y("entryAttemptingGate"),t.beforeAttempt()},entryAttemptingConnect:()=>{y("entryAttemptingConnect"),t.beforeConnectAttempt()},onLimitReachedTransition:({context:e})=>{y("onLimitReachedTransition"),t.onLimitReached(at(e))},onConnectDone:({context:e})=>{y("onConnectDone"),t.onConnectSucceeded(at(e))},assignHaltedError:T.assign({stopReason:()=>"halted",lastError:({event:e})=>{const n=z(e);return y("assignHaltedError",n),n}}),assignCancelledNotActualError:T.assign({stopReason:()=>"cancelled",lastError:({event:e})=>{const n=z(e);return y("assignCancelledNotActualError",n),n}}),assignWaitRetryCancelledError:T.assign({stopReason:()=>"cancelled",lastError:({event:e})=>{const n=z(e);return y("assignWaitRetryCancelledError",n),n}}),assignWaitRetryFailedError:T.assign({stopReason:()=>"failed",lastError:({event:e})=>{const n=z(e);return y("assignWaitRetryFailedError",n),n}}),emitTerminalOutcome:({context:e})=>{y("emitTerminalOutcome"),t.emitTerminalOutcome({stopReason:e.stopReason,lastError:e.lastError})},onTelephonyStillConnected:()=>{y("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 ks=()=>({parameters:void 0,afterDisconnect:"idle",stopReason:void 0,lastError:void 0}),ce=()=>({"AUTO.STOP":{target:O.DISCONNECTING,actions:"assignStop"},"AUTO.RESTART":{target:O.DISCONNECTING,actions:"assignRestart"}}),Fs=t=>Gs(t).createMachine({id:"autoConnector",initial:O.IDLE,context:ks,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:ce()},[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:ce()},[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:ce()},[O.CONNECTED_MONITORING]:{on:ce()},[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:ce()}}}),Us=I("AutoConnectorManager: AutoConnectorStateMachine");class Bs extends te{constructor(e){super(e)}send(e){if(!this.actor.getSnapshot().can(e)){Us(`[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")}isInConnectedMonitoringState(){return this.state===O.CONNECTED_MONITORING}isInWaitingBeforeRetryState(){return this.state===O.WAITING_BEFORE_RETRY}}const $t=t=>new Bs(Fs(t)),$s=new Set([401,403]),xs=t=>typeof t=="object"&&t!==null&&"response"in t,qs=t=>{if(!xs(t))return!1;const e=t.response?.status_code;return typeof e=="number"&&$s.has(e)},Vs=t=>!qs(t),Hs=t=>{if(!(typeof window>"u"))return window},Ws=t=>{if(!(typeof navigator>"u"))return navigator},Qs=t=>{const e=Hs(),n=Ws();if(!e)return;let s=[];const r=()=>{s.forEach(i=>{i()}),s=[]};return{subscribe:i=>{r();const a=()=>{i.onOnline()},o=()=>{i.onOffline()},c=()=>{i.onChange()};e.addEventListener("online",a),e.addEventListener("offline",o);const g=n?.connection;g?.addEventListener("change",c),s=[()=>{e.removeEventListener("online",a)},()=>{e.removeEventListener("offline",o)},()=>{g?.removeEventListener("change",c)}]},unsubscribe:r}},Ys="Failed to reconnect",ot=t=>t instanceof Error?t:new Error(Ys),js=t=>{const e=s=>t.baseCanRetryOnError(s)?t.canRetryOnError?.(s)??!0:!1,n=({stopReason:s,lastError:r})=>s==="cancelled"&&!Oe.isPromiseIsNotActualError(r)||s==="failed"?ot(r):r;return{canRetryOnError:e,shouldDisconnectBeforeAttempt:()=>t.runtime.shouldDisconnectBeforeAttempt(),stopConnectionFlow:async()=>{await t.runtime.stopConnectionFlow()},connect:async s=>{await t.runtime.connect(s)},delayBetweenAttempts:async()=>{await t.runtime.delayBeforeRetry()},hasLimitReached:()=>t.runtime.hasLimitReached(),beforeAttempt:()=>{t.runtime.beforeAttempt()},beforeConnectAttempt:()=>{t.runtime.beforeConnectAttempt()},onLimitReached:s=>{t.runtime.onLimitReached(s)},onConnectSucceeded:s=>{t.runtime.onConnectSucceeded(s)},emitTerminalOutcome:({stopReason:s,lastError:r})=>{t.runtime.emitTerminalOutcome({stopReason:s,lastError:n({stopReason:s,lastError:r})})},onTelephonyStillConnected:()=>{t.runtime.onTelephonyStillConnected()}}},xt=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts","telephony-check-failure","telephony-check-escalated"],zs=()=>new _.TypedEvents(xt),J=I("AutoConnectorManager: NetworkEventsReconnector"),Js=2e3,ct="probe",Ks="network-online",Xs="network-change";class Zs{subscriber;offlineGraceMs;onChangePolicy;onOnlinePolicy;probe;requestReconnect;stopConnection;parameters;offlineTimer;isSubscribed=!1;isProbeInFlight=!1;constructor({subscriber:e,offlineGraceMs:n,onChangePolicy:s,onOnlinePolicy:r,probe:i,requestReconnect:a,stopConnection:o}){this.subscriber=e,this.offlineGraceMs=n??Js,this.onChangePolicy=s??ct,this.onOnlinePolicy=r??ct,this.probe=i,this.requestReconnect=a,this.stopConnection=o}start(e){this.parameters=e,!this.isSubscribed&&(this.subscriber.subscribe({onChange:this.handleChange,onOnline:this.handleOnline,onOffline:this.handleOffline}),this.isSubscribed=!0)}setParameters(e){this.parameters=e}stop(){this.cancelOfflineTimer(),this.isSubscribed&&(this.subscriber.unsubscribe(),this.isSubscribed=!1,this.parameters=void 0)}handleOnline=()=>{J("network online",{policy:this.onOnlinePolicy}),this.cancelOfflineTimer(),this.applyPolicy(this.onOnlinePolicy,Ks)};handleChange=()=>{J("network change",{policy:this.onChangePolicy}),this.applyPolicy(this.onChangePolicy,Xs)};handleOffline=()=>{J("network offline, scheduling disconnect",{graceMs:this.offlineGraceMs}),this.cancelOfflineTimer(),this.offlineTimer=setTimeout(()=>{this.offlineTimer=void 0,J("network offline grace window elapsed, stopping active connection"),this.stopConnection()},this.offlineGraceMs)};applyPolicy(e,n){if(e==="ignore"){J("policy=ignore, skipping",{reason:n});return}if(e==="reconnect"||!this.probe){this.requestReconnectIfAvailable(n);return}if(this.isProbeInFlight){J("probe already in flight, skipping duplicate",{reason:n});return}this.isProbeInFlight=!0,this.probe().then(s=>{J("probe result",{reason:n,isReachable:s}),s||this.requestReconnectIfAvailable(n)}).catch(s=>{J("probe threw, requesting reconnect",{reason:n,error:s}),this.requestReconnectIfAvailable(n)}).finally(()=>{this.isProbeInFlight=!1})}requestReconnectIfAvailable(e){if(!this.parameters){J("skipping reconnect: no parameters",{reason:e});return}this.requestReconnect(this.parameters,e)}cancelOfflineTimer(){this.offlineTimer!==void 0&&(clearTimeout(this.offlineTimer),this.offlineTimer=void 0)}}const ee={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",NETWORK_ONLINE:"network-online",NETWORK_CHANGE:"network-change"},er={[ee.START]:0,[ee.TELEPHONY_DISCONNECTED]:1,[ee.TELEPHONY_CHECK_FAILED]:1,[ee.REGISTRATION_FAILED_OUT_OF_CALL]:3,[ee.MANUAL_RESTART]:4,[ee.NETWORK_ONLINE]:4,[ee.NETWORK_CHANGE]:4},lt=t=>er[t];class tr{generation=0;lastRequest;coalesceWindowMs;constructor({coalesceWindowMs:e}){this.coalesceWindowMs=e}register(e){const n=Date.now(),s=lt(e),{lastRequest:r}=this;if(r!==void 0&&n-r.timestamp<this.coalesceWindowMs){const a=lt(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 nr=250,sr={LIMIT_REACHED:"Limit reached"},G=I("AutoConnectorManager"),rr="start",ir="manual-restart";class ar extends _.EventEmitterProxy{stateMachine;runtime;connectionManager;reconnectCoalescer=new tr({coalesceWindowMs:nr});networkEventsReconnector;constructor({connectionQueueManager:e,connectionManager:n,callManager:s},r){super(zs()),this.connectionManager=n,this.runtime=new gs({connectionManager:n,connectionQueueManager:e,callManager:s,options:r,emitters:{emitBeforeAttempt:()=>{this.events.trigger("before-attempt",{})},emitLimitReachedAttempts:()=>{this.events.trigger("limit-reached-attempts",new Error(sr.LIMIT_REACHED))},emitSuccess:()=>{G("handleSucceededAttempt"),this.events.trigger("success")},emitStopAttemptsByError:a=>{this.events.trigger("stop-attempts-by-error",a)},emitCancelledAttempts:a=>{this.events.trigger("cancelled-attempts",a)},emitFailedAllAttempts:a=>{this.events.trigger("failed-all-attempts",a)},emitTelephonyCheckFailure:a=>{this.events.trigger("telephony-check-failure",a)},emitTelephonyCheckEscalated:a=>{this.events.trigger("telephony-check-escalated",a)},emitStatusChange:({isInProgress:a})=>{this.events.trigger("changed-attempt-status",{isInProgress:a})}},reconnectActions:{requestReconnect:this.requestReconnect,notifyTelephonyStillConnected:()=>{this.stateMachine.toTelephonyResultStillConnected()}}}),this.stateMachine=$t(js({baseCanRetryOnError:Vs,runtime:this.runtime,canRetryOnError:r?.canRetryOnError}));const i=r?.networkEventsSubscriber??Qs();i&&(this.networkEventsReconnector=new Zs({subscriber:i,offlineGraceMs:r?.offlineGraceMs,onChangePolicy:r?.onNetworkChangePolicy,onOnlinePolicy:r?.onNetworkOnlinePolicy,probe:this.probeServerReachability,requestReconnect:this.requestReconnect,stopConnection:()=>{this.stateMachine.toStop()}}))}async start(e){return G("auto connector start"),this.networkEventsReconnector?.start(e),this.requestReconnect(e,rr)?new Promise(s=>{const r=this.events.onceRace(["success","failed-all-attempts","stop-attempts-by-error","limit-reached-attempts"],(i,a)=>{if(r(),a==="success"){s({isSuccess:!0,reason:"started"});return}if(a==="failed-all-attempts"){s({isSuccess:!1,reason:"failed-all-attempts",error:i});return}if(a==="stop-attempts-by-error"){s({isSuccess:!1,reason:"stop-attempts-by-error",error:i});return}s({isSuccess:!1,reason:"limit-reached-attempts",error:i})})}):{isSuccess:!1,reason:"coalesced"}}restart(){G("auto connector restart");const{parameters:e}=this.stateMachine.context;if(!e){G("auto connector restart skipped: no parameters in context");return}this.requestReconnect(e,ir)}stop(){G("auto connector stop"),this.networkEventsReconnector?.stop(),this.resetReconnectCoalescingState(),this.stateMachine.toStop()}cancelPendingRetry(){this.runtime.cancelPendingRetry()}requestReconnect=(e,n)=>{const s=this.shouldRequestReconnect(n);return G("auto connector requestReconnect",{isAvailableToRestart:s,reason:n}),s?(this.networkEventsReconnector?.setParameters(e),this.stateMachine.toRestart(e),!0):!1};probeServerReachability=async()=>{if(this.stateMachine.isInConnectedMonitoringState()){G("probeServerReachability: isInConnectedMonitoringState");try{return await this.connectionManager.ping(),!0}catch(e){return G("probeServerReachability: ping failed",e),!1}}if(this.stateMachine.isInWaitingBeforeRetryState()){G("probeServerReachability: isInWaitingBeforeRetryState");const{parameters:e}=this.stateMachine.context;try{const n=await e.getParameters();return await this.connectionManager.checkTelephony(n),!1}catch(n){return G("probeServerReachability: checkTelephony failed",n),!0}}return G("probeServerReachability: default return false"),!1};shouldRequestReconnect(e){const n=this.reconnectCoalescer.register(e);return n.shouldRequest?(G(`auto connector reconnect requested: ${e}`,{state:String(this.stateMachine.state),generation:n.generation}),!0):(G(`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 dt=0,or=0;class cr{countInner=dt;initialCount=dt;limitInner;isInProgress=!1;onStatusChange;constructor(e){this.limitInner=e.limit,this.onStatusChange=e.onStatusChange}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.limitInner===or?!1: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.countInner+=1}reset(){this.countInner=this.initialCount,this.finishAttempt()}}const ht=1,lr=t=>t<ht?ht:t,dr=(t,e)=>{const{baseBackoffMs:n,maxBackoffMs:s,backoffFactor:r}=e,i=lr(t),a=n*r**(i-1);return Math.min(s,a)},hr=(t,e,n)=>{if(e==="none")return t;if(e==="full")return n()*t;const s=t/2;return s+n()*s},ur=(t,e,n=Math.random)=>{const s=dr(t,e);return hr(s,e.jitter,n)},gr=new Set([U.C.causes.CONNECTION_ERROR,U.C.causes.REQUEST_TIMEOUT,U.C.causes.RTP_TIMEOUT,U.C.causes.ADDRESS_INCOMPLETE]),Er=t=>{const{cause:e,originator:n}=t;return n==="local"?!1:!!(gr.has(e)||e===U.C.causes.INTERNAL_ERROR&&n==="system")},mr=t=>t??Er,ut=I("CallReconnectRuntime"),se={maxAttempts:5,baseBackoffMs:1e3,maxBackoffMs:3e4,backoffFactor:2,jitter:"equal",waitSignalingTimeoutMs:2e4},Tr=t=>({maxAttempts:t?.maxAttempts??se.maxAttempts,baseBackoffMs:t?.baseBackoffMs??se.baseBackoffMs,maxBackoffMs:t?.maxBackoffMs??se.maxBackoffMs,backoffFactor:t?.backoffFactor??se.backoffFactor,jitter:t?.jitter??se.jitter,waitSignalingTimeoutMs:t?.waitSignalingTimeoutMs??se.waitSignalingTimeoutMs}),pr=t=>!0;class Sr{resolvedOptions;callManager;connectionManager;attemptsState;delayRequester;performCall;isNetworkFailureFn;canRetryOnErrorFn;unsubscribeConnectionWait;constructor(e){this.resolvedOptions=Tr(e.options),this.callManager=e.callManager,this.connectionManager=e.connectionManager,this.isNetworkFailureFn=mr(e.options?.isNetworkFailure),this.canRetryOnErrorFn=e.options?.canRetryOnError??pr,this.delayRequester=new X.DelayRequester(this.resolvedOptions.baseBackoffMs),this.performCall=new K.CancelableRequest(async n=>{const s=await n.getCallParameters();await this.callManager.startCall(this.connectionManager.getUaProtected(),this.connectionManager.getUri.bind(this.connectionManager),s)}),this.attemptsState=new cr({limit:this.resolvedOptions.maxAttempts,onStatusChange:({isInProgress:n})=>{e.emitters.emitStatusChange({isReconnecting:n})}})}isNetworkFailure(e){return this.isNetworkFailureFn(e)}canRetryOnError(e){return this.canRetryOnErrorFn(e)}isSignalingReady(){return this.connectionManager.isRegistered}hasLimitReached(){return this.attemptsState.hasLimitReached()}computeNextDelayMs(e){return ur(e,{baseBackoffMs:this.resolvedOptions.baseBackoffMs,maxBackoffMs:this.resolvedOptions.maxBackoffMs,backoffFactor:this.resolvedOptions.backoffFactor,jitter:this.resolvedOptions.jitter})}async delayBeforeAttempt(e){ut("delayBeforeAttempt",e),await this.delayRequester.request(e)}async waitSignalingReady(){if(this.connectionManager.isRegistered)return;const e=this.resolvedOptions.waitSignalingTimeoutMs;await new Promise((n,s)=>{let r,i;const a=()=>{r!==void 0&&globalThis.clearTimeout(r),i!==void 0&&(this.connectionManager.off("connected",i),this.connectionManager.off("registered",i)),this.unsubscribeConnectionWait=void 0};i=()=>{a(),n()},r=globalThis.setTimeout(()=>{a(),s(new Error(`Wait signaling ready timeout after ${e}ms`))},e),this.unsubscribeConnectionWait=a,this.connectionManager.on("connected",i),this.connectionManager.on("registered",i)})}async performAttempt(e){await this.performCall.request(e)}registerAttemptStart(){this.attemptsState.increment(),this.attemptsState.startAttempt()}registerAttemptFinish(){this.attemptsState.finishAttempt()}resetAttemptsState(){this.attemptsState.reset()}cancelAll(){ut("cancelAll"),this.delayRequester.cancelRequest(),this.performCall.cancelRequest(),this.unsubscribeConnectionWait?.(),this.unsubscribeConnectionWait=void 0}getWaitSignalingTimeoutMs(){return this.resolvedOptions.waitSignalingTimeoutMs}}const pe=t=>{if(t!==null&&typeof t=="object"&&"error"in t)return t.error},ye=I("CallReconnectMachine"),Cr=t=>t.parameters,Rr=t=>T.setup({types:{context:{},events:{}},actors:{delayBeforeAttempt:T.fromPromise(async({input:e})=>{ye("delayBeforeAttempt",e),await t.delayBeforeAttempt(e)}),waitSignalingReady:T.fromPromise(async()=>{ye("waitSignalingReady"),await t.waitSignalingReady()}),performAttempt:T.fromPromise(async({input:e})=>{if(ye("performAttempt"),!e)throw new Error("CallReconnect parameters missing in attempting state");await t.performAttempt(e)})},guards:{isNetworkFailure:({event:e})=>{const n=e;return t.isNetworkFailure(n.event)},isLimitReached:()=>t.hasLimitReached(),isSignalingReady:()=>t.isSignalingReady(),isNoRetryPolicy:({event:e})=>!t.canRetryOnError(pe(e)),isAttemptCancelled:({event:e})=>{const n=pe(e);return K.isCanceledError(n)||X.hasCanceledError(n)}},actions:{assignArm:T.assign(({event:e})=>({parameters:e.parameters,attempt:0,nextDelayMs:0,lastError:void 0,lastFailureCause:void 0,cancelledReason:void 0})),assignDisarm:T.assign(({event:e})=>({parameters:void 0,attempt:0,nextDelayMs:0,lastError:void 0,lastFailureCause:void 0,cancelledReason:e.reason??"disarm"})),assignFailureDetected:T.assign(({event:e})=>({lastFailureCause:e.event.cause})),assignNextDelay:T.assign(({context:e})=>{const n=e.attempt+1;return{nextDelayMs:t.computeNextDelayMs(n)}}),assignIncrementAttempt:T.assign(({context:e})=>({attempt:e.attempt+1})),assignResetAttempt:T.assign({attempt:()=>0,nextDelayMs:()=>0,lastError:()=>{},lastFailureCause:()=>{}}),assignAttemptError:T.assign({lastError:({event:e})=>pe(e)}),emitArmedAction:()=>{t.emitArmed()},emitDisarmedAction:({context:e})=>{t.emitDisarmed();const{cancelledReason:n}=e;n!==void 0&&t.emitCancelled({reason:n})},emitFailureDetectedAction:({context:e,event:n})=>{const s=n;t.emitFailureDetected({cause:s.event.cause,originator:s.event.originator,attempt:e.attempt})},emitAttemptScheduledAction:({context:e})=>{t.emitAttemptScheduled({attempt:e.attempt+1,delayMs:e.nextDelayMs})},emitAttemptStartedAction:({context:e})=>{t.emitAttemptStarted({attempt:e.attempt})},emitAttemptSucceededAction:({context:e})=>{t.emitAttemptSucceeded({attempt:e.attempt})},emitAttemptFailedAction:({context:e,event:n})=>{t.emitAttemptFailed({attempt:e.attempt,error:pe(n)})},emitWaitingSignalingAction:()=>{t.emitWaitingSignaling({timeoutMs:t.getWaitSignalingTimeoutMs()})},emitLimitReachedAction:({context:e})=>{t.emitLimitReached({attempts:e.attempt})},registerAttemptStart:()=>{t.registerAttemptStart()},registerAttemptFinish:()=>{t.registerAttemptFinish()},resetAttemptsState:()=>{t.resetAttemptsState()},cancelAll:()=>{t.cancelAll()}}});var v=(t=>(t.IDLE="idle",t.ARMED="armed",t.EVALUATING="evaluating",t.BACKOFF="backoff",t.WAITING_SIGNALING="waitingSignaling",t.ATTEMPTING="attempting",t.LIMIT_REACHED="limitReached",t.ERROR_TERMINAL="errorTerminal",t))(v||{});const Nr=()=>({parameters:void 0,attempt:0,nextDelayMs:0,lastError:void 0,lastFailureCause:void 0,cancelledReason:void 0}),Ar=t=>Rr(t).createMachine({id:"callReconnect",initial:v.IDLE,context:Nr,on:{"RECONNECT.ARM":{target:`.${v.ARMED}`,actions:["cancelAll","resetAttemptsState","assignArm","emitArmedAction"]},"RECONNECT.DISARM":{target:`.${v.IDLE}`,actions:["cancelAll","resetAttemptsState","registerAttemptFinish","assignDisarm","emitDisarmedAction"]}},states:{[v.IDLE]:{on:{"RECONNECT.DISARM":{target:v.IDLE}}},[v.ARMED]:{on:{"CALL.FAILED":{guard:"isNetworkFailure",target:v.EVALUATING,actions:["assignFailureDetected","emitFailureDetectedAction"]},"CALL.ENDED":{target:v.IDLE,actions:["cancelAll","resetAttemptsState","assignDisarm","emitDisarmedAction"]}}},[v.EVALUATING]:{always:[{guard:"isLimitReached",target:v.LIMIT_REACHED,actions:["emitLimitReachedAction"]},{guard:"isSignalingReady",target:v.BACKOFF,actions:["assignNextDelay","emitAttemptScheduledAction"]},{target:v.WAITING_SIGNALING,actions:["emitWaitingSignalingAction"]}]},[v.BACKOFF]:{invoke:{id:"delayBeforeAttempt",src:"delayBeforeAttempt",input:({context:e})=>e.nextDelayMs,onDone:{target:v.ATTEMPTING},onError:{target:v.ARMED}},on:{"CONN.DISCONNECTED":{target:v.WAITING_SIGNALING,actions:["emitWaitingSignalingAction"]}}},[v.WAITING_SIGNALING]:{invoke:{id:"waitSignalingReady",src:"waitSignalingReady",onDone:{target:v.BACKOFF,actions:["assignNextDelay","emitAttemptScheduledAction"]},onError:[{guard:"isAttemptCancelled",target:v.ARMED},{target:v.ERROR_TERMINAL,actions:"assignAttemptError"}]},on:{"CONN.CONNECTED":{target:v.BACKOFF,actions:["assignNextDelay","emitAttemptScheduledAction"]}}},[v.ATTEMPTING]:{entry:["assignIncrementAttempt","registerAttemptStart","emitAttemptStartedAction"],invoke:{id:"performAttempt",src:"performAttempt",input:({context:e})=>Cr(e),onDone:{target:v.ARMED,actions:["registerAttemptFinish","assignResetAttempt","resetAttemptsState","emitAttemptSucceededAction"]},onError:[{guard:"isAttemptCancelled",target:v.ARMED,actions:["registerAttemptFinish"]},{guard:"isNoRetryPolicy",target:v.ERROR_TERMINAL,actions:["registerAttemptFinish","emitAttemptFailedAction","assignAttemptError"]},{target:v.EVALUATING,actions:["registerAttemptFinish","emitAttemptFailedAction"]}]}},[v.LIMIT_REACHED]:{on:{"RECONNECT.FORCE":{target:v.EVALUATING,actions:["resetAttemptsState","assignResetAttempt"]}}},[v.ERROR_TERMINAL]:{on:{"RECONNECT.FORCE":{target:v.EVALUATING,actions:["resetAttemptsState","assignResetAttempt"]}}}}}),Ir=I("CallReconnectStateMachine");class fr extends te{constructor(e){super(e)}send(e){if(!this.actor.getSnapshot().can(e)){Ir(`[CallReconnectStateMachine] Invalid transition: ${e.type} from ${String(this.state)}. Event cannot be processed in current state.`);return}super.send(e)}}const qt=t=>new fr(Ar(t)),vr=t=>{const{runtime:e,events:n}=t;return{isNetworkFailure:s=>e.isNetworkFailure(s),canRetryOnError:s=>e.canRetryOnError(s),isSignalingReady:()=>e.isSignalingReady(),hasLimitReached:()=>e.hasLimitReached(),computeNextDelayMs:s=>e.computeNextDelayMs(s),delayBeforeAttempt:async s=>{await e.delayBeforeAttempt(s)},waitSignalingReady:async()=>{await e.waitSignalingReady()},performAttempt:async s=>{await e.performAttempt(s)},registerAttemptStart:()=>{e.registerAttemptStart()},registerAttemptFinish:()=>{e.registerAttemptFinish()},resetAttemptsState:()=>{e.resetAttemptsState()},emitArmed:()=>{n.trigger("armed",{})},emitDisarmed:()=>{n.trigger("disarmed",{})},emitFailureDetected:s=>{n.trigger("failure-detected",s)},emitAttemptScheduled:s=>{n.trigger("attempt-scheduled",s)},emitAttemptStarted:s=>{n.trigger("attempt-started",s)},emitAttemptSucceeded:s=>{n.trigger("attempt-succeeded",s)},emitAttemptFailed:s=>{n.trigger("attempt-failed",s)},emitWaitingSignaling:s=>{n.trigger("waiting-signaling",s)},emitLimitReached:s=>{n.trigger("limit-reached",s)},emitCancelled:s=>{n.trigger("cancelled",s)},cancelAll:()=>{e.cancelAll()},getWaitSignalingTimeoutMs:()=>e.getWaitSignalingTimeoutMs()}},Ye=["armed","disarmed","failure-detected","attempt-scheduled","attempt-started","attempt-succeeded","attempt-failed","waiting-signaling","limit-reached","cancelled","status-changed"],Mr=()=>new _.TypedEvents(Ye),Pe=I("CallReconnectManager");class Or extends _.EventEmitterProxy{stateMachine;runtime;callManager;connectionManager;unsubscribes=[];constructor({callManager:e,connectionManager:n},s){super(Mr()),this.callManager=e,this.connectionManager=n,this.runtime=new Sr({callManager:e,connectionManager:n,options:s,emitters:{emitStatusChange:r=>{this.events.trigger("status-changed",r)}}}),this.stateMachine=qt(vr({runtime:this.runtime,events:this.events})),this.subscribeToManagers()}get isReconnecting(){return this.stateMachine.state!==v.IDLE}get state(){return this.stateMachine.state}arm(e){if(Pe("arm"),this.callManager.hasSpectator()){this.events.trigger("cancelled",{reason:"spectator-role"});return}this.stateMachine.send({type:"RECONNECT.ARM",parameters:e})}disarm(e="disarm"){Pe("disarm",e),this.stateMachine.send({type:"RECONNECT.DISARM",reason:e})}forceReconnect(){Pe("forceReconnect"),this.stateMachine.send({type:"RECONNECT.FORCE"})}cancelCurrentAttempt(){this.runtime.cancelAll()}stop(){this.unsubscribes.forEach(e=>{e()}),this.unsubscribes.length=0,this.runtime.cancelAll(),this.stateMachine.stop()}subscribeToManagers(){const e=o=>{if(this.runtime.isNetworkFailure(o)){this.stateMachine.send({type:"CALL.FAILED",event:o});return}this.stateMachine.send({type:"CALL.ENDED",event:o})},n=o=>{e(o)},s=o=>{e(o)},r=()=>{this.stateMachine.send({type:"CALL.ENDED"})},i=()=>{this.stateMachine.send({type:"CONN.CONNECTED"})},a=()=>{this.stateMachine.send({type:"CONN.DISCONNECTED"})};this.callManager.on("failed",n),this.callManager.on("end-call",r),this.callManager.on("ended",s),this.connectionManager.on("connected",i),this.connectionManager.on("registered",i),this.connectionManager.on("disconnected",a),this.unsubscribes.push(()=>{this.callManager.off("failed",n)},()=>{this.callManager.off("end-call",r)},()=>{this.callManager.off("ended",s)},()=>{this.connectionManager.off("connected",i)},()=>{this.connectionManager.off("registered",i)},()=>{this.connectionManager.off("disconnected",a)})}}const _r="incomingCall",br="declinedIncomingCall",yr="failedIncomingCall",Pr="terminatedIncomingCall",Vt="connecting",Dr="connected",Lr="disconnected",wr="newRTCSession",Gr="registered",kr="unregistered",Fr="registrationFailed",Ur="newMessage",Br="sipEvent",$r="availableSecondRemoteStream",xr="notAvailableSecondRemoteStream",qr="mustStopPresentation",Vr="enterRoom",Hr="useLicense",Wr="peerconnection:confirmed",Qr="peerconnection:ontrack",Yr="channels",jr="channels:notify",zr="ended:fromserver",Jr="main-cam-control",Kr="admin:stop-main-cam",Xr="admin:start-main-cam",Zr="admin:stop-mic",ei="admin:start-mic",ti="admin:force-sync-media-state",ni="participant:added-to-list-moderators",si="participant:removed-from-list-moderators",ri="participant:move-request-to-stream",ii="participant:move-request-to-spectators",ai="participant:move-request-to-participants",oi="participation:accepting-word-request",ci="participation:cancelling-word-request",li="webcast:started",di="webcast:stopped",hi="account:changed",ui="account:deleted",gi="conference:participant-token-issued",Ei="ended",mi="sending",Ti="reinvite",pi="replaces",Si="refer",Ci="progress",Ri="accepted",Ni="confirmed",Ai="peerconnection",Ii="failed",fi="muted",vi="unmuted",Mi="newDTMF",Oi="newInfo",_i="hold",bi="unhold",yi="update",Pi="sdp",Di="icecandidate",Li="getusermediafailed",wi="peerconnection:createofferfailed",Gi="peerconnection:createanswerfailed",ki="peerconnection:setlocaldescriptionfailed",Fi="peerconnection:setremotedescriptionfailed",Ui="presentation:start",Bi="presentation:started",$i="presentation:end",xi="presentation:ended",qi="presentation:failed",Vi=[_r,br,Pr,yr,oi,ci,ri,jr,gi,hi,ui,li,di,ni,si],Ht=[Vt,Dr,Lr,wr,Gr,kr,Fr,Ur,Br],Hi=[$r,xr,qr,Vr,Hr,Wr,Qr,Yr,zr,Jr,Xr,Kr,Zr,ei,ti,ii,ai],xe=[Ei,Vt,mi,Ti,pi,Si,Ci,Ri,Ni,Ai,Ii,fi,vi,Mi,Oi,_i,bi,yi,Pi,Di,Li,wi,Gi,ki,Fi,Ui,Bi,$i,xi,qi];[...Ht,...Vi];[...xe,...Hi];const Wi=I("BaseSession.mock");class Qi{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(xe),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){return!1}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 Wi("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)=>(xe.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 gt{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 Yi 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 gt({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 gt({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 Ue.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 ji(t){const e=t.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}var Wt=(t=>(t.LOCAL="local",t.REMOTE="remote",t.SYSTEM="system",t))(Wt||{});const Qt=["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"],zi=["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"],Yt=[...Qt,...zi],jt=()=>new _.TypedEvents(Yt),mt=400,zt="777",Ji=t=>t.getVideoTracks().length>0;class $ extends Qi{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)},mt)});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 U.NameAddrHeader(new U.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 U.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=>($.countStartsPresentation+=1,new Promise((n,s)=>{this.timeoutStartPresentation=setTimeout(()=>{if($.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),s($.presentationError);return}if($.startPresentationError&&$.countStartsPresentation<$.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),s($.startPresentationError);return}n(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if($.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),$.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=Ue.createAudioMediaStreamTrackMock();n.id="mainaudio1";const s=[n];if(Ji(e)){const i=Ue.createVideoMediaStreamTrackMock();i.id="mainvideo1",s.push(i)}this.connection=new Yi(void 0,s),this.trigger("peerconnection",{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:n}={}){const s=ji(e);return this.initPeerconnection(n),this.timeoutConnect=setTimeout(()=>{e.includes(zt)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:Wt.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))},mt),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 Ki=["snapshot-changed"],Xi=()=>new _.TypedEvents(Ki),Jt=t=>t.type==="participant",oe=t=>t.type==="spectator_synthetic",V=t=>t.type==="spectator",Kt=(t,e)=>V(t)&&!V(e),Xt=(t,e)=>V(e),Zt=(t,e)=>{const n=V(t)||oe(t),s=V(e)||oe(e);return n&&!s},en=(t,e)=>{const n=V(t)||oe(t),s=V(e)||oe(e);return!n&&s},De={type:"participant"},Zi={type:"spectator_synthetic"},ea=t=>({type:"spectator",recvParams:t});class ta{role=De;isAvailableSendingMedia=!0;onRoleChanged;listeners=new Set;constructor(e){this.onRoleChanged=e}getRole(){return this.role}getIsAvailableSendingMedia(){return this.isAvailableSendingMedia}setCallRoleParticipant(){this.isAvailableSendingMedia=!0,this.changeRole(De)}setCallRoleSpectatorSynthetic(e=!0){this.isAvailableSendingMedia=e,this.changeRole(Zi)}setCallRoleSpectator(e,n=!0){this.isAvailableSendingMedia=n,this.changeRole(ea(e))}changeRole(e){const n=this.role;if(n.type!==e.type){this.setRole(e);return}V(e)&&V(n)&&n.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=De,this.isAvailableSendingMedia=!0}hasParticipant(){return Jt(this.role)}hasSpectatorSynthetic(){return oe(this.role)}hasSpectator(){return V(this.role)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRole(e){const n=this.role;this.role=e,this.onRoleChanged?.({previous:n,next:e}),this.listeners.forEach(s=>{s({previous:n,next:e})})}}const na=(t,e)=>t.type!==e.type?!1:t.type!=="spectator"?!0:e.type==="spectator"&&t.recvParams.audioId===e.recvParams.audioId,sa=(t,e)=>t.license===e.license&&t.isDuplexSendingMediaMode===e.isDuplexSendingMediaMode&&na(t.role,e.role)&&t.derived.isAvailableSendingMedia===e.derived.isAvailableSendingMedia,Tt=(t,e,n)=>{const s=t.getRole(),r=s.type==="spectator"||s.type==="spectator_synthetic";return{license:n,isDuplexSendingMediaMode:e,role:s,derived:{isSpectatorAny:r,isRecvSessionExpected:s.type==="spectator",isAvailableSendingMedia:t.getIsAvailableSendingMedia()}}},pt=_e.VIDEO;class tn extends _.EventEmitterProxy{roleManager=new ta;license=pt;isDuplexSendingMediaMode=!1;currentSnapshot;subscriptions=[];dedupedTotal=0;constructor(){super(Xi()),this.currentSnapshot=Tt(this.roleManager,this.isDuplexSendingMediaMode,this.license);const e=this.roleManager.subscribe(this.notifySubscribers);this.subscriptions.push({unsubscribe:e})}getSnapshot(){return this.currentSnapshot}subscribe(e){return this.on("snapshot-changed",({current:n})=>{e(n)})}subscribeRoleChanges(e){return this.roleManager.subscribe(e)}hasSpectator(){return this.roleManager.hasSpectator()}setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(e=!0){this.roleManager.setCallRoleSpectatorSynthetic(e)}setCallRoleSpectator(e,n=!0){this.roleManager.setCallRoleSpectator(e,n)}reset(){this.roleManager.reset(),this.license=pt,this.isDuplexSendingMediaMode=!1,this.notifySubscribers()}subscribeToApiEvents(e){const n=e.on("use-license",this.handleUseLicense),s=e.on("admin:force-sync-media-state",this.handleSyncMediaState),r=e.on("admin:stop-main-cam",this.handleSyncMediaState),i=e.on("admin:stop-mic",this.handleSyncMediaState),a=e.on("admin:start-mic",this.handleSyncMediaState);this.subscriptions.push({unsubscribe:n}),this.subscriptions.push({unsubscribe:s}),this.subscriptions.push({unsubscribe:r}),this.subscriptions.push({unsubscribe:i}),this.subscriptions.push({unsubscribe:a})}stop(){this.subscriptions.forEach(e=>{e.unsubscribe()}),this.events.offAll("snapshot-changed")}getDiagnostics(){return{emitsTotal:this.events.getEmitsTotal("snapshot-changed"),dedupedTotal:this.dedupedTotal,subscribersCount:this.events.getSubscribersCount("snapshot-changed")}}notifySubscribers=()=>{const{previousSnapshot:e,currentSnapshot:n}=this.updateCurrentSnapshot();if(sa(e,n)){this.dedupedTotal+=1;return}this.events.trigger("snapshot-changed",{previous:e,current:n})};updateCurrentSnapshot(){const e=this.currentSnapshot;return this.currentSnapshot=Tt(this.roleManager,this.isDuplexSendingMediaMode,this.license),{previousSnapshot:e,currentSnapshot:this.currentSnapshot}}handleUseLicense=e=>{this.license=e,this.notifySubscribers()};handleSyncMediaState=({isSyncForced:e})=>{this.isDuplexSendingMediaMode=e,this.notifySubscribers()}}const ra=(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},ia=t=>t.major!==void 0&&t.minor!==void 0&&t.patch!==void 0,aa=t=>e=>ia(t)&&ra(t,e),oa=(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}},ca=()=>globalThis.process?.versions?.electron!==void 0,je=()=>{const t=new Bn.UAParser,{name:e,version:n}=t.getBrowser(),{name:s}=t.getOS(),{type:r}=t.getDevice(),i=ca(),a=r==="mobile",o=oa(n);return{hasGreaterThanBrowserVersion:aa(o),isMobileDevice:a,isChrome:e==="Chrome"||i,isYandexBrowser:e==="Yandex",isSafari:e==="Safari",isOpera:e==="Opera",isWindows:s==="Windows"}},la=I("stringifyMessage"),da=t=>{let e="";try{e=JSON.stringify(t)}catch(n){la("failed to stringify message",n)}return e},ha=/^p2p.+to.+$/i,Ie=t=>t!==void 0&&t.length>0&&ha.test(t),nn="purgatory",me=t=>t===nn,ua=(t,e)=>{t.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},ge=(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"&&ua(o,s),o},ga="api/v2/rtp2webrtc/offer",sn=async({serverUrl:t,conferenceNumber:e,quality:n,audio:s,offer:r,token:i})=>{const a=new URL(`https://${t.replace(/\/$/,"")}/${ga}/${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 g=await c.json();return{type:g.type,sdp:g.sdp,toJSON(){return g}}},Ea=(t,e)=>(t.degradationPreference=e.degradationPreference,t),ma=(t,e)=>{t.encodings??=[];for(let n=t.encodings.length;n<e;n+=1)t.encodings.push({});return t},rn=t=>(e,n)=>n!==void 0&&e!==n||n===void 0&&e!==t,Ta=rn(),pa=(t,e)=>{if(Ta(t,e))return t},Sa=(t,e,{isResetAllowed:n=!1}={})=>{const s=t.maxBitrate,r=pa(e,s);return(r!==void 0||n)&&(t.maxBitrate=r??e),t},an=1,Ca=rn(an),Ra=(t,e)=>{const n=t===void 0?void 0:Math.max(t,an);if(n!==void 0&&Ca(n,e))return n},Na=(t,e)=>{const n=t.scaleResolutionDownBy,s=Ra(e,n);return s!==void 0&&(t.scaleResolutionDownBy=s),t},Aa=(t,e,{isResetAllowed:n}={})=>{const s=e.encodings?.length??0;return ma(t,s),t.encodings.forEach((r,i)=>{const a=(e?.encodings??[])[i],o=a?.maxBitrate,c=a?.scaleResolutionDownBy;Sa(r,o,{isResetAllowed:n}),Na(r,c)}),t},Ia=(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},fe=async(t,e,{isResetAllowed:n}={})=>{const s=t.getParameters(),r=JSON.parse(JSON.stringify(s));Aa(s,e,{isResetAllowed:n}),Ea(s,e);const i=Ia(r,s);return i&&await t.setParameters(s),{parameters:s,isChanged:i}},ze=async(t,e,n)=>{const{isChanged:s,parameters:r}=await fe(t,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&n&&n(r),{isChanged:s,parameters:r}},fa=(t,e)=>t.find(n=>n.track!==null&&e.getTracks().includes(n.track)),va=async(t,e,n)=>{const s=fa(t,e);if(s)return ze(s,{maxBitrate:n})},Ma=I("resolveOnStartMainCam"),Oa=t=>n=>(Ma("onStartMainCam"),t.on("api:admin:start-main-cam",n)),_a=I("resolveOnStartMic"),ba=t=>n=>(_a("onStartMic"),t.on("api:admin:start-mic",n)),ya=I("resolveOnStopMainCam"),Pa=t=>n=>(ya("onStopMainCam"),t.on("api:admin:stop-main-cam",n)),Da=I("resolveOnStopMic"),La=t=>n=>(Da("onStopMic"),t.on("api:admin:stop-mic",n));class on{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 M="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 cn={raw:{},state:{}},ln=t=>"number"in t&&q(t.number)&&Pt(t.answer),dn=t=>"room"in t&&q(t.room)&&q(t.participantName)&&$e(t.startedTimestamp),wa=t=>"token"in t&&q(t.token),hn=t=>wa(t)&&"conferenceForToken"in t&&q(t.conferenceForToken),he=t=>ln(t)&&dn(t),un=t=>!hn(t)||!dn(t)?!1:t.conferenceForToken===t.room,gn=({isDirectPeerToPeer:t})=>t===!0,Le=t=>"isDirectPeerToPeer"in t&&gn(t),Ga="x-vinteo-presentation-call: yes",ka=t=>jn(t)&&t.some(e=>e.trim().toLowerCase()===Ga),Fa=t=>"extraHeaders"in t&&ka(t.extraHeaders)&&"isConfirmed"in t&&t.isConfirmed===!0,Se=t=>he(t)&&!me(t.room)&&hn(t)&&un(t),le=t=>{const e=t;return{number:e.number,answer:e.answer,room:e.room,participantName:e.participantName,startedTimestamp:e.startedTimestamp}},w={[u.IDLE]:{guard:()=>!0,buildContext:()=>({})},[u.CONNECTING]:{guard:ln,buildContext:t=>{const{number:e,answer:n,extraHeaders:s}=t;return{number:e,answer:n,extraHeaders:s}}},[u.PRESENTATION_CALL]:{guard:Fa,buildContext:t=>{const{number:e,answer:n,startedTimestamp:s}=t;return{number:e,answer:n,startedTimestamp:s}}},[u.ROOM_PENDING_AUTH]:{guard:t=>he(t)&&!me(t.room)&&!Ie(t.room)&&!Le(t)&&!un(t),buildContext:le},[u.PURGATORY]:{guard:t=>he(t)&&me(t.room)&&!Se(t),buildContext:le},[u.P2P_ROOM]:{guard:t=>he(t)&&Ie(t.room)&&!Le(t)&&!Se(t),buildContext:le},[u.DIRECT_P2P_ROOM]:{guard:t=>he(t)&&Le(t)&&!Se(t),buildContext:t=>({...le(t),isDirectPeerToPeer:!0})},[u.IN_ROOM]:{guard:Se,buildContext:t=>{const{token:e,conferenceForToken:n}=t;return{...le(t),token:e,conferenceForToken:n}}},[u.DISCONNECTING]:{guard:t=>t.pendingDisconnect===!0,buildContext:()=>({})}},Ua=t=>me(t.room)||Ie(t.room)||gn(t),we=()=>({}),Ba=()=>T.setup({types:{context:cn,events:{}},actions:{setConnecting:T.assign(({event:t,context:e})=>t.type!=="CALL.CONNECTING"?e:{raw:{...we(),number:t.number,answer:t.answer,extraHeaders:t.extraHeaders}}),setRoomInfo:T.assign(({event:t,context:e})=>{if(t.type!=="CALL.ENTER_ROOM")return e;const n={room:t.room,participantName:t.participantName};q(t.token)?(n.token=t.token,n.conferenceForToken=t.room):Ua(t)&&(n.token=void 0,n.conferenceForToken=void 0),Pt(t.isDirectPeerToPeer)&&(n.isDirectPeerToPeer=t.isDirectPeerToPeer);const r=e.raw.startedTimestamp,i=$e(r)?r:Date.now();return{raw:{...e.raw,...n,startedTimestamp:i}}}),setTokenInfo:T.assign(({event:t,context:e})=>t.type!=="CALL.TOKEN_ISSUED"?e:{raw:{...e.raw,token:t.token,conferenceForToken:t.conferenceForToken,participantName:t.participantName}}),setConfirmed:T.assign(({event:t,context:e})=>{if(t.type!=="CALL.PRESENTATION_CALL")return e;const s=e.raw.startedTimestamp,r=$e(s)?s:Date.now();return{raw:{...e.raw,isConfirmed:!0,startedTimestamp:r}}}),reset:T.assign(()=>({raw:we()})),prepareDisconnect:T.assign(()=>({raw:{...we(),pendingDisconnect:!0}}))}}),$a=()=>Ba().createMachine({id:"call",initial:u.IDLE,context:cn,states:{[u.IDLE]:{entry:T.assign(()=>({state:w[u.IDLE].buildContext()})),on:{"CALL.CONNECTING":{target:M,actions:"setConnecting"}}},[u.CONNECTING]:{entry:T.assign(({context:t})=>({state:w[u.CONNECTING].buildContext(t.raw)})),on:{"CALL.PRESENTATION_CALL":{target:M,actions:"setConfirmed"},"CALL.ENTER_ROOM":{target:M,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:M,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[u.ROOM_PENDING_AUTH]:{entry:T.assign(({context:t})=>({state:w[u.ROOM_PENDING_AUTH].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:M,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:M,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[u.IN_ROOM]:{entry:T.assign(t=>({state:w[u.IN_ROOM].buildContext(t.context.raw)})),on:{"CALL.ENTER_ROOM":{target:M,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:M,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[M]:{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:T.assign(({context:t})=>({state:w[u.PURGATORY].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:M,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:M,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[u.P2P_ROOM]:{entry:T.assign(({context:t})=>({state:w[u.P2P_ROOM].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:M,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:M,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[u.PRESENTATION_CALL]:{entry:T.assign(({context:t})=>({state:w[u.PRESENTATION_CALL].buildContext(t.raw)})),on:{"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[u.DIRECT_P2P_ROOM]:{entry:T.assign(({context:t})=>({state:w[u.DIRECT_P2P_ROOM].buildContext(t.raw)})),on:{"CALL.ENTER_ROOM":{target:M,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:M,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:M,actions:"prepareDisconnect"},"CALL.RESET":{target:M,actions:"reset"}}},[u.DISCONNECTING]:{entry:T.assign(()=>({state:w[u.DISCONNECTING].buildContext()})),on:{"CALL.RESET":{target:M,actions:"reset"}}}}});function xa(t){return t!==M}const qa=I("CallManager: CallStateMachine");class Va 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 presentationCallContext(){if(this.state===u.PRESENTATION_CALL)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 startedTimestamp(){return this.inRoomContext?.startedTimestamp??this.roomPendingAuthContext?.startedTimestamp??this.presentationCallContext?.startedTimestamp??this.purgatoryContext?.startedTimestamp??this.p2pRoomContext?.startedTimestamp??this.directP2pRoomContext?.startedTimestamp}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}xa(r.value)&&(n=void 0)});return()=>{s.unsubscribe()}}reset(){this.send({type:"CALL.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){qa(`[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 En=t=>new Va($a(),t),Ha=t=>[...t.keys()].map(e=>t.get(e)),Wa=(t,e)=>Ha(t).find(n=>n?.type===e),Je=async t=>t.getStats().then(e=>Wa(e,"codec")?.mimeType);class Qa{async getCodecFromSender(e){return await Je(e)??""}}const Ya=I("TaskQueue");class ja{stackPromises=Oe.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{Ya("TaskQueue: error",e)})}}class za{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new ja}async setEncodingsToSender(e,n){return this.taskQueue.add(async()=>ze(e,n,this.onSetParameters))}stop(){this.taskQueue.stop()}}const qe=(t,e)=>t!==void 0&&e!==void 0&&t.toLowerCase().includes(e.toLowerCase()),Ja=1e6,Y=t=>t*Ja,mn=Y(.06),Tn=Y(4),Ka=t=>t<=64?mn:t<=128?Y(.12):t<=256?Y(.25):t<=384?Y(.32):t<=426?Y(.38):t<=640?Y(.5):t<=848?Y(.7):t<=1280?Y(1):t<=1920?Y(2):Tn,Xa="av1",Za=t=>qe(t,Xa),eo=.6,Ke=(t,e)=>Za(e)?t*eo:t,pn=t=>Ke(mn,t),Sn=t=>Ke(Tn,t),St=(t,e)=>{const n=Ka(t);return Ke(n,e)},Ge=1,to=({videoTrack:t,targetSize:e})=>{const n=t.getSettings(),s=n.width,r=n.height,i=s===void 0?Ge:s/e.width,a=r===void 0?Ge:r/e.height;return Math.max(i,a,Ge)};class no{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(qe(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(qe(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 x.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(n);case x.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(n);case x.MAX_MAIN_CAM_RESOLUTION:return r!==void 0?this.setResolutionSender(r,n):this.setBitrateByTrackResolution(n);case x.ADMIN_STOP_MAIN_CAM:case x.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:pn(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?Sn(r):St(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)},g=to({videoTrack:a,targetSize:c}),R=St(c.width,o),f={scaleResolutionDownBy:g,maxBitrate:R};return this.parametersSetter.setEncodingsToSender(i,f)}}const so=t=>t.find(e=>e.track?.kind==="video");class ro{findVideoSender(e){return so(e)}}class io{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 X.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 ao{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 ke=I("VideoSendingBalancer");class oo{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,n,{ignoreForCodec:s,onSetParameters:r,pollIntervalMs:i}={}){this.getConnection=n,this.eventHandler=new ao(e),this.parametersSetterWithQueue=new za(r),this.senderBalancer=new no({senderFinder:new ro,codecProvider:new Qa,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new io({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=>{ke("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=>{ke("balance on track change: error",s)})}),n}clearState(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(n=>{ke("handleMainCamControl: error",n)})}}const co=6e3,lo=52e4,Ce=(t,e)=>t.getSenders().filter(n=>n.track?.kind===e),ho=(t,e)=>t==="audio"?co:pn(e),uo=t=>t.track!==null;class go{previousBitrates=new Map;async setMinBitrateForSenders(e,n="all"){const s=[];if(!e)return;(n==="audio"||n==="all")&&s.push(...Ce(e,"audio")),(n==="video"||n==="all")&&s.push(...Ce(e,"video"));const r=s.filter(uo).map(async i=>{const a=i.getParameters();this.saveCurrentBitrate(i,a);const o={...a,encodings:a.encodings.map(c=>({...c,maxBitrate:ho(i.track.kind)}))};await fe(i,o)});await Promise.all(r)}async restoreBitrateForSenders(e,n="all"){const s=[];if(!e)return;(n==="audio"||n==="all")&&s.push(...Ce(e,"audio")),(n==="video"||n==="all")&&s.push(...Ce(e,"video"));const r=s.map(async i=>{const a=this.getSavedBitrate(i);if(a){const o=i.getParameters(),c=i.track?.kind==="video",g=c?await Je(i):void 0,R={...o,encodings:a.map(f=>{const P=c?Sn(g):lo;return{...f,maxBitrate:f.maxBitrate??P}})};await fe(i,R,{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 Xe=(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))(Xe||{});const Ct=I("CallManager: MCUSession");class Eo{events;rtcSession;disposers=new Set;pcConfig;bitrateStateManager=new go;constructor(e){this.events=e,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:g,offerToReceiveAudio:R=!0,offerToReceiveVideo:f=!0,degradationPreference:P,sendEncodings:b,onAddedTransceiver:H})=>new Promise((B,Z)=>{this.handleCall().then(B).catch(ne=>{Z(ne)}),this.pcConfig={iceServers:a},this.rtcSession=e.call(n(s),{mediaStream:ge(r,{directionVideo:o,directionAudio:c,contentHint:g}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:R,offerToReceiveVideo:f},eventHandlers:this.events.triggers,extraHeaders:i,directionVideo:o,directionAudio:c,degradationPreference:P,sendEncodings:b,onAddedTransceiver:H})});async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Xe.CANCELED})}answerToIncomingCall=async(e,{mediaStream:n,extraHeaders:s=[],iceServers:r,directionVideo:i,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:c,contentHint:g,degradationPreference:R,sendEncodings:f,onAddedTransceiver:P})=>new Promise((b,H)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(b).catch(B=>{H(B)}),this.pcConfig={iceServers:r},e.answer({pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:c},mediaStream:ge(n,{directionVideo:i,directionAudio:a,contentHint:g}),extraHeaders:s,directionVideo:i,directionAudio:a,degradationPreference:R,sendEncodings:f,onAddedTransceiver:P})}catch(B){H(B)}});async replaceMediaStream(e,n){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=n??{},r=ge(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=>{Ct("setMinBitrateForSenders",n)})}restoreBitrateForSenders(e="all"){this.bitrateStateManager.restoreBitrateForSenders(this.connection,e).catch(n=>{Ct("restoreBitrateForSenders",n)})}reset=()=>{delete this.rtcSession,delete this.pcConfig,this.unsubscribeFromSessionEvents(),this.bitrateStateManager.clearAll()};handleCall=async()=>new Promise((e,n)=>{const s=()=>{this.events.on("peerconnection",g),this.events.on("confirmed",R)},r=()=>{this.events.off("peerconnection",g),this.events.off("confirmed",R)},i=()=>{this.events.on("failed",o),this.events.on("ended",o)},a=()=>{this.events.off("failed",o),this.events.off("ended",o)},o=f=>{r(),a(),n(f)};let c;const g=({peerconnection:f})=>{c=f;const P=b=>{this.events.trigger("peerconnection:ontrack",b)};f.addEventListener("track",P),this.disposers.add(()=>{f.removeEventListener("track",P)})},R=()=>{c!==void 0&&this.events.trigger("peerconnection:confirmed",c),r(),a(),e(c)};s(),i()});subscribeToSessionEvents(e){this.events.eachTriggers((n,s)=>{const r=Qt.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)}}const Ve=t=>t==="auto"?"high":t,mo=10,To=500,po=5e3;class So{cancelableSendOfferWithRepeatedCalls;currentRenegotiation;config;tools;connection;lastCallParams;constructor(e,n){const s=e.quality??"auto";this.config={...e,quality:s,effectiveQuality:Ve(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=Ve(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=Me.repeatedCallsAsync({targetFunction:r,isComplete:i,callLimit:mo,delay:To,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",g),this.connection.removeEventListener("connectionstatechange",g),s())},c=R=>{a||(a=!0,clearTimeout(i),this.connection.removeEventListener("signalingstatechange",g),this.connection.removeEventListener("connectionstatechange",g),r(R))};function g(){const R=n();if(R==="error"){c(e());return}R==="success"&&o()}i=setTimeout(()=>{c(new Error("Timed out waiting for stable signaling state and ready connection state"))},po),this.connection.addEventListener("signalingstatechange",g),this.connection.addEventListener("connectionstatechange",g),g()})}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 Cn=t=>t.getSettings(),Co=(t,e)=>{const n=Cn(t);let s=e;s??=t.label;let r=n?.msid;return r??=s,r??=t.id,r},Ro=(t,e)=>{const n=Cn(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=Ro(e,s),i=Co(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 g=o;g||(g={participantId:r,groupId:i,stream:new MediaStream,trackIds:new Set},a.set(i,g)),g.stream.addTrack(e),g.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:r,groupId:i});const R=()=>{this.disposeTrackListener(e.id);const f=this.removeTrack(e.id);f.isRemovedTrack&&n?.({participantId:r,trackId:e.id,isRemovedStream:f.isRemovedStream})};return e.addEventListener("ended",R),this.trackDisposers.set(e.id,()=>{e.removeEventListener("ended",R)}),{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(g=>g.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 g=this.removeTrack(c);r||=g.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 No=(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 Ao{lastEmittedStreams;hasChanged(e){return!No(this.lastEmittedStreams,e)}updateLastEmittedStreams(e){this.lastEmittedStreams=e}getLastEmittedStreams(){return this.lastEmittedStreams}reset(){this.lastEmittedStreams=void 0}}const Io="default",fo="dual",vo="content_",Mo=t=>`${vo}${t.toLowerCase()}`,Oo=t=>[...t.getTracks()].some(e=>e.label.includes(fo));class _o{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=>!Oo(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(Io)[0],a=this.getRecvRemoteContentedStream({stateInfo:e});return{mainStream:i,contentedStream:a}}}}getRecvRemoteContentedStream({stateInfo:e}){if(!e.isAvailable||e.codec===void 0)return;const n=Mo(e.codec);return this.recvRemoteStreamsManager.getStreams(n)[0]}}const bo="udp",yo=t=>t.transport?.iceTransport?t.transport.iceTransport.getLocalCandidates():[],Po=t=>t.getReceivers().flatMap(yo),Do=t=>{const s=Po(t).filter(({protocol:r,port:i})=>i!==null&&bo===r).map(({port:r})=>r);return[...new Set(s)]},Nt=t=>t.streams[0]?.id;class Lo extends _.EventEmitterProxy{stateMachine;sessionState;isPendingCall=!1;isPendingAnswer=!1;mainRemoteStreamsManager=new Rt;recvRemoteStreamsManager=new Rt;streamsManagerProvider;contentedStreamManager;tools;roleManager={hasSpectator:()=>this.sessionState.hasSpectator(),reset:()=>{this.sessionState.reset()}};mcuSession;recvSession;disposeRecvSessionTrackListener;disposeInRoomCredentialsListener;deferredStartRecvSessionRunner;streamsChangeTracker=new Ao;constructor({contentedStreamManager:e},n,{callSessionState:s}){super(jt()),this.contentedStreamManager=e,this.tools=n,this.mcuSession=new Eo(this.events),this.stateMachine=En(this.events),this.sessionState=s,this.sessionState.subscribeRoleChanges(this.onRoleChanged),this.streamsManagerProvider=new _o(this.mainRemoteStreamsManager,this.recvRemoteStreamsManager),this.deferredStartRecvSessionRunner=new on({subscribe:r=>this.stateMachine.onStateChange(r),isReady:r=>r===u.IN_ROOM,isCancelled:r=>r===u.IDLE,onExecute:r=>{this.startRecvSessionForced({audioChannel:r.audioId}).catch(()=>{})}}),this.subscribeCallEndedStateMachine(),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?Do(e):[]}getStreamsManagerProvider(){return this.streamsManagerProvider}getContentedStreamManager(){return this.contentedStreamManager}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events),this.sessionState.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()}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=Ve(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 g=o.getEffectiveQuality();this.events.trigger("recv-quality-changed",{previousQuality:s,quality:e,effectiveQuality:g})}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.recvRemoteStreamsManager.reset(),this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.streamsChangeTracker.reset(),this.mcuSession.reset(),this.roleManager.reset()};subscribeCallEndedStateMachine(){this.stateMachine.onStateChange(e=>{e===u.IDLE&&this.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,Nt(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,Nt(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 So(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 g=new U.IncomingResponse;g.body=c instanceof Error?c.message:String(c);const R=U.C.causes.INTERNAL_ERROR;throw await this.failed(g,R),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(Kt(e,n)&&(this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.emitEventChangedRemoteStreamsConnected()),Xt(e,n)){const s=n.recvParams;this.stateMachine.getInRoomCredentials()===void 0?this.deferredStartRecvSessionRunner.set({audioId:s.audioId}):this.startRecvSession({audioChannel:s.audioId}).catch(()=>{})}Zt(e,n)&&this.mcuSession.restoreBitrateForSenders(),en(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 Rn=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],wo=()=>new _.TypedEvents(Rn);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||{}),p=(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))(p||{});const Nn={lastError:void 0},At=I("PresentationStateMachine"),Go=t=>t instanceof Error?t:new Error(JSON.stringify(t)),ko=()=>T.setup({types:{context:Nn,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]:T.assign(({event:t})=>"error"in t&&t.error!==void 0?{lastError:Go(t.error)}:{lastError:void 0}),[S.CLEAR_ERROR]:T.assign(()=>({lastError:void 0}))}}),Fo=()=>ko().createMachine({id:"presentation",initial:h.IDLE,context:Nn,states:{[h.IDLE]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.IDLE}},on:{[p.SCREEN_STARTING]:{target:h.STARTING,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.IDLE,to:h.STARTING,event:p.SCREEN_STARTING}}]}}},[h.STARTING]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.STARTING}},on:{[p.SCREEN_STARTED]:{target:h.ACTIVE,actions:{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.ACTIVE,event:p.SCREEN_STARTED}}},[p.SCREEN_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.FAILED,event:p.SCREEN_FAILED}}]},[p.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.IDLE,event:p.SCREEN_ENDED}}]},[p.CALL_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.IDLE,event:p.CALL_ENDED}}]},[p.CALL_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STARTING,to:h.FAILED,event:p.CALL_FAILED}}]}}},[h.ACTIVE]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.ACTIVE}},on:{[p.SCREEN_ENDING]:{target:h.STOPPING,actions:{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.STOPPING,event:p.SCREEN_ENDING}}},[p.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.IDLE,event:p.SCREEN_ENDED}}]},[p.SCREEN_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.FAILED,event:p.SCREEN_FAILED}}]},[p.CALL_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.IDLE,event:p.CALL_ENDED}}]},[p.CALL_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.ACTIVE,to:h.FAILED,event:p.CALL_FAILED}}]}}},[h.STOPPING]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.STOPPING}},on:{[p.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.IDLE,event:p.SCREEN_ENDED}}]},[p.SCREEN_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.FAILED,event:p.SCREEN_FAILED}}]},[p.CALL_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.IDLE,event:p.CALL_ENDED}}]},[p.CALL_FAILED]:{target:h.FAILED,actions:[S.SET_ERROR,{type:S.LOG_TRANSITION,params:{from:h.STOPPING,to:h.FAILED,event:p.CALL_FAILED}}]}}},[h.FAILED]:{entry:{type:S.LOG_STATE_CHANGE,params:{state:h.FAILED}},on:{[p.SCREEN_STARTING]:{target:h.STARTING,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.FAILED,to:h.STARTING,event:p.SCREEN_STARTING}}]},[p.SCREEN_ENDED]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.FAILED,to:h.IDLE,event:p.SCREEN_ENDED}}]},[p.PRESENTATION_RESET]:{target:h.IDLE,actions:[S.CLEAR_ERROR,{type:S.LOG_TRANSITION,params:{from:h.FAILED,to:h.IDLE,event:p.PRESENTATION_RESET}}]}}}}}),Uo=Fo(),Bo=I("PresentationStateMachine");class An extends te{constructor(e){super(Uo),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:p.PRESENTATION_RESET})}send(e){this.sendEvent(e)}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){Bo(`[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:p.SCREEN_STARTING})})),this.addSubscription(e.on("presentation:started",()=>{this.sendEvent({type:p.SCREEN_STARTED})})),this.addSubscription(e.on("presentation:end",()=>{this.sendEvent({type:p.SCREEN_ENDING})})),this.addSubscription(e.on("presentation:ended",()=>{this.sendEvent({type:p.SCREEN_ENDED})})),this.addSubscription(e.on("presentation:failed",n=>{this.sendEvent({type:p.SCREEN_FAILED,error:n})})),this.addSubscription(e.on("ended",()=>{this.sendEvent({type:p.CALL_ENDED})})),this.addSubscription(e.on("failed",n=>{this.sendEvent({type:p.CALL_FAILED,error:n})}))}}const $o=1,xo=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],qo=t=>t instanceof Error?t:new Error(String(t)),Vo=t=>Me.hasCanceledError(t);class Ho extends _.EventEmitterProxy{stateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:n}){super(wo()),this.callManager=e,this.maxBitrate=n,this.stateMachine=new An(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(){xo.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:$o}}){const a=async()=>this.sendPresentation(e,n,s,r),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=Me.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 g=ge(s,{contentHint:i});if(g===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=g;const R=e().then(async()=>n.startPresentation(g,r,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(f=>{throw this.removeStreamPresentationCurrent(),this.notifyPresentationFailed(f),f});return this.promisePendingStartPresentation=R,R.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 va(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",qo(e))}}const Wo=I("ContentedStreamStateMachine"),Qo=T.setup({types:{context:{},events:{}},actions:{setCodec:T.assign(({event:t})=>"codec"in t?{codec:t.codec}:{}),clearCodec:T.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 Yo extends te{constructor(){super(Qo)}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)){Wo(`[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 jo=["available","not-available"],zo=()=>new _.TypedEvents(jo);class Jo extends _.EventEmitterProxy{stateMachine;constructor(){super(zo()),this.stateMachine=new Yo,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 In=["ringing","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],fn=()=>new _.TypedEvents(In);var d=(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))(d||{}),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||{}),N=(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))(N||{});const vn={remoteCallerData:void 0,lastReason:void 0},It=I("IncomingCallManager: createIncomingCallMachineSetup"),Ko=()=>T.setup({types:{context:vn,events:{}},actions:{[C.LOG_TRANSITION]:(t,e)=>{It(`State transition: ${e.from} -> ${e.to} (${e.event})`)},[C.LOG_STATE_CHANGE]:(t,e)=>{It("IncomingCallStateMachine state changed",e.state)},[C.REMEMBER_INCOMING]:T.assign(({event:t})=>({remoteCallerData:t.data,lastReason:void 0})),[C.REMEMBER_REASON]:T.assign(({event:t,context:e})=>t.type===N.CONSUMED?{remoteCallerData:e.remoteCallerData,lastReason:d.CONSUMED}:t.type===N.DECLINED?{remoteCallerData:t.data,lastReason:d.DECLINED}:t.type===N.TERMINATED?{remoteCallerData:t.data,lastReason:d.TERMINATED}:{remoteCallerData:t.data,lastReason:d.FAILED}),[C.CLEAR_INCOMING]:T.assign(()=>({remoteCallerData:void 0,lastReason:void 0}))}}),Xo=()=>Ko().createMachine({id:"incoming",initial:d.IDLE,context:vn,states:{[d.IDLE]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:d.IDLE}},on:{[N.RINGING]:{target:d.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.IDLE,to:d.RINGING,event:N.RINGING}}]},[N.CLEAR]:{target:d.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.IDLE,to:d.IDLE,event:N.CLEAR}}]}}},[d.RINGING]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:d.RINGING}},on:{[N.RINGING]:{target:d.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.RINGING,to:d.RINGING,event:N.RINGING}}]},[N.CONSUMED]:{target:d.CONSUMED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:d.RINGING,to:d.CONSUMED,event:N.CONSUMED}}]},[N.DECLINED]:{target:d.DECLINED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:d.RINGING,to:d.DECLINED,event:N.DECLINED}}]},[N.TERMINATED]:{target:d.TERMINATED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:d.RINGING,to:d.TERMINATED,event:N.TERMINATED}}]},[N.FAILED]:{target:d.FAILED,actions:[C.REMEMBER_REASON,{type:C.LOG_TRANSITION,params:{from:d.RINGING,to:d.FAILED,event:N.FAILED}}]},[N.CLEAR]:{target:d.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.RINGING,to:d.IDLE,event:N.CLEAR}}]}}},[d.CONSUMED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:d.CONSUMED}},on:{[N.CLEAR]:{target:d.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.CONSUMED,to:d.IDLE,event:N.CLEAR}}]},[N.RINGING]:{target:d.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.CONSUMED,to:d.RINGING,event:N.RINGING}}]}}},[d.DECLINED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:d.DECLINED}},on:{[N.CLEAR]:{target:d.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.DECLINED,to:d.IDLE,event:N.CLEAR}}]},[N.RINGING]:{target:d.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.DECLINED,to:d.RINGING,event:N.RINGING}}]}}},[d.TERMINATED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:d.TERMINATED}},on:{[N.CLEAR]:{target:d.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.TERMINATED,to:d.IDLE,event:N.CLEAR}}]},[N.RINGING]:{target:d.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.TERMINATED,to:d.RINGING,event:N.RINGING}}]}}},[d.FAILED]:{entry:{type:C.LOG_STATE_CHANGE,params:{state:d.FAILED}},on:{[N.CLEAR]:{target:d.IDLE,actions:[C.CLEAR_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.FAILED,to:d.IDLE,event:N.CLEAR}}]},[N.RINGING]:{target:d.RINGING,actions:[C.REMEMBER_INCOMING,{type:C.LOG_TRANSITION,params:{from:d.FAILED,to:d.RINGING,event:N.RINGING}}]}}}}}),Zo=Xo(),ec=I("IncomingCallStateMachine");class Mn extends te{constructor({incomingEvents:e,connectionEvents:n}){super(Zo),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(n)}get isIdle(){return this.hasState(d.IDLE)}get isRinging(){return this.hasState(d.RINGING)}get isConsumed(){return this.hasState(d.CONSUMED)}get isDeclined(){return this.hasState(d.DECLINED)}get isTerminated(){return this.hasState(d.TERMINATED)}get isFailed(){return this.hasState(d.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:N.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)){ec(`[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:N.RINGING,data:{displayName:n.displayName,host:n.host,incomingNumber:n.incomingNumber}})})),this.addSubscription(e.on("declinedIncomingCall",n=>{this.sendEvent({type:N.DECLINED,data:{displayName:n.displayName,host:n.host,incomingNumber:n.incomingNumber}})})),this.addSubscription(e.on("terminatedIncomingCall",n=>{this.sendEvent({type:N.TERMINATED,data:{displayName:n.displayName,host:n.host,incomingNumber:n.incomingNumber}})})),this.addSubscription(e.on("failedIncomingCall",n=>{this.sendEvent({type:N.FAILED,data:{displayName:n.displayName,host:n.host,incomingNumber:n.incomingNumber}})}))}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:N.CLEAR})}}const tc=486,nc=487,Fe=t=>({displayName:t.remote_identity.display_name,host:t.remote_identity.uri.host,incomingNumber:t.remote_identity.uri.user,rtcSession:t});class sc extends _.EventEmitterProxy{stateMachine;incomingRTCSession;connectionManager;constructor(e){super(fn()),this.connectionManager=e,this.stateMachine=new Mn({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get remoteCallerData(){if(this.incomingRTCSession)return Fe(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=nc}={}){return new Promise((n,s)=>{try{const r=this.getIncomingRTCSession(),i=Fe(r);this.removeIncomingSession(),this.events.trigger("declinedIncomingCall",i),r.terminate({status_code:e}),n()}catch(r){s(r)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:tc})}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=Fe(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 rc{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=[`${E.CONTENT_ENTER_ROOM}: ${this.peerToPeerRoom}`,`${E.PARTICIPANT_NAME}: ${this.number}`,`${E.IS_DIRECT_PEER_TO_PEER}: true`];s.sendEnterRoom(r)}}const On=["snapshot-changed"],ic=()=>new _.TypedEvents(On),ac=(t,e)=>Object.is(t,e),ft=(t,e)=>t.connection.value===e.connection.value&&Be.isEqual(t.call,e.call)&&t.incoming.value===e.incoming.value&&t.presentation.value===e.presentation.value&&t.autoConnector.value===e.autoConnector.value&&Be.isEqual(t.callReconnect,e.callReconnect),vt=t=>({connection:t.connection.getSnapshot(),call:t.call.getSnapshot(),incoming:t.incoming.getSnapshot(),presentation:t.presentation.getSnapshot(),autoConnector:t.autoConnector.getSnapshot(),callReconnect:t.callReconnect.getSnapshot()});class _n extends _.EventEmitterProxy{machines;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){super(ic()),this.machines={connection:e.connectionManager.stateMachine,call:e.callManager.stateMachine,incoming:e.incomingCallManager.stateMachine,presentation:e.presentationManager.stateMachine,autoConnector:e.autoConnectorManager.stateMachine,callReconnect:e.callReconnectManager.stateMachine},this.currentSnapshot=vt(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),this.machines.callReconnect.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,n,s){const r=typeof n=="function",i=r?e:f=>f,a=r?n:e,c=r?s??ac:ft,g=i(this.currentSnapshot),R={selector:i,listener:a,equals:c,current:g};return this.subscribers.add(R),()=>{this.subscribers.delete(R)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}notifySubscribers=()=>{const e=this.currentSnapshot;this.currentSnapshot=vt(this.machines);const n=ft(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 de=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 bn=["collected","stopped"],oc=()=>new _.TypedEvents(bn),Mt=()=>"performance"in window?performance.now():Date.now(),Te=t=>[...t.keys()].reduce((e,n)=>{const s=t.get(n);return s===void 0?e:{...e,[s.type]:s}},{}),cc=t=>{if(!t)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=Te(t);return{outboundRtp:e[D.OUTBOUND_RTP],codec:e[D.CODEC],mediaSource:e[D.MEDIA_SOURCE],remoteInboundRtp:e[D.REMOTE_INBOUND_RTP]}},Ot=t=>{if(!t)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=Te(t);return{outboundRtp:e[D.OUTBOUND_RTP],codec:e[D.CODEC],mediaSource:e[D.MEDIA_SOURCE],remoteInboundRtp:e[D.REMOTE_INBOUND_RTP]}},_t=({videoReceiversStats:t,synchronizationSourcesVideo:e})=>{if(!t)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const n=Te(t);return{inboundRtp:n[D.INBOUND_RTP],codec:n[D.CODEC],synchronizationSources:e}},lc=({audioReceiverStats:t,synchronizationSourcesAudio:e})=>{if(!t)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const n=Te(t);return{inboundRtp:n[D.INBOUND_RTP],codec:n[D.CODEC],remoteOutboundRtp:n[D.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},yn=t=>{if(!t)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=Te(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]}},dc=({audioSenderStats:t,videoSenderFirstStats:e,videoSenderSecondStats:n})=>({video:Ot(e),secondVideo:Ot(n),audio:cc(t),additional:yn(t??e??n)}),hc=({audioReceiverStats:t,videoReceiverFirstStats:e,videoReceiverSecondStats:n,synchronizationSources:s})=>({video:_t({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:_t({videoReceiversStats:n,synchronizationSourcesVideo:s.secondVideo??s.video}),audio:lc({audioReceiverStats:t,synchronizationSourcesAudio:s.audio}),additional:yn(t??e??n)}),uc=({audioSenderStats:t,videoSenderFirstStats:e,videoSenderSecondStats:n,audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a})=>{const o=dc({audioSenderStats:t,videoSenderFirstStats:e,videoSenderSecondStats:n}),c=hc({audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a});return{outbound:o,inbound:c}},gc=async t=>{const e="audio",n="video",s=t.getSenders(),r=s.find(b=>b.track?.kind===e),i=s.filter(b=>b.track?.kind===n),a=t.getReceivers(),o=a.find(b=>b.track.kind===e),c=a.filter(b=>b.track.kind===n),g={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},R={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},f={trackIdentifier:c[1]?.track.id,item:c[1]?.getSynchronizationSources()[0]},P={audio:g,video:R,secondVideo:f};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(b=>{const[H,B,Z,ne,be,et]=b;return{synchronizationSources:P,audioSenderStats:H,videoSenderFirstStats:B,videoSenderSecondStats:Z,audioReceiverStats:ne,videoReceiverFirstStats:be,videoReceiverSecondStats:et}})},Ec=I("StatsPeerConnection");class Pn extends _.EventEmitterProxy{setTimeoutRequest;requesterAllStatistics=new K.CancelableRequest(gc);constructor(){super(oc()),this.setTimeoutRequest=new X.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:n=de,onError:s=Ec}={}){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=Mt();this.requestAllStatistics(e).then(i=>{this.events.trigger("collected",uc(i));const o=Mt()-r;let c=de;o>48?c=de*4:o>32?c=de*3:o>16&&(c=de*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 mc=500,Tc=I("StatsManager");class pc extends _.EventEmitterProxy{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:n}){const s=new Pn;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>=mc,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=>{Tc("Failed to send stats",e)})}}const Sc=I("setCodecPreferences"),Cc=(t,e)=>t.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),Rc=t=>{const e=RTCRtpSender.getCapabilities(t),n=RTCRtpReceiver.getCapabilities(t),s=e===null?[]:e.codecs,r=n===null?[]:n.codecs;return Cc(s,r)},Nc=(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}),Ac=(t,e)=>e===void 0||e.length===0?t:t.filter(n=>!e.includes(n.mimeType)),Ic=(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=Rc("video"),r=Ac(s,n),i=Nc(r,e);t.setCodecPreferences(i)}}catch(s){Sc("setCodecPreferences error",s)}},Dn=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"],fc=()=>new _.TypedEvents(Dn),vc=I("VideoSendingBalancerManager");class Mc extends _.EventEmitterProxy{isBalancingActive=!1;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,n,s={}){super(fc()),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new oo(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=>{vc("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const Ln="health-snapshot",wn="inbound-video-problem-detected",Gn="inbound-video-problem-resolved",kn="inbound-video-problem-reset",Fn=[Ln,wn,Gn,kn],Oc=()=>new _.TypedEvents(Fn),_c=3;class Ee extends _.EventEmitterProxy{statsManager;callManager;minConsecutiveProblemSamplesCount;consecutiveProblemSamplesCount=0;currentProblemReason;hasEmittedCurrentProblem=!1;constructor(e,n,s=_c){super(Oc()),this.statsManager=e,this.callManager=n,Ee.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){Ee.assertValidMinConsecutiveProblemSamplesCount(e),this.minConsecutiveProblemSamplesCount=e,this.resetProblemDetectionState()}handleStatsCollected=()=>{const{healthSnapshot:e}=this;this.events.trigger(Ln,e);const n=Ee.resolveProblemReason(e);if(n===void 0){this.maybeEmitResolvedProblem(e),this.resetProblemDetectionState();return}this.updateProblemDetectionState(n),this.consecutiveProblemSamplesCount>=this.minConsecutiveProblemSamplesCount&&!this.hasEmittedCurrentProblem&&(this.events.trigger(wn,{...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(Gn,{...e,reason:this.currentProblemReason})};handleProblemReset=e=>()=>{this.maybeEmitResetProblem(e),this.resetProblemDetectionState()};maybeEmitResetProblem=e=>{!this.hasEmittedCurrentProblem||this.currentProblemReason===void 0||this.events.trigger(kn,{reason:this.currentProblemReason,resetCause:e})};resetProblemDetectionState=()=>{this.currentProblemReason=void 0,this.consecutiveProblemSamplesCount=0,this.hasEmittedCurrentProblem=!1}}const re=I("MainStreamRecovery"),bc=4e3;class ve{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,n=bc){this.callManager=e,this.renegotiateRequester=new K.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){ve.assertValidThrottleRecoveryTimeout(e),this.renegotiateThrottled.cancel(),this.renegotiateThrottled=this.createRenegotiateThrottled(e)}recover(){re("trying to recover main stream"),this.renegotiateThrottled()}requestRenegotiate=()=>{if(re("trying to renegotiate"),this.renegotiateRequester.requested){re("previous renegotiate is not finished yet");return}this.renegotiateRequester.request().then(()=>{re("renegotiate has successful")}).catch(e=>{re("failed to renegotiate main media stream",e)})};createRenegotiateThrottled(e){return ve.assertValidThrottleRecoveryTimeout(e),Be.throttle(this.requestRenegotiate.bind(this),e)}subscribe(){this.callManager.on("ended",()=>{this.cancel()})}cancel(){re("cancel recover main stream"),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}}var Ze=(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))(Ze||{});const yc={major:25,minor:8,patch:0},Pc=({isYandexBrowser:t,hasGreaterThanBrowserVersion:e})=>{const n=e(yc);return t&&n},Dc=()=>{const t=je();if(Pc(t))return[Ze.VP8]},Lc=()=>{const{isMobileDevice:t,isSafari:e,isOpera:n,isWindows:s}=je();return t||e||n&&s};let Un;Lc()&&(Un="h264");const wc={ignoreForCodec:Un},Gc=Dc(),kc=1e6,Fc=xt.map(t=>`auto-connect:${t}`),Uc=Ye.map(t=>`call-reconnect:${t}`),Bc=Ut.map(t=>`connection:${t}`),$c=Yt.map(t=>`call:${t}`),xc=Dt.map(t=>`api:${t}`),qc=In.map(t=>`incoming-call:${t}`),Vc=Rn.map(t=>`presentation:${t}`),Hc=bn.map(t=>`stats:${t}`),Wc=Dn.map(t=>`video-balancer:${t}`),Qc=Fn.map(t=>`main-stream-health:${t}`),Yc=On.map(t=>`session:${t}`),jc=["disconnected-from-out-of-call","connected-with-configuration-from-out-of-call","stopped-presentation-by-server-command"],zc=[...Fc,...Uc,...Bc,...$c,...xc,...qc,...Vc,...Hc,...Wc,...Qc,...Yc,...jc],Jc=()=>new _.TypedEvents(zc),bt=I("SipConnector");class Kc extends _.EventEmitterProxy{connectionManager;connectionQueueManager;contentedStreamManager;callManager;callSessionState;autoConnectorManager;callReconnectManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;peerToPeerManager;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:n,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:r,autoConnectorOptions:i,callReconnectOptions:a,numberOfConnectionAttempts:o,minConsecutiveProblemSamplesCount:c,throttleRecoveryTimeout:g}={}){super(Jc()),this.preferredMimeTypesVideoCodecs=n??Gc,this.excludeMimeTypesVideoCodecs=s,this.apiManager=new es,this.connectionManager=new Ls({JsSIP:e},{numberOfConnectionAttempts:o}),this.connectionQueueManager=new ws({connectionManager:this.connectionManager}),this.contentedStreamManager=new Jo,this.callSessionState=new tn,this.callManager=new Lo({contentedStreamManager:this.contentedStreamManager},{sendOffer:this.sendOffer},{callSessionState:this.callSessionState}),this.incomingCallManager=new sc(this.connectionManager),this.presentationManager=new Ho({callManager:this.callManager,maxBitrate:kc}),this.statsManager=new pc({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new ar({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},i),this.callReconnectManager=new Or({callManager:this.callManager,connectionManager:this.connectionManager},a),this.videoSendingBalancerManager=new Mc(this.callManager,this.apiManager,r??wc),this.mainStreamHealthMonitor=new Ee(this.statsManager,this.callManager,c),this.mainStreamRecovery=new ve(this.callManager,g),this.sessionManager=new _n({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager,autoConnectorManager:this.autoConnectorManager,callReconnectManager:this.callReconnectManager}),this.callManager.subscribeToApiEvents(this.apiManager),this.contentedStreamManager.subscribeToApiEvents(this.apiManager),this.apiManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager}),this.peerToPeerManager=new rc,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=async(...e)=>this.autoConnectorManager.start(...e);stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async(e,n={})=>{const{onAddedTransceiver:s,...r}=e,i={...r,onAddedTransceiver:this.resolveHandleAddTransceiver(s)};return n.autoRedial===!0&&this.callReconnectManager.arm({getCallParameters:async()=>i}),this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,i)};hangUp=async()=>(this.callReconnectManager.disarm("local-hangup"),this.callManager.endCall());armCallAutoRedial=e=>{this.callReconnectManager.arm(e)};disarmCallAutoRedial=e=>{this.callReconnectManager.disarm(e)};forceCallReconnect=()=>{this.callReconnectManager.forceReconnect()};cancelCurrentCallReconnectAttempt=()=>{this.callReconnectManager.cancelCurrentAttempt()};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.callSessionState.setCallRoleParticipant()}),this.apiManager.on("participant:move-request-to-spectators-synthetic",e=>{this.callSessionState.setCallRoleSpectatorSynthetic(e.isAvailableSendingMedia),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("participant:move-request-to-spectators-with-audio-id",({audioId:e,isAvailableSendingMedia:n})=>{this.callSessionState.setCallRoleSpectator({audioId:e},n),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("presentation:must-stop",()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on("failed-send-room-direct-p2p",({error:e})=>{const n=new U.IncomingResponse;n.body=e instanceof Error?e.message:String(e);const s=U.C.causes.INTERNAL_ERROR;this.callManager.failed(n,s).catch(r=>{bt("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 sn({serverUrl:r,offer:n,token:e.token,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){Ic(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents("auto-connect",this.autoConnectorManager),this.bridgeEvents("call-reconnect",this.callReconnectManager),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})=>{bt("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.CallSessionState=tn;exports.ConnectionStateMachine=kt;exports.DeferredCommandRunner=on;exports.ECallCause=Xe;exports.EContentUseLicense=_e;exports.EEvents=m;exports.EEvents$1=N;exports.EEvents$2=p;exports.EMimeTypesVideoCodecs=Ze;exports.EState=u;exports.EState$1=l;exports.EState$2=O;exports.EState$3=v;exports.EState$4=d;exports.EState$5=h;exports.EStatsTypes=D;exports.EVENT_NAMES=Ye;exports.FAILED_CONFERENCE_NUMBER=zt;exports.IncomingCallStateMachine=Mn;exports.PURGATORY_CONFERENCE_NUMBER=nn;exports.PresentationStateMachine=An;exports.RTCSessionMock=$;exports.SessionManager=_n;exports.SipConnector=Kc;exports.StatsPeerConnection=Pn;exports.UA_JSSIP_EVENT_NAMES=Ht;exports.createAutoConnectorStateMachine=$t;exports.createCallReconnectStateMachine=qt;exports.createCallStateMachine=En;exports.createEvents=jt;exports.createEvents$1=Bt;exports.createEvents$2=fn;exports.createUaParser=je;exports.disableDebug=qn;exports.enableDebug=xn;exports.getCodecFromSender=Je;exports.hasCanceledStartPresentationError=Vo;exports.hasNotReadyForConnectionError=wt;exports.hasParticipant=Jt;exports.hasPeerToPeer=Ie;exports.hasPurgatory=me;exports.hasSpectator=V;exports.hasSpectatorSynthetic=oe;exports.isEnteringAnySpectatorRole=en;exports.isEnteringSpectatorRole=Xt;exports.isExitingAnySpectatorRole=Zt;exports.isExitingSpectatorRole=Kt;exports.prepareMediaStream=ge;exports.resolveDebug=I;exports.resolveOnStartMainCam=Oa;exports.resolveOnStartMic=ba;exports.resolveOnStopMainCam=Pa;exports.resolveOnStopMic=La;exports.sendOffer=sn;exports.setEncodingsToSender=ze;exports.setParametersToSender=fe;exports.stringifyMessage=da;
|