sip-connector 19.2.0 → 19.2.1
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-BRWV-qDT.js → @SipConnector-Cr5Qu1ds.js} +92 -90
- package/dist/{@SipConnector-4vrb2RbW.cjs → @SipConnector-Cx-er9n6.cjs} +1 -1
- package/dist/AutoConnectorManager/eventNames.d.ts +12 -8
- package/dist/SipConnector/eventNames.d.ts +1 -1
- package/dist/doMock.cjs +1 -1
- package/dist/doMock.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const y=require("events-constructor"),G=require("debug"),$=require("@krivega/cancelable-promise"),b=require("@krivega/timeout-requester"),Q=require("repeated-calls"),se=require("xstate"),Y=require("stack-promises");require("ua-parser-js");require("sequent-promises");const z="sip-connector",d=G(z),ye=()=>{G.enable(z)},De=()=>{G.enable(`-${z}`)},be="Error decline with 603",we=1006,Ue=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===we,Le=n=>n.message===be;var l=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n.AVAILABLE_INCOMING_BITRATE="X-WEBRTC-AVAILABLE-INCOMING-BITRATE",n.AUDIO_TRACK_COUNT="X-WEBRTC-AUDIO-TRACK-COUNT",n.VIDEO_TRACK_COUNT="X-WEBRTC-VIDEO-TRACK-COUNT",n.TRACKS_DIRECTION="X-WEBRTC-TRACKS-DIRECTION",n))(l||{}),k=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(k||{}),W=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(W||{}),P=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.RESTART="application/vinteo.webrtc.restart",n))(P||{}),m=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.STATS="application/vinteo.webrtc.stats",n))(m||{}),v=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(v||{}),H=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(H||{}),x=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(x||{}),re=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(re||{}),u=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n.RESTART="restart",n))(u||{});const ie=["participation:accepting-word-request","participation:cancelling-word-request","participant:move-request-to-stream","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-spectators","participant:move-request-to-participants","channels","enterRoom","shareState","main-cam-control","useLicense","admin-start-main-cam","admin-stop-main-cam","admin-start-mic","admin-stop-mic","admin-force-sync-media-state","availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","newDTMF","restart"];var p=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(p||{});class Be{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=new y.Events(ie),this.subscribe()}async waitChannels(){return this.wait(u.CHANNELS)}async waitSyncMediaState(){return this.wait(u.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let r;try{r=this.getEstablishedRTCSessionProtected()}catch(i){s(i)}r&&(this.callManager.once("newDTMF",({originator:i})=>{i==="local"&&t()}),r.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),r=`${l.INPUT_CHANNELS}: ${e}`,i=`${l.OUTPUT_CHANNELS}: ${t}`,a=[r,i];return s.sendInfo(m.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const r=this.getEstablishedRTCSessionProtected(),i=`${l.MEDIA_STATE}: currentstate`,a=`${l.MAIN_CAM_STATE}: ${Number(e)}`,o=`${l.MIC_STATE}: ${Number(t)}`,c=[i,a,o];return r.sendInfo(m.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),r=[`${l.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(m.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:r})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${l.MEDIA_TYPE}: ${a}`];return s.sendInfo(m.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[l.ENABLE_MAIN_CAM];return t.sendInfo(m.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(r=>{if(Le(r))throw r})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(l.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){d("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case p.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case p.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case p.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case p.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case p.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case p.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case p.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case p.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case p.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case p.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case p.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:d("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,r=s,i=r.getHeader(l.CONTENT_TYPE);if(i!==void 0)switch(i){case P.ENTER_ROOM:{this.triggerEnterRoom(r),this.maybeTriggerChannels(r);break}case P.NOTIFY:{this.maybeHandleNotify(r);break}case P.SHARE_STATE:{this.triggerShareState(r);break}case P.MAIN_CAM:{this.triggerMainCamControl(r);break}case P.MIC:{this.triggerMicControl(r);break}case P.USE_LICENSE:{this.triggerUseLicense(r);break}case P.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(r);break}case P.RESTART:{this.triggerRestart(r);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,r={inputChannels:t,outputChannels:s};this.events.trigger(u.CHANNELS_NOTIFY,r)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(u.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(u.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(u.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(u.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(u.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(u.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(u.ACCOUNT_CHANGED,void 0)};triggerAccountDeletedNotify=()=>{this.events.trigger(u.ACCOUNT_DELETED,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const r={conference:e,participant:t,jwt:s};this.events.trigger(u.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,r)};maybeTriggerChannels=e=>{const t=e.getHeader(l.INPUT_CHANNELS),s=e.getHeader(l.OUTPUT_CHANNELS);if(t&&s){const r={inputChannels:t,outputChannels:s};this.events.trigger(u.CHANNELS,r)}};triggerEnterRoom=e=>{const t=e.getHeader(l.CONTENT_ENTER_ROOM),s=e.getHeader(l.PARTICIPANT_NAME);this.events.trigger(u.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(l.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case k.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(u.AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case k.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(u.NOT_AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case k.MUST_STOP_PRESENTATION:{this.events.trigger(u.MUST_STOP_PRESENTATION,void 0);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(l.CONTENT_PARTICIPANT_STATE);t===W.SPECTATOR&&this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,void 0),t===W.PARTICIPANT&&this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(l.MAIN_CAM),s=e.getHeader(l.MEDIA_SYNC),r=s===x.ADMIN_SYNC_FORCED;if(t===v.ADMIN_START_MAIN_CAM){this.events.trigger(u.ADMIN_START_MAIN_CAM,{isSyncForced:r});return}if(t===v.ADMIN_STOP_MAIN_CAM){this.events.trigger(u.ADMIN_STOP_MAIN_CAM,{isSyncForced:r});return}(t===v.RESUME_MAIN_CAM||t===v.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(u.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:r});const i=e.getHeader(l.MAIN_CAM_RESOLUTION);this.events.trigger(u.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:i})};triggerMicControl=e=>{const t=e.getHeader(l.MIC),r=e.getHeader(l.MEDIA_SYNC)===x.ADMIN_SYNC_FORCED;t===H.ADMIN_START_MIC?this.events.trigger(u.ADMIN_START_MIC,{isSyncForced:r}):t===H.ADMIN_STOP_MIC&&this.events.trigger(u.ADMIN_STOP_MIC,{isSyncForced:r})};triggerUseLicense=e=>{const t=e.getHeader(l.CONTENT_USE_LICENSE);this.events.trigger(u.USE_LICENSE,t)};triggerRestart=e=>{const t=e.getHeader(l.TRACKS_DIRECTION),s=Number(e.getHeader(l.AUDIO_TRACK_COUNT)),r=Number(e.getHeader(l.VIDEO_TRACK_COUNT)),i={tracksDirection:t,audioTrackCount:s,videoTrackCount:r};this.events.trigger(u.RESTART,i)}}var N=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n.CALL_STATUS_CHANGED="call-status-changed",n))(N||{}),ae=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(ae||{});const oe=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","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"],Fe=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed"],ce=[...oe,...Fe],ke=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},B=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const r=t==="recvonly"?[]:n.getAudioTracks(),i=e==="recvonly"?[]:n.getVideoTracks(),a=[...r,...i],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&ke(o,s),o};function $e(n){return e=>`sip:${e}@${n}`}const qe=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,de=n=>n.trim().replaceAll(" ","_"),Ve=qe(1e5,99999999),We=n=>n.some(t=>{const{kind:s}=t;return s==="video"});class He{isPendingCall=!1;isPendingAnswer=!1;rtcSession;remoteStreams={};events;callConfiguration={};constructor(e){this.events=e}}var X=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(X||{});class xe{remoteStreams={};reset(){this.remoteStreams={}}generateStream(e,t){const{id:s}=e,r=this.remoteStreams[s]??new MediaStream;return t&&r.addTrack(t),r.addTrack(e),this.remoteStreams[s]=r,r}generateAudioStream(e){const{id:t}=e,s=this.remoteStreams[t]??new MediaStream;return s.addTrack(e),this.remoteStreams[t]=s,s}generateStreams(e){const t=[];return e.forEach((s,r)=>{if(s.kind==="audio")return;const i=s,a=e[r-1];let o;a?.kind==="audio"&&(o=a);const c=this.generateStream(i,o);t.push(c)}),t}generateAudioStreams(e){return e.map(t=>this.generateAudioStream(t))}}class Ge extends He{remoteStreamsManager=new xe;disposers=new Set;constructor(e){super(e),e.on(N.FAILED,this.handleEnded),e.on(N.ENDED,this.handleEnded)}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}startCall=async(e,t,{number:s,mediaStream:r,extraHeaders:i=[],ontrack:a,iceServers:o,directionVideo:c,directionAudio:h,contentHint:T,offerToReceiveAudio:S=!0,offerToReceiveVideo:g=!0,degradationPreference:E,sendEncodings:_,onAddedTransceiver:I})=>(this.isPendingCall=!0,new Promise((R,w)=>{this.callConfiguration.number=s,this.callConfiguration.answer=!1,this.handleCall({ontrack:a}).then(R).catch(q=>{w(q)}),this.rtcSession=e.call(t(s),{mediaStream:B(r,{directionVideo:c,directionAudio:h,contentHint:T}),pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:S,offerToReceiveVideo:g},eventHandlers:this.events.triggers,extraHeaders:i,directionVideo:c,directionAudio:h,degradationPreference:E,sendEncodings:_,onAddedTransceiver:I})}).finally(()=>{this.isPendingCall=!1}));async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:X.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,ontrack:s,extraHeaders:r=[],iceServers:i,directionVideo:a,directionAudio:o,offerToReceiveAudio:c,offerToReceiveVideo:h,contentHint:T,degradationPreference:S,sendEncodings:g,onAddedTransceiver:E})=>(this.isPendingAnswer=!0,new Promise((_,I)=>{try{const R=e();this.rtcSession=R,this.subscribeToSessionEvents(R),this.callConfiguration.answer=!0,this.callConfiguration.number=R.remote_identity.uri.user,this.handleCall({ontrack:s}).then(_).catch(w=>{I(w)}),R.answer({pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:h},mediaStream:B(t,{directionVideo:a,directionAudio:o,contentHint:T}),extraHeaders:r,directionVideo:a,directionAudio:o,degradationPreference:S,sendEncodings:g,onAddedTransceiver:E})}catch(R){I(R)}}).finally(()=>{this.isPendingAnswer=!1}));getEstablishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}getCallConfiguration(){return{...this.callConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return We(t)?this.remoteStreamsManager.generateStreams(t):this.remoteStreamsManager.generateAudioStreams(t)}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},r=B(e,{contentHint:s});if(r===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(r,t)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}async addTransceiver(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.addTransceiver(e,t)}handleCall=async({ontrack:e})=>new Promise((t,s)=>{const r=()=>{this.events.on(N.PEER_CONNECTION,T),this.events.on(N.CONFIRMED,S)},i=()=>{this.events.off(N.PEER_CONNECTION,T),this.events.off(N.CONFIRMED,S)},a=()=>{this.events.on(N.FAILED,c),this.events.on(N.ENDED,c)},o=()=>{this.events.off(N.FAILED,c),this.events.off(N.ENDED,c)},c=g=>{i(),o(),s(g)};let h;const T=({peerconnection:g})=>{h=g;const E=_=>{this.events.trigger(N.PEER_CONNECTION_ONTRACK,_),e&&e(_)};g.addEventListener("track",E),this.disposers.add(()=>{g.removeEventListener("track",E)})},S=()=>{h!==void 0&&this.events.trigger(N.PEER_CONNECTION_CONFIRMED,h),i(),o(),t(h)};r(),a()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const r=oe.find(i=>i===s);r&&(e.on(r,t),this.disposers.add(()=>{e.off(r,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t==="remote"&&this.events.trigger(N.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.remoteStreamsManager.reset(),this.unsubscribeFromSessionEvents(),this.callConfiguration.number=void 0,this.callConfiguration.answer=!1}}class Qe{events;strategy;constructor(e){this.events=new y.TypedEvents(ce),this.strategy=e??new Ge(this.events),this.subscribeCallStatusChange()}get requested(){return this.strategy.requested}get connection(){return this.strategy.connection}get establishedRTCSession(){return this.strategy.establishedRTCSession}get isCallActive(){return this.strategy.isCallActive}on(e,t){return this.events.on(e,t)}onRace(e,t){return this.events.onRace(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}setStrategy(e){this.strategy=e}startCall=async(...e)=>this.strategy.startCall(...e);endCall=async()=>this.strategy.endCall();answerToIncomingCall=async(...e)=>this.strategy.answerToIncomingCall(...e);getEstablishedRTCSession=()=>this.strategy.getEstablishedRTCSession();getCallConfiguration=()=>this.strategy.getCallConfiguration();getRemoteStreams=()=>this.strategy.getRemoteStreams();addTransceiver=async(...e)=>this.strategy.addTransceiver(...e);replaceMediaStream=async(...e)=>this.strategy.replaceMediaStream(...e);restartIce=async e=>this.strategy.restartIce(e);subscribeCallStatusChange(){let{isCallActive:e}=this;const{ACCEPTED:t,CONFIRMED:s,ENDED:r,FAILED:i}=N;this.onRace([t,s,r,i],()=>{e=this.maybeTriggerCallStatus(e)})}maybeTriggerCallStatus(e){const t=this.isCallActive;return t!==e&&this.events.trigger(N.CALL_STATUS_CHANGED,{isCallActive:t}),t}}const Ye=(n,e)=>(n.degradationPreference=e.degradationPreference,n),ze=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},he=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,Xe=he(),Je=(n,e)=>{if(Xe(n,e))return n},Ke=(n,e)=>{const t=n.maxBitrate,s=Je(e,t);return s!==void 0&&(n.maxBitrate=s),n},le=1,je=he(le),Ze=(n,e)=>{const t=n===void 0?void 0:Math.max(n,le);if(t!==void 0&&je(t,e))return t},et=(n,e)=>{const t=n.scaleResolutionDownBy,s=Ze(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},tt=(n,e)=>{const t=e.encodings?.length??0;return ze(n,t),n.encodings.forEach((s,r)=>{const i=(e?.encodings??[])[r],a=i?.maxBitrate,o=i?.scaleResolutionDownBy;Ke(s,a),et(s,o)}),n},nt=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},ge=async(n,e)=>{const t=n.getParameters(),s=JSON.parse(JSON.stringify(t));tt(t,e),Ye(t,e);const r=nt(s,t);return r&&await n.setParameters(t),{parameters:t,isChanged:r}},J=async(n,e,t)=>{const{isChanged:s,parameters:r}=await ge(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(r),{isChanged:s,parameters:r}},st=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),rt=async(n,e,t)=>{const s=st(n,e);if(s)return J(s,{maxBitrate:t})};var f=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(f||{});const ue=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],it=1,at=n=>Q.hasCanceledError(n);class ot{events;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=new y.Events(ue),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async startPresentation(e,t,{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:t,presentationOptions:{isNeedReinvite:s,contentHint:r,sendEncodings:i,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const r=this.callManager.getEstablishedRTCSession();return r&&t?s=e().then(async()=>r.stopPresentation(t)).catch(i=>{throw this.events.trigger(f.FAILED_PRESENTATION,i),i}):t&&this.events.trigger(f.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{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,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:i}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(f.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(f.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(f.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(f.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(f.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:r,options:i={callLimit:it}}){const a=async()=>this.sendPresentation(e,t,s,r),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=Q.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:r=!0,contentHint:i="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const h=B(s,{contentHint:i});if(h===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=h;const T=e().then(async()=>t.startPresentation(h,r,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(S=>{throw this.removeStreamPresentationCurrent(),this.events.trigger(f.FAILED_PRESENTATION,S),S});return this.promisePendingStartPresentation=T,T.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const r=e.getSenders();await rt(r,t,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}}class ct{data={};getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){return{...this.data}}set(e){this.data={...e}}update(e,t){this.data[e]=t}clear(){this.data={}}isRegister(){return this.data.register===!0}getSipServerUrl(){return this.data.sipServerUrl}getDisplayName(){return this.data.displayName}getUser(){return this.data.user}getPassword(){return this.data.password}isRegisterEnabled(){return this.data.register===!0}}var A=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.DISCONNECTING="disconnecting",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n.CONNECT_STARTED="connect-started",n.CONNECT_SUCCEEDED="connect-succeeded",n.CONNECT_FAILED="connect-failed",n.CONNECT_PARAMETERS_RESOLVE_FAILED="connect-parameters-resolve-failed",n))(A||{});const Te=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],dt=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-failed"],Se=[...Te,...dt],ht=3;class lt{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setSipServerUrl;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setSipServerUrl=e.setSipServerUrl,this.setSocket=e.setSocket}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const r=this.getUa();if(!r){s(new Error("this.ua is not initialized"));return}let i=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a.displayName&&(i=r.set("display_name",de(e)),this.updateConnectionConfiguration("displayName",e));const o=i;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{this.events.trigger(A.DISCONNECTING,{});const e=new Promise(s=>{this.events.once(A.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(A.DISCONNECTED,{socket:{},error:!1}),e.finally(()=>{this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=ht}={})=>{const s=async()=>this.connectInner(e),r=i=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),h=i!=null&&!Ue(i);return c||h};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=Q.repeatedCallsAsync({targetFunction:s,isComplete:r,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(i=>{if(i instanceof this.JsSIP.UA)return i;throw i})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),r=this.getUa()?.configuration;return r?r.password===t.password&&r.register===t.register&&r.uri.toString()===t.uri&&r.display_name===t.display_name&&r.user_agent===t.user_agent&&r.sockets===t.sockets&&r.session_timers===t.session_timers&&r.register_expires===t.register_expires&&r.connection_recovery_min_interval===t.connection_recovery_min_interval&&r.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start());initUa=async({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:r,remoteAddress:i,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:T,displayName:S="",register:g=!1,extraHeaders:E=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerUrl:s,displayName:S,register:g,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:I,helpers:R}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:r,displayName:S,register:g,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:T,remoteAddress:i,extraHeaders:E},this.events);return this.setUa(I),this.setSipServerUrl(R.getSipServerUrl),this.setSocket(R.socket),I};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let r;r=((c,h)=>{if(this.getConnectionConfiguration().register===!0)return this.registrationManager.subscribeToStartEvents(c,h);const S=A.CONNECTED,g=[A.DISCONNECTED];return this.events.on(S,c),g.forEach(E=>{this.events.on(E,h)}),()=>{this.events.off(S,c),g.forEach(E=>{this.events.off(E,h)})}})(()=>{r?.(),e(s)},c=>{r?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}}var Ce=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(Ce||{});const gt=se.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"idle",context:{},states:{idle:{entry:{type:"logStateChange",params:{state:"idle"}},on:{START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"idle",to:"connecting",event:"START_CONNECT"}}}}},connecting:{entry:{type:"logStateChange",params:{state:"connecting"}},on:{START_INIT_UA:{target:"initializing",actions:{type:"logTransition",params:{from:"connecting",to:"initializing",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connecting",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connecting",to:"failed",event:"CONNECTION_FAILED"}}}}},initializing:{entry:{type:"logStateChange",params:{state:"initializing"}},on:{UA_CONNECTED:{target:"connected",actions:{type:"logTransition",params:{from:"initializing",to:"connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"initializing",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"initializing",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"initializing",to:"failed",event:"CONNECTION_FAILED"}}}}},connected:{entry:{type:"logStateChange",params:{state:"connected"}},on:{UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"connected",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connected",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connected",to:"failed",event:"CONNECTION_FAILED"}}}}},registered:{entry:{type:"logStateChange",params:{state:"registered"}},on:{UA_UNREGISTERED:{target:"connected",actions:{type:"logTransition",params:{from:"registered",to:"connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"registered",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"registered",to:"failed",event:"CONNECTION_FAILED"}}}}},disconnected:{entry:{type:"logStateChange",params:{state:"disconnected"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"disconnected",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"disconnected",to:"connecting",event:"START_CONNECT"}}}}},failed:{entry:{type:"logStateChange",params:{state:"failed"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"failed",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"failed",to:"connecting",event:"START_CONNECT"}}}}}}});class ut{actor;stateChangeListeners=new Set;events;unsubscribeFromEvents;actorSubscription;constructor(e){this.events=e,this.actor=se.createActor(gt),this.actorSubscription=this.actor.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(r=>{r(s)})}),this.actor.start(),this.subscribeToEvents()}get state(){return this.actor.getSnapshot().value}get isIdle(){return this.hasState("idle")}get isConnecting(){return this.hasState("connecting")}get isInitializing(){return this.hasState("initializing")}get isConnected(){return this.hasState("connected")}get isRegistered(){return this.hasState("registered")}get isDisconnected(){return this.hasState("disconnected")}get isFailed(){return this.hasState("failed")}get isPending(){return this.isConnecting||this.isInitializing}get isPendingConnect(){return this.isConnecting}get isPendingInitUa(){return this.isInitializing}get isActiveConnection(){return this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.actorSubscription?.unsubscribe(),this.actor.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return Object.values(Ce).filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){const t=this.actor.getSnapshot(),s={type:e};if(!t.can(s)){d(`Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`);return}this.actor.send(s)}toStartConnect=()=>{this.sendEvent("START_CONNECT")};toStartInitUa=()=>{this.sendEvent("START_INIT_UA")};toConnected=()=>{this.sendEvent("UA_CONNECTED")};toRegistered=()=>{this.sendEvent("UA_REGISTERED")};toUnregistered=()=>{this.sendEvent("UA_UNREGISTERED")};toDisconnected=()=>{this.sendEvent("UA_DISCONNECTED")};toFailed=()=>{this.sendEvent("CONNECTION_FAILED")};toIdle=()=>{this.sendEvent("RESET")};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toFailed)}}}class Tt{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(A.REGISTERED,t),e.on(A.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(A.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){d("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=A.REGISTERED,r=[A.REGISTRATION_FAILED,A.DISCONNECTED];return this.events.on(s,e),r.forEach(i=>{this.events.on(i,t)}),()=>{this.events.off(s,e),r.forEach(i=>{this.events.off(i,t)})}}}class St{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const r=this.getUaProtected();return new Promise((i,a)=>{try{r.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{i()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const r=this.getUaProtected().configuration.uri;return this.sendOptions(r,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:s,sipWebSocketServerURL:r,remoteAddress:i,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:h}=this.uaFactory.createConfiguration({sipWebSocketServerURL:r,displayName:t,userAgent:e,sipServerUrl:s}),T=this.uaFactory.createUA({...h,remoteAddress:i,extraHeaders:a}),S=()=>{const E=new Error("Telephony is not available");c(E)};T.once(A.DISCONNECTED,S);const g=()=>{T.removeAllListeners(),T.once(A.DISCONNECTED,()=>{o()}),T.stop()};T.once(A.CONNECTED,g),T.start()})}}const Ct=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class D{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:s,sipServerUrl:r,sipWebSocketServerURL:i}){if(!r)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(e&&(t===void 0||t===""))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,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${Ve()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?Ct(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipWebSocketServerURL:s,displayName:r="",sipServerUrl:i,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:T=6,userAgent:S}){D.validateParametersConnection({register:a,password:t,user:e,sipServerUrl:i,sipWebSocketServerURL:s});const g=D.resolveAuthorizationUser(a,e),E=$e(i),_=E(g),I=new this.JsSIP.WebSocketInterface(s);return{configuration:{password:t,register:a,uri:_,display_name:de(r),user_agent:S,sdpSemantics:"unified-plan",sockets:[I],session_timers:o,register_expires:c,connection_recovery_min_interval:h,connection_recovery_max_interval:T},helpers:{socket:I,getSipServerUrl:E}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const r=new this.JsSIP.UA(s),i=D.buildExtraHeaders(e,t);return i.length>0&&r.registrator().setExtraHeaders(i),r}createUAWithConfiguration(e,t){const{configuration:s,helpers:r}=this.createConfiguration(e),i=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=Te.find(h=>h===o);c&&i.on(c,a)}),{ua:i,helpers:r}}}const Ee="Not ready for connection",Ae=n=>n instanceof Error&&n.message===Ee,Et=()=>new Error(Ee),Ne=async n=>typeof n=="function"?n():n;class At{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=new y.TypedEvents(Se),this.uaFactory=new D(e),this.registrationManager=new Tt({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new ut(this.events),this.configurationManager=new ct({getUa:this.getUa}),this.sipOperations=new St({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new lt({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setSipServerUrl:t=>{this.getSipServerUrl=t},setSocket:t=>{this.socket=t}})}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 isFailed(){return this.stateMachine.isFailed}get connectionState(){return this.stateMachine.state}get isRegistered(){return D.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.disconnect().catch(s=>{d("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,t));set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>{if(this.isConfigured())return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getSipServerUrl=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw Et();return this.processConnect(e,t).catch(async r=>{const i=r;return this.disconnect().then(()=>{throw i}).catch(()=>{throw i})})};processConnect=async(e,t)=>(this.events.trigger(A.CONNECT_STARTED,{}),Ne(e).catch(s=>{throw this.events.trigger(A.CONNECT_PARAMETERS_RESOLVE_FAILED,s),s}).then(async s=>this.connectionFlow.connect(s,t)).then(s=>(this.events.trigger(A.CONNECT_SUCCEEDED,{ua:s}),s)).catch(s=>{const r=s??new Error("Failed to connect to server");throw this.events.trigger(A.CONNECT_FAILED,r),r}))}class Nt{connectionManager;stackPromises=Y.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()}}var O=(n=>(n.BEFORE_ATTEMPT="before-attempt",n.SUCCEEDED_ATTEMPT="succeeded-attempt",n.FAILED_ATTEMPT="failed-attempt",n.CANCELLED_ATTEMPT="cancelled-attempt",n.CHANGED_ATTEMPT_STATUS="changed-attempt-status",n))(O||{});const Re=["before-attempt","succeeded-attempt","failed-attempt","cancelled-attempt","changed-attempt-status"],j=0,Rt=30;class It{events;countInner=j;initialCount=j;limitInner=Rt;isInProgress=!1;constructor({events:e}){this.events=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.emitStatusChange())}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.emitStatusChange())}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}emitStatusChange(){this.events.trigger(O.CHANGED_ATTEMPT_STATUS,{isInProgress:this.isInProgress})}}class pt{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableBeforeRequest=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start({onBeforeRequest:e,onSuccessRequest:t,onFailRequest:s}){this.stop(),this.cancelableBeforeRequest=new $.CancelableRequest(e),this.checkTelephonyByTimeout=b.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableBeforeRequest)throw new Error("cancelableBeforeRequest is not defined");const r=await this.cancelableBeforeRequest.request();return this.connectionManager.checkTelephony(r)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableBeforeRequest?.cancelRequest(),this.cancelableBeforeRequest=void 0}}const _t=15e3,mt=2;class Mt{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=b.requesterByTimeoutsWithFailCalls(mt,{whenPossibleRequest:async()=>{},requestInterval:_t,request:async()=>(d("ping"),this.connectionManager.ping().then(()=>{d("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(d)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}class vt{callManager;pingServerRequester;disposeCallStatusChange;constructor({connectionManager:e,callManager:t}){this.callManager=t,this.pingServerRequester=new Mt({connectionManager:e})}start({onFailRequest:e}){d("start"),this.disposeCallStatusChange=this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange({onFailRequest:e})}),this.handleCallStatusChange({onFailRequest:e})}stop(){d("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.disposeCallStatusChange?.(),this.disposeCallStatusChange=void 0}handleCallStatusChange({onFailRequest:e}){this.callManager.isCallActive?this.pingServerRequester.stop():this.pingServerRequester.start({onFailRequest:e})}}class Pt{connectionManager;callManager;isRegistrationFailed=!1;disposers=[];constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.disposers.push(this.callManager.on("call-status-changed",({isCallActive:t})=>{!t&&this.isRegistrationFailed&&e()}))}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const ft=3e3,Ot=15e3,yt=async()=>{},Dt=n=>!0;class bt{events;connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;cancelableRequestBeforeRetry;onBeforeRetry;canRetryOnError;constructor({connectionQueueManager:e,connectionManager:t,callManager:s},r){const i=r?.onBeforeRetry??yt,a=r?.canRetryOnError??Dt;this.connectionQueueManager=e,this.connectionManager=t,this.onBeforeRetry=i,this.canRetryOnError=a,this.events=new y.TypedEvents(Re),this.checkTelephonyRequester=new pt({connectionManager:t,interval:r?.checkTelephonyRequestInterval??Ot}),this.pingServerIfNotActiveCallRequester=new vt({connectionManager:t,callManager:s}),this.registrationFailedOutOfCallSubscriber=new Pt({connectionManager:t,callManager:s}),this.attemptsState=new It({events:this.events}),this.cancelableRequestBeforeRetry=new $.CancelableRequest(i),this.delayBetweenAttempts=new b.DelayRequester(r?.timeoutBetweenAttempts??ft)}start(e){d("auto connector start"),this.stop(),this.connect(e).catch(t=>{d("auto connector failed to connect:",t)})}stop(){d("auto connector stop"),this.stopAttempts(),this.stopConnectTriggers(),this.connectionQueueManager.disconnect().catch(e=>{d("auto connector disconnect: error",e)})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.delayBetweenAttempts.cancelRequest(),this.cancelableRequestBeforeRetry.cancelRequest(),this.attemptsState.reset()}stopConnectTriggers(){d("stopConnectTriggers"),this.pingServerIfNotActiveCallRequester.stop(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}runCheckTelephony(e){d("runCheckTelephony"),this.checkTelephonyRequester.start({onBeforeRequest:async()=>(await this.onBeforeRetry(),e.getParameters()),onSuccessRequest:()=>{d("runCheckTelephony: onSuccessRequest"),this.connectIfDisconnected(e)},onFailRequest:t=>{d("runCheckTelephony: onFailRequest",t.message)}})}async connect(e){if(d("connect: attempts.count",this.attemptsState.count),this.events.trigger(O.BEFORE_ATTEMPT,{}),this.stopConnectTriggers(),this.attemptsState.hasLimitReached()){d("connect: isLimitReached!"),this.handleLimitReached(e);return}return this.attemptsState.startAttempt(),this.attemptsState.increment(),this.processConnect(e)}async processConnect(e){try{await this.connectionQueueManager.connect(e.getParameters,e.options),d("processConnect success"),this.handleSucceededAttempt(e)}catch(t){if(Ae(t)){this.handleSucceededAttempt(e);return}if(!this.canRetryOnError(t)){d("processConnect: error does not allow retry",t);return}if(Y.isPromiseIsNotActualError(t)){d("processConnect: not actual error",t),this.events.trigger(O.CANCELLED_ATTEMPT,t);return}d("processConnect: error",t),this.reconnect(e)}}handleLimitReached(e){this.attemptsState.finishAttempt(),this.events.trigger(O.FAILED_ATTEMPT,new Error("Limit reached")),this.runCheckTelephony(e)}handleSucceededAttempt(e){d("handleSucceededAttempt"),this.subscribeToConnectTriggers(e),this.events.trigger(O.SUCCEEDED_ATTEMPT,{})}subscribeToConnectTriggers(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{d("pingServer onFailRequest"),this.start(e)}}),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{d("registrationFailedOutOfCallListener callback"),this.start(e)})}connectIfDisconnected(e){const t=this.hasFailedOrDisconnectedConnection();d("connectIfDisconnected: isFailedOrDisconnected",t),t?this.start(e):(this.stopConnectTriggers(),this.events.trigger(O.SUCCEEDED_ATTEMPT,{}))}reconnect(e){d("reconnect"),this.delayBetweenAttempts.request().then(async()=>(d("reconnect: delayBetweenAttempts success"),this.cancelableRequestBeforeRetry.request())).then(async()=>(d("reconnect: onBeforeRetry success"),this.connect(e))).catch(t=>{const s=t instanceof Error?t:new Error("Failed to reconnect");$.isCanceledError(t)||b.hasCanceledError(t)?this.events.trigger(O.CANCELLED_ATTEMPT,s):this.events.trigger(O.FAILED_ATTEMPT,s),d("reconnect: error",t)})}hasFailedOrDisconnectedConnection(){const{isFailed:e,isDisconnected:t,isIdle:s}=this.connectionManager;return e||t||s}}var L=(n=>(n.INCOMING_CALL="incomingCall",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(L||{});const Ie=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],wt=486,Ut=487;class Lt{events;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=new y.Events(Ie),this.start()}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession: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.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=Ut}={}){return new Promise((t,s)=>{try{const r=this.getIncomingRTCSession(),i=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(L.DECLINED_INCOMING_CALL,i),r.terminate({status_code:e}),t()}catch(r){s(r)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:wt})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e==="remote"&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger(L.TERMINATED_INCOMING_CALL,t):this.events.trigger(L.FAILED_INCOMING_CALL,t)}),this.events.trigger(L.INCOMING_CALL,t)}removeIncomingSession(){delete this.incomingRTCSession}}const U=1e3;var C=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(C||{});const pe=["collected"],Z=()=>"performance"in window?performance.now():Date.now(),F=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),Bt=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=F(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},ee=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=F(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},te=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=F(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],synchronizationSources:e}},Ft=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=F(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],remoteOutboundRtp:t[C.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},_e=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=F(n);return{candidatePair:e[C.CANDIDATE_PAIR],certificate:e[C.CERTIFICATE],localCandidate:e[C.LOCAL_CANDIDATE],remoteCandidate:e[C.REMOTE_CANDIDATE],transport:e[C.TRANSPORT]}},kt=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:ee(e),secondVideo:ee(t),audio:Bt(n),additional:_e(n??e??t)}),$t=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:te({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:te({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:Ft({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:_e(n??e??t)}),qt=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a})=>{const o=kt({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=$t({audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a});return{outbound:o,inbound:c}},Vt=async n=>{const e="audio",t="video",s=n.getSenders(),r=s.find(g=>g.track?.kind===e),i=s.filter(g=>g.track?.kind===t),a=n.getReceivers(),o=a.find(g=>g.track.kind===e),c=a.filter(g=>g.track.kind===t),h={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},T={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},S={audio:h,video:T};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(g=>{const[E,_,I,R,w,q]=g;return{synchronizationSources:S,audioSenderStats:E,videoSenderFirstStats:_,videoSenderSecondStats:I,audioReceiverStats:R,videoReceiverFirstStats:w,videoReceiverSecondStats:q}})},Wt=n=>{d(String(n))};class me{events;setTimeoutRequest;requesterAllStatistics=new $.CancelableRequest(Vt);constructor(){this.events=new y.TypedEvents(pe),this.setTimeoutRequest=new b.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=U,onError:s=Wt}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=Z();this.requesterAllStatistics.request(e).then(r=>{this.events.trigger("collected",qt(r));const a=Z()-s;let o=U;a>48?o=U*4:a>32?o=U*3:a>16&&(o=U*2),this.start(e,{onError:t,interval:o})}).catch(r=>{t&&t(r)})}}class Ht{availableIncomingBitrate;statsPeerConnection;callManager;apiManager;previousAvailableIncomingBitrate;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new me,this.subscribe()}get events(){return this.statsPeerConnection.events}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableIncomingBitrate=this.availableIncomingBitrate,this.availableIncomingBitrate=e.inbound.additional.candidatePair?.availableIncomingBitrate,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableIncomingBitrate=void 0,this.previousAvailableIncomingBitrate=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{d("Failed to send stats",e)})}}const xt=(n,e)=>n.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),Gt=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return xt(s,r)},Qt=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const r=e.indexOf(t.mimeType),i=e.indexOf(s.mimeType),a=r===-1?Number.MAX_VALUE:r,o=i===-1?Number.MAX_VALUE:i;return a-o}),Yt=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),zt=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=Gt("video"),r=Yt(s,t),i=Qt(r,e);n.setCodecPreferences(i)}}catch(s){d("setCodecPreferences error",s)}};class Xt{transceivers={};callManager;apiManager;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.subscribe()}storeTransceiver(e,t){const{kind:s}=t;if(s==="audio")this.transceivers.mainAudio??=e;else{const{mid:r}=e;r==="2"?this.transceivers.presentationVideo??=e:this.transceivers.mainVideo??=e}}getTransceivers(){return{...this.transceivers}}getMainAudioTransceiver(){return this.transceivers.mainAudio}getMainVideoTransceiver(){return this.transceivers.mainVideo}getPresentationVideoTransceiver(){return this.transceivers.presentationVideo}hasTransceiver(e){return this.transceivers[e]!==void 0}clear(){this.transceivers.mainVideo=void 0,this.transceivers.mainAudio=void 0,this.transceivers.presentationVideo=void 0}getCount(){let e=0;return this.transceivers.mainAudio&&(e+=1),this.transceivers.mainVideo&&(e+=1),this.transceivers.presentationVideo&&(e+=1),e}isEmpty(){return this.getCount()===0}handleRestart=e=>{this.updateTransceivers(e).catch(t=>{d("Failed to update transceivers",t)}).finally(()=>{this.callManager.restartIce().catch(t=>{d("Failed to restart ICE",t)})})};updateTransceivers=async e=>{const{videoTrackCount:t}=e;t===2&&(this.getTransceivers().presentationVideo!==void 0||await this.callManager.addTransceiver("video",{direction:"recvonly"}).catch(i=>{d("Failed to add presentation video transceiver",i)}))};subscribe(){this.callManager.on("peerconnection:ontrack",this.handleTrack),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.apiManager.on("restart",this.handleRestart)}handleTrack=e=>{this.storeTransceiver(e.transceiver,e.track)};handleEnded=()=>{this.clear()}}const Jt=n=>[...n.keys()].map(e=>n.get(e)),Kt=(n,e)=>Jt(n).find(t=>t?.type===e),Me=async n=>n.getStats().then(e=>Kt(e,"codec")?.mimeType);class jt{async getCodecFromSender(e){return await Me(e)??""}}class Zt{stackPromises=Y.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{d("TaskQueue: error",e)})}}class en{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Zt}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>J(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const ve=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),tn=1e6,M=n=>n*tn,Pe=M(.06),fe=M(4),nn=n=>n<=64?Pe:n<=128?M(.12):n<=256?M(.25):n<=384?M(.32):n<=426?M(.38):n<=640?M(.5):n<=848?M(.7):n<=1280?M(1):n<=1920?M(2):fe,sn="av1",rn=n=>ve(n,sn),an=.6,K=(n,e)=>rn(e)?n*an:n,on=n=>K(Pe,n),cn=n=>K(fe,n),ne=(n,e)=>{const t=nn(n);return K(t,e)},V=1,dn=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,r=t.height,i=s===void 0?V:s/e.width,a=r===void 0?V:r/e.height;return Math.max(i,a,V)};class hn{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},r){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=r.ignoreForCodec}async balance(e,t){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(ve(i,this.ignoreForCodec))return{...this.resultNoChanged,sender:r};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:r,codec:i,videoTrack:r.track}).then(c=>({...c,sender:r}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:r}=e;switch(s){case v.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case v.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case v.MAX_MAIN_CAM_RESOLUTION:return r!==void 0?this.setResolutionSender(r,t):this.setBitrateByTrackResolution(t);case v.ADMIN_STOP_MAIN_CAM:case v.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,r={scaleResolutionDownBy:200,maxBitrate:on(s)};return this.parametersSetter.setEncodingsToSender(t,r)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:r}=e,a=s.getSettings().width,o=a===void 0?cn(r):ne(a,r);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,r]=e.split("x"),{sender:i,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(r)},h=dn({videoTrack:a,targetSize:c}),T=ne(c.width,o),S={scaleResolutionDownBy:h,maxBitrate:T};return this.parametersSetter.setEncodingsToSender(i,S)}}const ln=n=>n.find(e=>e.track?.kind==="video");class gn{findVideoSender(e){return ln(e)}}class un{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new b.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async r=>{await s(r),this.attachTrack(t,r??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:r}=t.getSettings();this.lastWidth=s,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){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,t()):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 Tn{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)}}class Sn{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:r,pollIntervalMs:i}={}){this.getConnection=t,this.eventHandler=new Tn(e),this.parametersSetterWithQueue=new en(r),this.senderBalancer=new hn({senderFinder:new gn,codecProvider:new jt,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new un({pollIntervalMs:i})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{d("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{d("handleMainCamControl: error",t)})}}const Oe=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"];class Cn{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=new y.TypedEvents(Oe),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new Sn(t,()=>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()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{d("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const En=1e6,An=Re.map(n=>`auto-connect:${n}`),Nn=Se.map(n=>`connection:${n}`),Rn=ce.map(n=>`call:${n}`),In=ie.map(n=>`api:${n}`),pn=Ie.map(n=>`incoming-call:${n}`),_n=ue.map(n=>`presentation:${n}`),mn=pe.map(n=>`stats:${n}`),Mn=Oe.map(n=>`video-balancer:${n}`),vn=[...An,...Nn,...Rn,...In,...pn,..._n,...mn,...Mn];class Pn{events;connectionManager;connectionQueueManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;transceiverManager;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:r,autoConnectorOptions:i}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=new y.Events(vn),this.connectionManager=new At({JsSIP:e}),this.connectionQueueManager=new Nt({connectionManager:this.connectionManager}),this.callManager=new Qe,this.apiManager=new Be({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new Lt(this.connectionManager),this.presentationManager=new ot({callManager:this.callManager,maxBitrate:En}),this.statsManager=new Ht({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new bt({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},i),this.transceiverManager=new Xt({callManager:this.callManager,apiManager:this.apiManager}),this.videoSendingBalancerManager=new Cn(this.callManager,this.apiManager,r),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 establishedRTCSession(){return this.callManager.establishedRTCSession}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}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();set=async(...e)=>this.connectionManager.set(...e);sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getSipServerUrl=e=>this.connectionManager.getSipServerUrl(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getSipServerUrl,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>this.callManager.getCallConfiguration();getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:r,onAddedTransceiver:i,...a}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...a,onAddedTransceiver:this.resolveHandleAddTransceiver(i)},r===void 0?void 0:{callLimit:r})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{await(t===!0?this.apiManager.sendMustStopPresentationP2P():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{isP2P:s,onAddedTransceiver:r,...i}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...i,onAddedTransceiver:this.resolveHandleAddTransceiver(r)})}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 sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}setCodecPreferences(e){zt(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)}bridgeEvents=(e,t)=>{t.events.eachTriggers((s,r)=>{t.on(r,i=>{this.events.trigger(`${e}:${r}`,i)})})};resolveHandleAddTransceiver=e=>async(t,s,r)=>{this.setCodecPreferences(t),await e?.(t,s,r)}}exports.ECallCause=X;exports.EStatsTypes=C;exports.EUseLicense=re;exports.Originator=ae;exports.SipConnector=Pn;exports.StatsPeerConnection=me;exports.disableDebug=De;exports.enableDebug=ye;exports.getCodecFromSender=Me;exports.hasCanceledStartPresentationError=at;exports.hasNotReadyForConnectionError=Ae;exports.logger=d;exports.prepareMediaStream=B;exports.resolveParameters=Ne;exports.setEncodingsToSender=J;exports.setParametersToSender=ge;
|
|
1
|
+
"use strict";const y=require("events-constructor"),G=require("debug"),$=require("@krivega/cancelable-promise"),b=require("@krivega/timeout-requester"),Q=require("repeated-calls"),se=require("xstate"),Y=require("stack-promises");require("ua-parser-js");require("sequent-promises");const z="sip-connector",d=G(z),ye=()=>{G.enable(z)},De=()=>{G.enable(`-${z}`)},be="Error decline with 603",we=1006,Ue=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===we,Le=n=>n.message===be;var l=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n.AVAILABLE_INCOMING_BITRATE="X-WEBRTC-AVAILABLE-INCOMING-BITRATE",n.AUDIO_TRACK_COUNT="X-WEBRTC-AUDIO-TRACK-COUNT",n.VIDEO_TRACK_COUNT="X-WEBRTC-VIDEO-TRACK-COUNT",n.TRACKS_DIRECTION="X-WEBRTC-TRACKS-DIRECTION",n))(l||{}),k=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(k||{}),W=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(W||{}),f=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.RESTART="application/vinteo.webrtc.restart",n))(f||{}),m=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.STATS="application/vinteo.webrtc.stats",n))(m||{}),P=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(P||{}),H=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(H||{}),x=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(x||{}),re=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(re||{}),u=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n.RESTART="restart",n))(u||{});const ie=["participation:accepting-word-request","participation:cancelling-word-request","participant:move-request-to-stream","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-spectators","participant:move-request-to-participants","channels","enterRoom","shareState","main-cam-control","useLicense","admin-start-main-cam","admin-stop-main-cam","admin-start-mic","admin-stop-mic","admin-force-sync-media-state","availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","newDTMF","restart"];var p=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(p||{});class Be{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=new y.Events(ie),this.subscribe()}async waitChannels(){return this.wait(u.CHANNELS)}async waitSyncMediaState(){return this.wait(u.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let r;try{r=this.getEstablishedRTCSessionProtected()}catch(i){s(i)}r&&(this.callManager.once("newDTMF",({originator:i})=>{i==="local"&&t()}),r.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),r=`${l.INPUT_CHANNELS}: ${e}`,i=`${l.OUTPUT_CHANNELS}: ${t}`,a=[r,i];return s.sendInfo(m.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const r=this.getEstablishedRTCSessionProtected(),i=`${l.MEDIA_STATE}: currentstate`,a=`${l.MAIN_CAM_STATE}: ${Number(e)}`,o=`${l.MIC_STATE}: ${Number(t)}`,c=[i,a,o];return r.sendInfo(m.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),r=[`${l.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(m.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:r})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${l.MEDIA_TYPE}: ${a}`];return s.sendInfo(m.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(m.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[l.ENABLE_MAIN_CAM];return t.sendInfo(m.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(r=>{if(Le(r))throw r})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(l.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){d("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case p.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case p.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case p.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case p.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case p.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case p.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case p.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case p.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case p.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case p.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case p.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:d("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,r=s,i=r.getHeader(l.CONTENT_TYPE);if(i!==void 0)switch(i){case f.ENTER_ROOM:{this.triggerEnterRoom(r),this.maybeTriggerChannels(r);break}case f.NOTIFY:{this.maybeHandleNotify(r);break}case f.SHARE_STATE:{this.triggerShareState(r);break}case f.MAIN_CAM:{this.triggerMainCamControl(r);break}case f.MIC:{this.triggerMicControl(r);break}case f.USE_LICENSE:{this.triggerUseLicense(r);break}case f.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(r);break}case f.RESTART:{this.triggerRestart(r);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,r={inputChannels:t,outputChannels:s};this.events.trigger(u.CHANNELS_NOTIFY,r)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(u.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(u.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(u.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(u.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(u.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(u.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(u.ACCOUNT_CHANGED,void 0)};triggerAccountDeletedNotify=()=>{this.events.trigger(u.ACCOUNT_DELETED,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const r={conference:e,participant:t,jwt:s};this.events.trigger(u.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,r)};maybeTriggerChannels=e=>{const t=e.getHeader(l.INPUT_CHANNELS),s=e.getHeader(l.OUTPUT_CHANNELS);if(t&&s){const r={inputChannels:t,outputChannels:s};this.events.trigger(u.CHANNELS,r)}};triggerEnterRoom=e=>{const t=e.getHeader(l.CONTENT_ENTER_ROOM),s=e.getHeader(l.PARTICIPANT_NAME);this.events.trigger(u.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(l.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case k.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(u.AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case k.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(u.NOT_AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case k.MUST_STOP_PRESENTATION:{this.events.trigger(u.MUST_STOP_PRESENTATION,void 0);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(l.CONTENT_PARTICIPANT_STATE);t===W.SPECTATOR&&this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,void 0),t===W.PARTICIPANT&&this.events.trigger(u.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(l.MAIN_CAM),s=e.getHeader(l.MEDIA_SYNC),r=s===x.ADMIN_SYNC_FORCED;if(t===P.ADMIN_START_MAIN_CAM){this.events.trigger(u.ADMIN_START_MAIN_CAM,{isSyncForced:r});return}if(t===P.ADMIN_STOP_MAIN_CAM){this.events.trigger(u.ADMIN_STOP_MAIN_CAM,{isSyncForced:r});return}(t===P.RESUME_MAIN_CAM||t===P.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(u.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:r});const i=e.getHeader(l.MAIN_CAM_RESOLUTION);this.events.trigger(u.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:i})};triggerMicControl=e=>{const t=e.getHeader(l.MIC),r=e.getHeader(l.MEDIA_SYNC)===x.ADMIN_SYNC_FORCED;t===H.ADMIN_START_MIC?this.events.trigger(u.ADMIN_START_MIC,{isSyncForced:r}):t===H.ADMIN_STOP_MIC&&this.events.trigger(u.ADMIN_STOP_MIC,{isSyncForced:r})};triggerUseLicense=e=>{const t=e.getHeader(l.CONTENT_USE_LICENSE);this.events.trigger(u.USE_LICENSE,t)};triggerRestart=e=>{const t=e.getHeader(l.TRACKS_DIRECTION),s=Number(e.getHeader(l.AUDIO_TRACK_COUNT)),r=Number(e.getHeader(l.VIDEO_TRACK_COUNT)),i={tracksDirection:t,audioTrackCount:s,videoTrackCount:r};this.events.trigger(u.RESTART,i)}}var N=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n.CALL_STATUS_CHANGED="call-status-changed",n))(N||{}),ae=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(ae||{});const oe=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","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"],Fe=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed"],ce=[...oe,...Fe],ke=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},B=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const r=t==="recvonly"?[]:n.getAudioTracks(),i=e==="recvonly"?[]:n.getVideoTracks(),a=[...r,...i],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&ke(o,s),o};function $e(n){return e=>`sip:${e}@${n}`}const qe=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,de=n=>n.trim().replaceAll(" ","_"),Ve=qe(1e5,99999999),We=n=>n.some(t=>{const{kind:s}=t;return s==="video"});class He{isPendingCall=!1;isPendingAnswer=!1;rtcSession;remoteStreams={};events;callConfiguration={};constructor(e){this.events=e}}var X=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(X||{});class xe{remoteStreams={};reset(){this.remoteStreams={}}generateStream(e,t){const{id:s}=e,r=this.remoteStreams[s]??new MediaStream;return t&&r.addTrack(t),r.addTrack(e),this.remoteStreams[s]=r,r}generateAudioStream(e){const{id:t}=e,s=this.remoteStreams[t]??new MediaStream;return s.addTrack(e),this.remoteStreams[t]=s,s}generateStreams(e){const t=[];return e.forEach((s,r)=>{if(s.kind==="audio")return;const i=s,a=e[r-1];let o;a?.kind==="audio"&&(o=a);const c=this.generateStream(i,o);t.push(c)}),t}generateAudioStreams(e){return e.map(t=>this.generateAudioStream(t))}}class Ge extends He{remoteStreamsManager=new xe;disposers=new Set;constructor(e){super(e),e.on(N.FAILED,this.handleEnded),e.on(N.ENDED,this.handleEnded)}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}startCall=async(e,t,{number:s,mediaStream:r,extraHeaders:i=[],ontrack:a,iceServers:o,directionVideo:c,directionAudio:h,contentHint:T,offerToReceiveAudio:S=!0,offerToReceiveVideo:g=!0,degradationPreference:E,sendEncodings:_,onAddedTransceiver:I})=>(this.isPendingCall=!0,new Promise((R,w)=>{this.callConfiguration.number=s,this.callConfiguration.answer=!1,this.handleCall({ontrack:a}).then(R).catch(q=>{w(q)}),this.rtcSession=e.call(t(s),{mediaStream:B(r,{directionVideo:c,directionAudio:h,contentHint:T}),pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:S,offerToReceiveVideo:g},eventHandlers:this.events.triggers,extraHeaders:i,directionVideo:c,directionAudio:h,degradationPreference:E,sendEncodings:_,onAddedTransceiver:I})}).finally(()=>{this.isPendingCall=!1}));async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:X.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,ontrack:s,extraHeaders:r=[],iceServers:i,directionVideo:a,directionAudio:o,offerToReceiveAudio:c,offerToReceiveVideo:h,contentHint:T,degradationPreference:S,sendEncodings:g,onAddedTransceiver:E})=>(this.isPendingAnswer=!0,new Promise((_,I)=>{try{const R=e();this.rtcSession=R,this.subscribeToSessionEvents(R),this.callConfiguration.answer=!0,this.callConfiguration.number=R.remote_identity.uri.user,this.handleCall({ontrack:s}).then(_).catch(w=>{I(w)}),R.answer({pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:h},mediaStream:B(t,{directionVideo:a,directionAudio:o,contentHint:T}),extraHeaders:r,directionVideo:a,directionAudio:o,degradationPreference:S,sendEncodings:g,onAddedTransceiver:E})}catch(R){I(R)}}).finally(()=>{this.isPendingAnswer=!1}));getEstablishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}getCallConfiguration(){return{...this.callConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return We(t)?this.remoteStreamsManager.generateStreams(t):this.remoteStreamsManager.generateAudioStreams(t)}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},r=B(e,{contentHint:s});if(r===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(r,t)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}async addTransceiver(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.addTransceiver(e,t)}handleCall=async({ontrack:e})=>new Promise((t,s)=>{const r=()=>{this.events.on(N.PEER_CONNECTION,T),this.events.on(N.CONFIRMED,S)},i=()=>{this.events.off(N.PEER_CONNECTION,T),this.events.off(N.CONFIRMED,S)},a=()=>{this.events.on(N.FAILED,c),this.events.on(N.ENDED,c)},o=()=>{this.events.off(N.FAILED,c),this.events.off(N.ENDED,c)},c=g=>{i(),o(),s(g)};let h;const T=({peerconnection:g})=>{h=g;const E=_=>{this.events.trigger(N.PEER_CONNECTION_ONTRACK,_),e&&e(_)};g.addEventListener("track",E),this.disposers.add(()=>{g.removeEventListener("track",E)})},S=()=>{h!==void 0&&this.events.trigger(N.PEER_CONNECTION_CONFIRMED,h),i(),o(),t(h)};r(),a()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const r=oe.find(i=>i===s);r&&(e.on(r,t),this.disposers.add(()=>{e.off(r,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t==="remote"&&this.events.trigger(N.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.remoteStreamsManager.reset(),this.unsubscribeFromSessionEvents(),this.callConfiguration.number=void 0,this.callConfiguration.answer=!1}}class Qe{events;strategy;constructor(e){this.events=new y.TypedEvents(ce),this.strategy=e??new Ge(this.events),this.subscribeCallStatusChange()}get requested(){return this.strategy.requested}get connection(){return this.strategy.connection}get establishedRTCSession(){return this.strategy.establishedRTCSession}get isCallActive(){return this.strategy.isCallActive}on(e,t){return this.events.on(e,t)}onRace(e,t){return this.events.onRace(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}setStrategy(e){this.strategy=e}startCall=async(...e)=>this.strategy.startCall(...e);endCall=async()=>this.strategy.endCall();answerToIncomingCall=async(...e)=>this.strategy.answerToIncomingCall(...e);getEstablishedRTCSession=()=>this.strategy.getEstablishedRTCSession();getCallConfiguration=()=>this.strategy.getCallConfiguration();getRemoteStreams=()=>this.strategy.getRemoteStreams();addTransceiver=async(...e)=>this.strategy.addTransceiver(...e);replaceMediaStream=async(...e)=>this.strategy.replaceMediaStream(...e);restartIce=async e=>this.strategy.restartIce(e);subscribeCallStatusChange(){let{isCallActive:e}=this;const{ACCEPTED:t,CONFIRMED:s,ENDED:r,FAILED:i}=N;this.onRace([t,s,r,i],()=>{e=this.maybeTriggerCallStatus(e)})}maybeTriggerCallStatus(e){const t=this.isCallActive;return t!==e&&this.events.trigger(N.CALL_STATUS_CHANGED,{isCallActive:t}),t}}const Ye=(n,e)=>(n.degradationPreference=e.degradationPreference,n),ze=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},he=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,Xe=he(),Je=(n,e)=>{if(Xe(n,e))return n},Ke=(n,e)=>{const t=n.maxBitrate,s=Je(e,t);return s!==void 0&&(n.maxBitrate=s),n},le=1,je=he(le),Ze=(n,e)=>{const t=n===void 0?void 0:Math.max(n,le);if(t!==void 0&&je(t,e))return t},et=(n,e)=>{const t=n.scaleResolutionDownBy,s=Ze(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},tt=(n,e)=>{const t=e.encodings?.length??0;return ze(n,t),n.encodings.forEach((s,r)=>{const i=(e?.encodings??[])[r],a=i?.maxBitrate,o=i?.scaleResolutionDownBy;Ke(s,a),et(s,o)}),n},nt=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},ge=async(n,e)=>{const t=n.getParameters(),s=JSON.parse(JSON.stringify(t));tt(t,e),Ye(t,e);const r=nt(s,t);return r&&await n.setParameters(t),{parameters:t,isChanged:r}},J=async(n,e,t)=>{const{isChanged:s,parameters:r}=await ge(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(r),{isChanged:s,parameters:r}},st=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),rt=async(n,e,t)=>{const s=st(n,e);if(s)return J(s,{maxBitrate:t})};var O=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(O||{});const ue=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],it=1,at=n=>Q.hasCanceledError(n);class ot{events;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=new y.Events(ue),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async startPresentation(e,t,{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:t,presentationOptions:{isNeedReinvite:s,contentHint:r,sendEncodings:i,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const r=this.callManager.getEstablishedRTCSession();return r&&t?s=e().then(async()=>r.stopPresentation(t)).catch(i=>{throw this.events.trigger(O.FAILED_PRESENTATION,i),i}):t&&this.events.trigger(O.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{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,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:i}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(O.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(O.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(O.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(O.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(O.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:r,options:i={callLimit:it}}){const a=async()=>this.sendPresentation(e,t,s,r),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=Q.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:r=!0,contentHint:i="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const h=B(s,{contentHint:i});if(h===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=h;const T=e().then(async()=>t.startPresentation(h,r,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(S=>{throw this.removeStreamPresentationCurrent(),this.events.trigger(O.FAILED_PRESENTATION,S),S});return this.promisePendingStartPresentation=T,T.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const r=e.getSenders();await rt(r,t,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}}class ct{data={};getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){return{...this.data}}set(e){this.data={...e}}update(e,t){this.data[e]=t}clear(){this.data={}}isRegister(){return this.data.register===!0}getSipServerUrl(){return this.data.sipServerUrl}getDisplayName(){return this.data.displayName}getUser(){return this.data.user}getPassword(){return this.data.password}isRegisterEnabled(){return this.data.register===!0}}var A=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.DISCONNECTING="disconnecting",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n.CONNECT_STARTED="connect-started",n.CONNECT_SUCCEEDED="connect-succeeded",n.CONNECT_FAILED="connect-failed",n.CONNECT_PARAMETERS_RESOLVE_FAILED="connect-parameters-resolve-failed",n))(A||{});const Te=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],dt=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-failed"],Se=[...Te,...dt],ht=3;class lt{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setSipServerUrl;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setSipServerUrl=e.setSipServerUrl,this.setSocket=e.setSocket}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const r=this.getUa();if(!r){s(new Error("this.ua is not initialized"));return}let i=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a.displayName&&(i=r.set("display_name",de(e)),this.updateConnectionConfiguration("displayName",e));const o=i;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{this.events.trigger(A.DISCONNECTING,{});const e=new Promise(s=>{this.events.once(A.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(A.DISCONNECTED,{socket:{},error:!1}),e.finally(()=>{this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=ht}={})=>{const s=async()=>this.connectInner(e),r=i=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),h=i!=null&&!Ue(i);return c||h};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=Q.repeatedCallsAsync({targetFunction:s,isComplete:r,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(i=>{if(i instanceof this.JsSIP.UA)return i;throw i})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),r=this.getUa()?.configuration;return r?r.password===t.password&&r.register===t.register&&r.uri.toString()===t.uri&&r.display_name===t.display_name&&r.user_agent===t.user_agent&&r.sockets===t.sockets&&r.session_timers===t.session_timers&&r.register_expires===t.register_expires&&r.connection_recovery_min_interval===t.connection_recovery_min_interval&&r.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start());initUa=async({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:r,remoteAddress:i,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:T,displayName:S="",register:g=!1,extraHeaders:E=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerUrl:s,displayName:S,register:g,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:I,helpers:R}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:r,displayName:S,register:g,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:h,userAgent:T,remoteAddress:i,extraHeaders:E},this.events);return this.setUa(I),this.setSipServerUrl(R.getSipServerUrl),this.setSocket(R.socket),I};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let r;r=((c,h)=>{if(this.getConnectionConfiguration().register===!0)return this.registrationManager.subscribeToStartEvents(c,h);const S=A.CONNECTED,g=[A.DISCONNECTED];return this.events.on(S,c),g.forEach(E=>{this.events.on(E,h)}),()=>{this.events.off(S,c),g.forEach(E=>{this.events.off(E,h)})}})(()=>{r?.(),e(s)},c=>{r?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}}var Ce=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(Ce||{});const gt=se.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"idle",context:{},states:{idle:{entry:{type:"logStateChange",params:{state:"idle"}},on:{START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"idle",to:"connecting",event:"START_CONNECT"}}}}},connecting:{entry:{type:"logStateChange",params:{state:"connecting"}},on:{START_INIT_UA:{target:"initializing",actions:{type:"logTransition",params:{from:"connecting",to:"initializing",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connecting",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connecting",to:"failed",event:"CONNECTION_FAILED"}}}}},initializing:{entry:{type:"logStateChange",params:{state:"initializing"}},on:{UA_CONNECTED:{target:"connected",actions:{type:"logTransition",params:{from:"initializing",to:"connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"initializing",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"initializing",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"initializing",to:"failed",event:"CONNECTION_FAILED"}}}}},connected:{entry:{type:"logStateChange",params:{state:"connected"}},on:{UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"connected",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connected",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connected",to:"failed",event:"CONNECTION_FAILED"}}}}},registered:{entry:{type:"logStateChange",params:{state:"registered"}},on:{UA_UNREGISTERED:{target:"connected",actions:{type:"logTransition",params:{from:"registered",to:"connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"registered",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"registered",to:"failed",event:"CONNECTION_FAILED"}}}}},disconnected:{entry:{type:"logStateChange",params:{state:"disconnected"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"disconnected",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"disconnected",to:"connecting",event:"START_CONNECT"}}}}},failed:{entry:{type:"logStateChange",params:{state:"failed"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"failed",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"failed",to:"connecting",event:"START_CONNECT"}}}}}}});class ut{actor;stateChangeListeners=new Set;events;unsubscribeFromEvents;actorSubscription;constructor(e){this.events=e,this.actor=se.createActor(gt),this.actorSubscription=this.actor.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(r=>{r(s)})}),this.actor.start(),this.subscribeToEvents()}get state(){return this.actor.getSnapshot().value}get isIdle(){return this.hasState("idle")}get isConnecting(){return this.hasState("connecting")}get isInitializing(){return this.hasState("initializing")}get isConnected(){return this.hasState("connected")}get isRegistered(){return this.hasState("registered")}get isDisconnected(){return this.hasState("disconnected")}get isFailed(){return this.hasState("failed")}get isPending(){return this.isConnecting||this.isInitializing}get isPendingConnect(){return this.isConnecting}get isPendingInitUa(){return this.isInitializing}get isActiveConnection(){return this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.actorSubscription?.unsubscribe(),this.actor.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return Object.values(Ce).filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){const t=this.actor.getSnapshot(),s={type:e};if(!t.can(s)){d(`Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`);return}this.actor.send(s)}toStartConnect=()=>{this.sendEvent("START_CONNECT")};toStartInitUa=()=>{this.sendEvent("START_INIT_UA")};toConnected=()=>{this.sendEvent("UA_CONNECTED")};toRegistered=()=>{this.sendEvent("UA_REGISTERED")};toUnregistered=()=>{this.sendEvent("UA_UNREGISTERED")};toDisconnected=()=>{this.sendEvent("UA_DISCONNECTED")};toFailed=()=>{this.sendEvent("CONNECTION_FAILED")};toIdle=()=>{this.sendEvent("RESET")};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toFailed)}}}class Tt{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(A.REGISTERED,t),e.on(A.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(A.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){d("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=A.REGISTERED,r=[A.REGISTRATION_FAILED,A.DISCONNECTED];return this.events.on(s,e),r.forEach(i=>{this.events.on(i,t)}),()=>{this.events.off(s,e),r.forEach(i=>{this.events.off(i,t)})}}}class St{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const r=this.getUaProtected();return new Promise((i,a)=>{try{r.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{i()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const r=this.getUaProtected().configuration.uri;return this.sendOptions(r,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:s,sipWebSocketServerURL:r,remoteAddress:i,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:h}=this.uaFactory.createConfiguration({sipWebSocketServerURL:r,displayName:t,userAgent:e,sipServerUrl:s}),T=this.uaFactory.createUA({...h,remoteAddress:i,extraHeaders:a}),S=()=>{const E=new Error("Telephony is not available");c(E)};T.once(A.DISCONNECTED,S);const g=()=>{T.removeAllListeners(),T.once(A.DISCONNECTED,()=>{o()}),T.stop()};T.once(A.CONNECTED,g),T.start()})}}const Ct=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class D{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:s,sipServerUrl:r,sipWebSocketServerURL:i}){if(!r)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(e&&(t===void 0||t===""))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,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${Ve()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?Ct(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipWebSocketServerURL:s,displayName:r="",sipServerUrl:i,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:T=6,userAgent:S}){D.validateParametersConnection({register:a,password:t,user:e,sipServerUrl:i,sipWebSocketServerURL:s});const g=D.resolveAuthorizationUser(a,e),E=$e(i),_=E(g),I=new this.JsSIP.WebSocketInterface(s);return{configuration:{password:t,register:a,uri:_,display_name:de(r),user_agent:S,sdpSemantics:"unified-plan",sockets:[I],session_timers:o,register_expires:c,connection_recovery_min_interval:h,connection_recovery_max_interval:T},helpers:{socket:I,getSipServerUrl:E}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const r=new this.JsSIP.UA(s),i=D.buildExtraHeaders(e,t);return i.length>0&&r.registrator().setExtraHeaders(i),r}createUAWithConfiguration(e,t){const{configuration:s,helpers:r}=this.createConfiguration(e),i=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=Te.find(h=>h===o);c&&i.on(c,a)}),{ua:i,helpers:r}}}const Ee="Not ready for connection",Ae=n=>n instanceof Error&&n.message===Ee,Et=()=>new Error(Ee),Ne=async n=>typeof n=="function"?n():n;class At{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=new y.TypedEvents(Se),this.uaFactory=new D(e),this.registrationManager=new Tt({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new ut(this.events),this.configurationManager=new ct({getUa:this.getUa}),this.sipOperations=new St({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new lt({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setSipServerUrl:t=>{this.getSipServerUrl=t},setSocket:t=>{this.socket=t}})}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 isFailed(){return this.stateMachine.isFailed}get connectionState(){return this.stateMachine.state}get isRegistered(){return D.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.disconnect().catch(s=>{d("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,t));set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>{if(this.isConfigured())return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getSipServerUrl=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw Et();return this.processConnect(e,t).catch(async r=>{const i=r;return this.disconnect().then(()=>{throw i}).catch(()=>{throw i})})};processConnect=async(e,t)=>(this.events.trigger(A.CONNECT_STARTED,{}),Ne(e).catch(s=>{throw this.events.trigger(A.CONNECT_PARAMETERS_RESOLVE_FAILED,s),s}).then(async s=>this.connectionFlow.connect(s,t)).then(s=>(this.events.trigger(A.CONNECT_SUCCEEDED,{ua:s}),s)).catch(s=>{const r=s??new Error("Failed to connect to server");throw this.events.trigger(A.CONNECT_FAILED,r),r}))}class Nt{connectionManager;stackPromises=Y.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()}}var M=(n=>(n.BEFORE_ATTEMPT="before-attempt",n.SUCCESS="success",n.FAILED_ALL_ATTEMPTS="failed-all-attempts",n.CANCELLED_ATTEMPTS="cancelled-attempts",n.CHANGED_ATTEMPT_STATUS="changed-attempt-status",n.STOP_ATTEMPTS_BY_ERROR="stop-attempts-by-error",n.LIMIT_REACHED_ATTEMPTS="limit-reached-attempts",n))(M||{});const Re=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts"],j=0,Rt=30;class It{events;countInner=j;initialCount=j;limitInner=Rt;isInProgress=!1;constructor({events:e}){this.events=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.emitStatusChange())}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.emitStatusChange())}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}emitStatusChange(){this.events.trigger(M.CHANGED_ATTEMPT_STATUS,{isInProgress:this.isInProgress})}}class pt{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableBeforeRequest=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start({onBeforeRequest:e,onSuccessRequest:t,onFailRequest:s}){this.stop(),this.cancelableBeforeRequest=new $.CancelableRequest(e),this.checkTelephonyByTimeout=b.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableBeforeRequest)throw new Error("cancelableBeforeRequest is not defined");const r=await this.cancelableBeforeRequest.request();return this.connectionManager.checkTelephony(r)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableBeforeRequest?.cancelRequest(),this.cancelableBeforeRequest=void 0}}const _t=15e3,mt=2;class Mt{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=b.requesterByTimeoutsWithFailCalls(mt,{whenPossibleRequest:async()=>{},requestInterval:_t,request:async()=>(d("ping"),this.connectionManager.ping().then(()=>{d("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(d)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}class vt{callManager;pingServerRequester;disposeCallStatusChange;constructor({connectionManager:e,callManager:t}){this.callManager=t,this.pingServerRequester=new Mt({connectionManager:e})}start({onFailRequest:e}){d("start"),this.disposeCallStatusChange=this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange({onFailRequest:e})}),this.handleCallStatusChange({onFailRequest:e})}stop(){d("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.disposeCallStatusChange?.(),this.disposeCallStatusChange=void 0}handleCallStatusChange({onFailRequest:e}){this.callManager.isCallActive?this.pingServerRequester.stop():this.pingServerRequester.start({onFailRequest:e})}}class Pt{connectionManager;callManager;isRegistrationFailed=!1;disposers=[];constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.disposers.push(this.callManager.on("call-status-changed",({isCallActive:t})=>{!t&&this.isRegistrationFailed&&e()}))}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const ft=3e3,Ot=15e3,yt=async()=>{},Dt=n=>!0;class bt{events;connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;cancelableRequestBeforeRetry;onBeforeRetry;canRetryOnError;constructor({connectionQueueManager:e,connectionManager:t,callManager:s},r){const i=r?.onBeforeRetry??yt,a=r?.canRetryOnError??Dt;this.connectionQueueManager=e,this.connectionManager=t,this.onBeforeRetry=i,this.canRetryOnError=a,this.events=new y.TypedEvents(Re),this.checkTelephonyRequester=new pt({connectionManager:t,interval:r?.checkTelephonyRequestInterval??Ot}),this.pingServerIfNotActiveCallRequester=new vt({connectionManager:t,callManager:s}),this.registrationFailedOutOfCallSubscriber=new Pt({connectionManager:t,callManager:s}),this.attemptsState=new It({events:this.events}),this.cancelableRequestBeforeRetry=new $.CancelableRequest(i),this.delayBetweenAttempts=new b.DelayRequester(r?.timeoutBetweenAttempts??ft)}start(e){d("auto connector start"),this.stop(),this.connect(e).catch(t=>{d("auto connector failed to connect:",t)})}stop(){d("auto connector stop"),this.stopAttempts(),this.stopConnectTriggers(),this.connectionQueueManager.disconnect().catch(e=>{d("auto connector disconnect: error",e)})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.delayBetweenAttempts.cancelRequest(),this.cancelableRequestBeforeRetry.cancelRequest(),this.attemptsState.reset()}stopConnectTriggers(){d("stopConnectTriggers"),this.pingServerIfNotActiveCallRequester.stop(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}runCheckTelephony(e){d("runCheckTelephony"),this.checkTelephonyRequester.start({onBeforeRequest:async()=>(await this.onBeforeRetry(),e.getParameters()),onSuccessRequest:()=>{d("runCheckTelephony: onSuccessRequest"),this.connectIfDisconnected(e)},onFailRequest:t=>{d("runCheckTelephony: onFailRequest",t.message)}})}async connect(e){if(d("connect: attempts.count",this.attemptsState.count),this.events.trigger(M.BEFORE_ATTEMPT,{}),this.stopConnectTriggers(),this.attemptsState.hasLimitReached()){d("connect: isLimitReached!"),this.handleLimitReached(e);return}return this.attemptsState.startAttempt(),this.attemptsState.increment(),this.processConnect(e)}async processConnect(e){try{await this.connectionQueueManager.connect(e.getParameters,e.options),d("processConnect success"),this.handleSucceededAttempt(e)}catch(t){if(Ae(t)){this.handleSucceededAttempt(e);return}if(!this.canRetryOnError(t)){d("processConnect: error does not allow retry",t),this.events.trigger(M.STOP_ATTEMPTS_BY_ERROR,t);return}if(Y.isPromiseIsNotActualError(t)){d("processConnect: not actual error",t),this.events.trigger(M.CANCELLED_ATTEMPTS,t);return}d("processConnect: error",t),this.reconnect(e)}}handleLimitReached(e){this.attemptsState.finishAttempt(),this.events.trigger(M.LIMIT_REACHED_ATTEMPTS,new Error("Limit reached")),this.runCheckTelephony(e)}handleSucceededAttempt(e){d("handleSucceededAttempt"),this.subscribeToConnectTriggers(e),this.events.trigger(M.SUCCESS)}subscribeToConnectTriggers(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{d("pingServer onFailRequest"),this.start(e)}}),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{d("registrationFailedOutOfCallListener callback"),this.start(e)})}connectIfDisconnected(e){const t=this.hasFailedOrDisconnectedConnection();d("connectIfDisconnected: isFailedOrDisconnected",t),t?this.start(e):(this.stopConnectTriggers(),this.events.trigger(M.SUCCESS))}reconnect(e){d("reconnect"),this.delayBetweenAttempts.request().then(async()=>(d("reconnect: delayBetweenAttempts success"),this.cancelableRequestBeforeRetry.request())).then(async()=>(d("reconnect: onBeforeRetry success"),this.connect(e))).catch(t=>{const s=t instanceof Error?t:new Error("Failed to reconnect");$.isCanceledError(t)||b.hasCanceledError(t)?this.events.trigger(M.CANCELLED_ATTEMPTS,s):this.events.trigger(M.FAILED_ALL_ATTEMPTS,s),d("reconnect: error",t)})}hasFailedOrDisconnectedConnection(){const{isFailed:e,isDisconnected:t,isIdle:s}=this.connectionManager;return e||t||s}}var L=(n=>(n.INCOMING_CALL="incomingCall",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(L||{});const Ie=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],wt=486,Ut=487;class Lt{events;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=new y.Events(Ie),this.start()}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession: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.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=Ut}={}){return new Promise((t,s)=>{try{const r=this.getIncomingRTCSession(),i=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(L.DECLINED_INCOMING_CALL,i),r.terminate({status_code:e}),t()}catch(r){s(r)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:wt})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e==="remote"&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger(L.TERMINATED_INCOMING_CALL,t):this.events.trigger(L.FAILED_INCOMING_CALL,t)}),this.events.trigger(L.INCOMING_CALL,t)}removeIncomingSession(){delete this.incomingRTCSession}}const U=1e3;var C=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(C||{});const pe=["collected"],Z=()=>"performance"in window?performance.now():Date.now(),F=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),Bt=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=F(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},ee=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=F(n);return{outboundRtp:e[C.OUTBOUND_RTP],codec:e[C.CODEC],mediaSource:e[C.MEDIA_SOURCE],remoteInboundRtp:e[C.REMOTE_INBOUND_RTP]}},te=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=F(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],synchronizationSources:e}},Ft=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=F(n);return{inboundRtp:t[C.INBOUND_RTP],codec:t[C.CODEC],remoteOutboundRtp:t[C.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},_e=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=F(n);return{candidatePair:e[C.CANDIDATE_PAIR],certificate:e[C.CERTIFICATE],localCandidate:e[C.LOCAL_CANDIDATE],remoteCandidate:e[C.REMOTE_CANDIDATE],transport:e[C.TRANSPORT]}},kt=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:ee(e),secondVideo:ee(t),audio:Bt(n),additional:_e(n??e??t)}),$t=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:te({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:te({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:Ft({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:_e(n??e??t)}),qt=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a})=>{const o=kt({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=$t({audioReceiverStats:s,videoReceiverFirstStats:r,videoReceiverSecondStats:i,synchronizationSources:a});return{outbound:o,inbound:c}},Vt=async n=>{const e="audio",t="video",s=n.getSenders(),r=s.find(g=>g.track?.kind===e),i=s.filter(g=>g.track?.kind===t),a=n.getReceivers(),o=a.find(g=>g.track.kind===e),c=a.filter(g=>g.track.kind===t),h={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},T={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},S={audio:h,video:T};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(g=>{const[E,_,I,R,w,q]=g;return{synchronizationSources:S,audioSenderStats:E,videoSenderFirstStats:_,videoSenderSecondStats:I,audioReceiverStats:R,videoReceiverFirstStats:w,videoReceiverSecondStats:q}})},Wt=n=>{d(String(n))};class me{events;setTimeoutRequest;requesterAllStatistics=new $.CancelableRequest(Vt);constructor(){this.events=new y.TypedEvents(pe),this.setTimeoutRequest=new b.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=U,onError:s=Wt}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=Z();this.requesterAllStatistics.request(e).then(r=>{this.events.trigger("collected",qt(r));const a=Z()-s;let o=U;a>48?o=U*4:a>32?o=U*3:a>16&&(o=U*2),this.start(e,{onError:t,interval:o})}).catch(r=>{t&&t(r)})}}class Ht{availableIncomingBitrate;statsPeerConnection;callManager;apiManager;previousAvailableIncomingBitrate;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new me,this.subscribe()}get events(){return this.statsPeerConnection.events}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableIncomingBitrate=this.availableIncomingBitrate,this.availableIncomingBitrate=e.inbound.additional.candidatePair?.availableIncomingBitrate,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableIncomingBitrate=void 0,this.previousAvailableIncomingBitrate=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{d("Failed to send stats",e)})}}const xt=(n,e)=>n.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),Gt=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return xt(s,r)},Qt=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const r=e.indexOf(t.mimeType),i=e.indexOf(s.mimeType),a=r===-1?Number.MAX_VALUE:r,o=i===-1?Number.MAX_VALUE:i;return a-o}),Yt=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),zt=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=Gt("video"),r=Yt(s,t),i=Qt(r,e);n.setCodecPreferences(i)}}catch(s){d("setCodecPreferences error",s)}};class Xt{transceivers={};callManager;apiManager;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.subscribe()}storeTransceiver(e,t){const{kind:s}=t;if(s==="audio")this.transceivers.mainAudio??=e;else{const{mid:r}=e;r==="2"?this.transceivers.presentationVideo??=e:this.transceivers.mainVideo??=e}}getTransceivers(){return{...this.transceivers}}getMainAudioTransceiver(){return this.transceivers.mainAudio}getMainVideoTransceiver(){return this.transceivers.mainVideo}getPresentationVideoTransceiver(){return this.transceivers.presentationVideo}hasTransceiver(e){return this.transceivers[e]!==void 0}clear(){this.transceivers.mainVideo=void 0,this.transceivers.mainAudio=void 0,this.transceivers.presentationVideo=void 0}getCount(){let e=0;return this.transceivers.mainAudio&&(e+=1),this.transceivers.mainVideo&&(e+=1),this.transceivers.presentationVideo&&(e+=1),e}isEmpty(){return this.getCount()===0}handleRestart=e=>{this.updateTransceivers(e).catch(t=>{d("Failed to update transceivers",t)}).finally(()=>{this.callManager.restartIce().catch(t=>{d("Failed to restart ICE",t)})})};updateTransceivers=async e=>{const{videoTrackCount:t}=e;t===2&&(this.getTransceivers().presentationVideo!==void 0||await this.callManager.addTransceiver("video",{direction:"recvonly"}).catch(i=>{d("Failed to add presentation video transceiver",i)}))};subscribe(){this.callManager.on("peerconnection:ontrack",this.handleTrack),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.apiManager.on("restart",this.handleRestart)}handleTrack=e=>{this.storeTransceiver(e.transceiver,e.track)};handleEnded=()=>{this.clear()}}const Jt=n=>[...n.keys()].map(e=>n.get(e)),Kt=(n,e)=>Jt(n).find(t=>t?.type===e),Me=async n=>n.getStats().then(e=>Kt(e,"codec")?.mimeType);class jt{async getCodecFromSender(e){return await Me(e)??""}}class Zt{stackPromises=Y.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{d("TaskQueue: error",e)})}}class en{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Zt}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>J(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const ve=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),tn=1e6,v=n=>n*tn,Pe=v(.06),fe=v(4),nn=n=>n<=64?Pe:n<=128?v(.12):n<=256?v(.25):n<=384?v(.32):n<=426?v(.38):n<=640?v(.5):n<=848?v(.7):n<=1280?v(1):n<=1920?v(2):fe,sn="av1",rn=n=>ve(n,sn),an=.6,K=(n,e)=>rn(e)?n*an:n,on=n=>K(Pe,n),cn=n=>K(fe,n),ne=(n,e)=>{const t=nn(n);return K(t,e)},V=1,dn=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,r=t.height,i=s===void 0?V:s/e.width,a=r===void 0?V:r/e.height;return Math.max(i,a,V)};class hn{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},r){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=r.ignoreForCodec}async balance(e,t){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(ve(i,this.ignoreForCodec))return{...this.resultNoChanged,sender:r};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:r,codec:i,videoTrack:r.track}).then(c=>({...c,sender:r}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:r}=e;switch(s){case P.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case P.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case P.MAX_MAIN_CAM_RESOLUTION:return r!==void 0?this.setResolutionSender(r,t):this.setBitrateByTrackResolution(t);case P.ADMIN_STOP_MAIN_CAM:case P.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,r={scaleResolutionDownBy:200,maxBitrate:on(s)};return this.parametersSetter.setEncodingsToSender(t,r)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:r}=e,a=s.getSettings().width,o=a===void 0?cn(r):ne(a,r);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,r]=e.split("x"),{sender:i,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(r)},h=dn({videoTrack:a,targetSize:c}),T=ne(c.width,o),S={scaleResolutionDownBy:h,maxBitrate:T};return this.parametersSetter.setEncodingsToSender(i,S)}}const ln=n=>n.find(e=>e.track?.kind==="video");class gn{findVideoSender(e){return ln(e)}}class un{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new b.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async r=>{await s(r),this.attachTrack(t,r??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:r}=t.getSettings();this.lastWidth=s,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){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,t()):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 Tn{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)}}class Sn{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:r,pollIntervalMs:i}={}){this.getConnection=t,this.eventHandler=new Tn(e),this.parametersSetterWithQueue=new en(r),this.senderBalancer=new hn({senderFinder:new gn,codecProvider:new jt,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new un({pollIntervalMs:i})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{d("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{d("handleMainCamControl: error",t)})}}const Oe=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"];class Cn{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=new y.TypedEvents(Oe),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new Sn(t,()=>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()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{d("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const En=1e6,An=Re.map(n=>`auto-connect:${n}`),Nn=Se.map(n=>`connection:${n}`),Rn=ce.map(n=>`call:${n}`),In=ie.map(n=>`api:${n}`),pn=Ie.map(n=>`incoming-call:${n}`),_n=ue.map(n=>`presentation:${n}`),mn=pe.map(n=>`stats:${n}`),Mn=Oe.map(n=>`video-balancer:${n}`),vn=[...An,...Nn,...Rn,...In,...pn,..._n,...mn,...Mn];class Pn{events;connectionManager;connectionQueueManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;transceiverManager;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:r,autoConnectorOptions:i}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=new y.Events(vn),this.connectionManager=new At({JsSIP:e}),this.connectionQueueManager=new Nt({connectionManager:this.connectionManager}),this.callManager=new Qe,this.apiManager=new Be({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new Lt(this.connectionManager),this.presentationManager=new ot({callManager:this.callManager,maxBitrate:En}),this.statsManager=new Ht({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new bt({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},i),this.transceiverManager=new Xt({callManager:this.callManager,apiManager:this.apiManager}),this.videoSendingBalancerManager=new Cn(this.callManager,this.apiManager,r),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 establishedRTCSession(){return this.callManager.establishedRTCSession}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}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();set=async(...e)=>this.connectionManager.set(...e);sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getSipServerUrl=e=>this.connectionManager.getSipServerUrl(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getSipServerUrl,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>this.callManager.getCallConfiguration();getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:r,onAddedTransceiver:i,...a}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...a,onAddedTransceiver:this.resolveHandleAddTransceiver(i)},r===void 0?void 0:{callLimit:r})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{await(t===!0?this.apiManager.sendMustStopPresentationP2P():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{isP2P:s,onAddedTransceiver:r,...i}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...i,onAddedTransceiver:this.resolveHandleAddTransceiver(r)})}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 sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}setCodecPreferences(e){zt(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)}bridgeEvents=(e,t)=>{t.events.eachTriggers((s,r)=>{t.on(r,i=>{this.events.trigger(`${e}:${r}`,i)})})};resolveHandleAddTransceiver=e=>async(t,s,r)=>{this.setCodecPreferences(t),await e?.(t,s,r)}}exports.ECallCause=X;exports.EStatsTypes=C;exports.EUseLicense=re;exports.Originator=ae;exports.SipConnector=Pn;exports.StatsPeerConnection=me;exports.disableDebug=De;exports.enableDebug=ye;exports.getCodecFromSender=Me;exports.hasCanceledStartPresentationError=at;exports.hasNotReadyForConnectionError=Ae;exports.logger=d;exports.prepareMediaStream=B;exports.resolveParameters=Ne;exports.setEncodingsToSender=J;exports.setParametersToSender=ge;
|
|
@@ -2,17 +2,21 @@ import { TypedEvents } from 'events-constructor';
|
|
|
2
2
|
import { TAttemptStatus } from './types';
|
|
3
3
|
export declare enum EEvent {
|
|
4
4
|
BEFORE_ATTEMPT = "before-attempt",
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
CHANGED_ATTEMPT_STATUS = "changed-attempt-status"
|
|
5
|
+
SUCCESS = "success",
|
|
6
|
+
FAILED_ALL_ATTEMPTS = "failed-all-attempts",
|
|
7
|
+
CANCELLED_ATTEMPTS = "cancelled-attempts",
|
|
8
|
+
CHANGED_ATTEMPT_STATUS = "changed-attempt-status",
|
|
9
|
+
STOP_ATTEMPTS_BY_ERROR = "stop-attempts-by-error",
|
|
10
|
+
LIMIT_REACHED_ATTEMPTS = "limit-reached-attempts"
|
|
9
11
|
}
|
|
10
|
-
export declare const EVENT_NAMES: readonly ["before-attempt", "
|
|
12
|
+
export declare const EVENT_NAMES: readonly ["before-attempt", "success", "failed-all-attempts", "cancelled-attempts", "changed-attempt-status", "stop-attempts-by-error", "limit-reached-attempts"];
|
|
11
13
|
export type TEventMap = {
|
|
12
14
|
'before-attempt': Record<string, never>;
|
|
13
|
-
|
|
14
|
-
'failed-
|
|
15
|
-
'cancelled-
|
|
15
|
+
success: never;
|
|
16
|
+
'failed-all-attempts': Error;
|
|
17
|
+
'cancelled-attempts': unknown;
|
|
16
18
|
'changed-attempt-status': TAttemptStatus;
|
|
19
|
+
'stop-attempts-by-error': unknown;
|
|
20
|
+
'limit-reached-attempts': Error;
|
|
17
21
|
};
|
|
18
22
|
export type TEvents = TypedEvents<TEventMap>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { Events } from 'events-constructor';
|
|
2
|
-
export declare const EVENT_NAMES: readonly ("auto-connect:before-attempt" | "auto-connect:
|
|
2
|
+
export declare const EVENT_NAMES: readonly ("auto-connect:before-attempt" | "auto-connect:success" | "auto-connect:failed-all-attempts" | "auto-connect:cancelled-attempts" | "auto-connect:changed-attempt-status" | "auto-connect:stop-attempts-by-error" | "auto-connect:limit-reached-attempts" | "connection:connecting" | "connection:connected" | "connection:disconnected" | "connection:disconnecting" | "connection:newRTCSession" | "connection:registered" | "connection:unregistered" | "connection:registrationFailed" | "connection:newMessage" | "connection:sipEvent" | "connection:connect-started" | "connection:connect-succeeded" | "connection:connect-failed" | "connection:connect-parameters-resolve-failed" | "call:newDTMF" | "call:peerconnection" | "call:connecting" | "call:sending" | "call:progress" | "call:accepted" | "call:confirmed" | "call:ended" | "call:failed" | "call:newInfo" | "call:reinvite" | "call:update" | "call:refer" | "call:replaces" | "call:sdp" | "call:icecandidate" | "call:getusermediafailed" | "call:peerconnection:createofferfailed" | "call:peerconnection:createanswerfailed" | "call:peerconnection:setlocaldescriptionfailed" | "call:peerconnection:setremotedescriptionfailed" | "call:presentation:start" | "call:presentation:started" | "call:presentation:end" | "call:presentation:ended" | "call:presentation:failed" | "call:peerconnection:confirmed" | "call:peerconnection:ontrack" | "call:ended:fromserver" | "call:call-status-changed" | "api:channels:notify" | "api:participant:added-to-list-moderators" | "api:participant:removed-from-list-moderators" | "api:participant:move-request-to-stream" | "api:participant:move-request-to-spectators" | "api:participant:move-request-to-participants" | "api:participation:accepting-word-request" | "api:participation:cancelling-word-request" | "api:webcast:started" | "api:webcast:stopped" | "api:account:changed" | "api:account:deleted" | "api:conference:participant-token-issued" | "api:channels" | "api:enterRoom" | "api:shareState" | "api:main-cam-control" | "api:useLicense" | "api:admin-start-main-cam" | "api:admin-stop-main-cam" | "api:admin-start-mic" | "api:admin-stop-mic" | "api:admin-force-sync-media-state" | "api:availableSecondRemoteStream" | "api:notAvailableSecondRemoteStream" | "api:mustStopPresentation" | "api:newDTMF" | "api:restart" | "incoming-call:incomingCall" | "incoming-call:declinedIncomingCall" | "incoming-call:terminatedIncomingCall" | "incoming-call:failedIncomingCall" | "presentation:presentation:start" | "presentation:presentation:started" | "presentation:presentation:end" | "presentation:presentation:ended" | "presentation:presentation:failed" | "stats:collected" | "video-balancer:balancing-scheduled" | "video-balancer:balancing-started" | "video-balancer:balancing-stopped" | "video-balancer:parameters-updated")[];
|
|
3
3
|
export type TEvent = (typeof EVENT_NAMES)[number];
|
|
4
4
|
export type TEvents = Events<typeof EVENT_NAMES>;
|
package/dist/doMock.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("node:events"),U=require("@krivega/jssip/lib/NameAddrHeader"),H=require("@krivega/jssip/lib/URI"),q=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),D=require("./@SipConnector-4vrb2RbW.cjs");class w extends q.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const G="incomingCall",x="declinedIncomingCall",z="failedIncomingCall",j="terminatedIncomingCall",y="connecting",Y="connected",B="disconnected",K="newRTCSession",J="registered",$="unregistered",Q="registrationFailed",X="newMessage",Z="sipEvent",ee="availableSecondRemoteStream",te="notAvailableSecondRemoteStream",re="mustStopPresentation",ne="shareState",oe="enterRoom",ie="useLicense",se="peerconnection:confirmed",ae="peerconnection:ontrack",ce="channels",de="channels:notify",he="ended:fromserver",Ee="main-cam-control",ue="admin-stop-main-cam",me="admin-start-main-cam",le="admin-stop-mic",pe="admin-start-mic",ge="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",Ie="participant:move-request-to-stream",Se="participant:move-request-to-spectators",we="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ce="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ae="account:changed",Me="account:deleted",Oe="conference:participant-token-issued",Pe="ended",ve="sending",De="reinvite",ye="replaces",Le="refer",Fe="progress",We="accepted",be="confirmed",ke="peerconnection",Ve="failed",Ue="muted",He="unmuted",qe="newDTMF",Ge="newInfo",xe="hold",ze="unhold",je="update",Ye="sdp",Be="icecandidate",Ke="getusermediafailed",Je="peerconnection:createofferfailed",$e="peerconnection:createanswerfailed",Qe="peerconnection:setlocaldescriptionfailed",Xe="peerconnection:setremotedescriptionfailed",Ze="presentation:start",et="presentation:started",tt="presentation:end",rt="presentation:ended",nt="presentation:failed",ot=[G,x,j,z,Ne,Ce,Ie,de,Oe,Ae,Me,Re,fe,_e,Te],L=[y,Y,B,K,J,$,Q,X,Z],it=[ee,te,re,ne,oe,ie,se,ae,ce,he,Ee,me,ue,le,pe,ge,Se,we],_=[Pe,y,ve,De,ye,Le,Fe,We,be,ke,Ve,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt,rt,nt];[...L,...ot];[..._,...it];class st{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),this.initEvents(t),this.remote_identity=r}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,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){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,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("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,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return _.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}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 A{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:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class M{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}const at=["track"];class ct{senders=[];receivers=[];canTrickleIceCandidates;connectionState;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;events;constructor(e,t){this.events=new S.Events(at),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,r){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.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const r=new A({track:e}),n=new M(r);return n.mid=e.kind==="audio"?"0":"1",this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r};addTrackWithMid=(e,t)=>{const r=new A({track:e}),n=new M(r);return t===void 0?n.mid=e.kind==="audio"?"0":"1":n.mid=t,this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r}}function dt(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const O=400,F="777",ht=o=>o.getVideoTracks().length>0;class s extends st{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;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)},O)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);addTransceiver=jest.fn((e,t)=>({}));restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:n=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=n}static get C(){return a.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(ht(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new ct(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=dt(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:D.Originator.REMOTE,request:{getHeader:n=>n==="content-type"?"application/vinteo.webrtc.roomname":n==="x-webrtc-enter-room"?r:n==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},O),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind==="video"&&(t.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:t}){this.trigger("muted",{audio:e,video:t})}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)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",W="NAME_INCORRECT",E=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},P={status_code:200,reason_phrase:"OK"},v={status_code:401,reason_phrase:"Unauthorized"};class i{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:n}=t;return this.session=new s({eventHandlers:n,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},E):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new S.Events(L);const[t,r]=e.uri.split(":"),[n,c]=r.split("@"),p={...e,uri:new a.URI(t,n,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(W)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:P})},E)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:P})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ut{url;constructor(e){this.url=e}}class mt extends V.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",lt=(o,e)=>{const t=new w(e),r={originator:I,request:t,info:new mt("","")};o.newInfo(r)},pt=(o,e)=>{const r={event:"sipEvent",request:new w(e)};o.newSipEvent(r)},gt=(o,{incomingNumber:e="1234",displayName:t,host:r})=>{const n=new s({originator:I,eventHandlers:{}}),c=new H("sip",e,r);n.remote_identity=new U(c,t);const p=new w([]);o.trigger("newRTCSession",{originator:I,session:n,request:p})},_t=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},N={triggerNewInfo:lt,triggerNewSipEvent:pt,triggerIncomingSession:gt,triggerFailIncomingSession:_t,WebSocketInterface:ut,UA:i,C:{INVITE:"INVITE"}},u="user",h="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",Tt=new N.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},It={...R},b={...R,user:u,password:d,register:!0},St={...b,displayName:h},wt={...R,displayName:h,register:!1},l={session_timers:!1,sockets:[Tt],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"",register:!0},Ct={...l,password:d,uri:new a.URI("sip",u,m),display_name:h,register:!0},Rt={...l,display_name:h,register:!1},ft={...l,display_name:"",register:!1},k="10.10.10.10",At=[`X-Vinteo-Remote: ${k}`],Mt=()=>new D.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=N;exports.NAME_INCORRECT=W;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=St;exports.dataForConnectionWithoutAuthorization=wt;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=It;exports.displayName=h;exports.doMockSipConnector=Mt;exports.extraHeadersRemoteAddress=At;exports.remoteAddress=k;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=Ct;exports.uaConfigurationWithoutAuthorization=Rt;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ft;exports.user=u;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("node:events"),U=require("@krivega/jssip/lib/NameAddrHeader"),H=require("@krivega/jssip/lib/URI"),q=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),D=require("./@SipConnector-Cx-er9n6.cjs");class w extends q.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const G="incomingCall",x="declinedIncomingCall",z="failedIncomingCall",j="terminatedIncomingCall",y="connecting",Y="connected",B="disconnected",K="newRTCSession",J="registered",$="unregistered",Q="registrationFailed",X="newMessage",Z="sipEvent",ee="availableSecondRemoteStream",te="notAvailableSecondRemoteStream",re="mustStopPresentation",ne="shareState",oe="enterRoom",ie="useLicense",se="peerconnection:confirmed",ae="peerconnection:ontrack",ce="channels",de="channels:notify",he="ended:fromserver",Ee="main-cam-control",ue="admin-stop-main-cam",me="admin-start-main-cam",le="admin-stop-mic",pe="admin-start-mic",ge="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",Ie="participant:move-request-to-stream",Se="participant:move-request-to-spectators",we="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ce="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ae="account:changed",Me="account:deleted",Oe="conference:participant-token-issued",Pe="ended",ve="sending",De="reinvite",ye="replaces",Le="refer",Fe="progress",We="accepted",be="confirmed",ke="peerconnection",Ve="failed",Ue="muted",He="unmuted",qe="newDTMF",Ge="newInfo",xe="hold",ze="unhold",je="update",Ye="sdp",Be="icecandidate",Ke="getusermediafailed",Je="peerconnection:createofferfailed",$e="peerconnection:createanswerfailed",Qe="peerconnection:setlocaldescriptionfailed",Xe="peerconnection:setremotedescriptionfailed",Ze="presentation:start",et="presentation:started",tt="presentation:end",rt="presentation:ended",nt="presentation:failed",ot=[G,x,j,z,Ne,Ce,Ie,de,Oe,Ae,Me,Re,fe,_e,Te],L=[y,Y,B,K,J,$,Q,X,Z],it=[ee,te,re,ne,oe,ie,se,ae,ce,he,Ee,me,ue,le,pe,ge,Se,we],_=[Pe,y,ve,De,ye,Le,Fe,We,be,ke,Ve,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt,rt,nt];[...L,...ot];[..._,...it];class st{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),this.initEvents(t),this.remote_identity=r}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,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){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,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("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,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return _.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}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 A{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:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class M{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}const at=["track"];class ct{senders=[];receivers=[];canTrickleIceCandidates;connectionState;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;events;constructor(e,t){this.events=new S.Events(at),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,r){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.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const r=new A({track:e}),n=new M(r);return n.mid=e.kind==="audio"?"0":"1",this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r};addTrackWithMid=(e,t)=>{const r=new A({track:e}),n=new M(r);return t===void 0?n.mid=e.kind==="audio"?"0":"1":n.mid=t,this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r}}function dt(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const O=400,F="777",ht=o=>o.getVideoTracks().length>0;class s extends st{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;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)},O)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);addTransceiver=jest.fn((e,t)=>({}));restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:n=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=n}static get C(){return a.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(ht(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new ct(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=dt(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:D.Originator.REMOTE,request:{getHeader:n=>n==="content-type"?"application/vinteo.webrtc.roomname":n==="x-webrtc-enter-room"?r:n==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},O),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind==="video"&&(t.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:t}){this.trigger("muted",{audio:e,video:t})}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)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",W="NAME_INCORRECT",E=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},P={status_code:200,reason_phrase:"OK"},v={status_code:401,reason_phrase:"Unauthorized"};class i{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:n}=t;return this.session=new s({eventHandlers:n,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},E):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new S.Events(L);const[t,r]=e.uri.split(":"),[n,c]=r.split("@"),p={...e,uri:new a.URI(t,n,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(W)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:P})},E)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:P})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ut{url;constructor(e){this.url=e}}class mt extends V.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",lt=(o,e)=>{const t=new w(e),r={originator:I,request:t,info:new mt("","")};o.newInfo(r)},pt=(o,e)=>{const r={event:"sipEvent",request:new w(e)};o.newSipEvent(r)},gt=(o,{incomingNumber:e="1234",displayName:t,host:r})=>{const n=new s({originator:I,eventHandlers:{}}),c=new H("sip",e,r);n.remote_identity=new U(c,t);const p=new w([]);o.trigger("newRTCSession",{originator:I,session:n,request:p})},_t=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},N={triggerNewInfo:lt,triggerNewSipEvent:pt,triggerIncomingSession:gt,triggerFailIncomingSession:_t,WebSocketInterface:ut,UA:i,C:{INVITE:"INVITE"}},u="user",h="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",Tt=new N.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},It={...R},b={...R,user:u,password:d,register:!0},St={...b,displayName:h},wt={...R,displayName:h,register:!1},l={session_timers:!1,sockets:[Tt],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"",register:!0},Ct={...l,password:d,uri:new a.URI("sip",u,m),display_name:h,register:!0},Rt={...l,display_name:h,register:!1},ft={...l,display_name:"",register:!1},k="10.10.10.10",At=[`X-Vinteo-Remote: ${k}`],Mt=()=>new D.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=N;exports.NAME_INCORRECT=W;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=St;exports.dataForConnectionWithoutAuthorization=wt;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=It;exports.displayName=h;exports.doMockSipConnector=Mt;exports.extraHeadersRemoteAddress=At;exports.remoteAddress=k;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=Ct;exports.uaConfigurationWithoutAuthorization=Rt;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ft;exports.user=u;
|
package/dist/doMock.js
CHANGED
|
@@ -5,7 +5,7 @@ import { IncomingRequest as k } from "@krivega/jssip/lib/SIPMessage";
|
|
|
5
5
|
import { NameAddrHeader as V, URI as E, SessionStatus as W, C as N } from "@krivega/jssip";
|
|
6
6
|
import { createAudioMediaStreamTrackMock as U, createVideoMediaStreamTrackMock as G } from "webrtc-mock";
|
|
7
7
|
import { Events as T } from "events-constructor";
|
|
8
|
-
import { O as H, S as x } from "./@SipConnector-
|
|
8
|
+
import { O as H, S as x } from "./@SipConnector-Cr5Qu1ds.js";
|
|
9
9
|
class _ extends k {
|
|
10
10
|
headers;
|
|
11
11
|
constructor(e) {
|