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