sip-connector 7.0.6 → 7.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";var Ot=Object.defineProperty;var ft=(r,e,t)=>e in r?Ot(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var i=(r,e,t)=>ft(r,typeof e!="symbol"?e+"":e,t);const N=require("@krivega/cancelable-promise"),ve=require("events-constructor"),pt=require("repeated-calls"),V=require("debug"),Dt="Connection Error",qe="Request Timeout",Pt="SIP Failure Code",Mt="Internal Error",vt="Busy",Y="Rejected",bt="Redirected",yt="Unavailable",We="Not Found",wt="Address Incomplete",Ut="Incompatible SDP",Lt="Missing SDP",Ht="Authentication Error",ke="Terminated",qt="WebRTC Error",Fe="Canceled",Wt="No Answer",kt="Expires",Ft="No ACK",Bt="Dialog Error",Vt="User Denied Media Access",Be="Bad Media Description",Yt="RTP Timeout",xt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:wt,AUTHENTICATION_ERROR:Ht,BAD_MEDIA_DESCRIPTION:Be,BUSY:vt,BYE:ke,CANCELED:Fe,CONNECTION_ERROR:Dt,DIALOG_ERROR:Bt,EXPIRES:kt,INCOMPATIBLE_SDP:Ut,INTERNAL_ERROR:Mt,MISSING_SDP:Lt,NOT_FOUND:We,NO_ACK:Ft,NO_ANSWER:Wt,REDIRECTED:bt,REJECTED:Y,REQUEST_TIMEOUT:qe,RTP_TIMEOUT:Yt,SIP_FAILURE_CODE:Pt,UNAVAILABLE:yt,USER_DENIED_MEDIA_ACCESS:Vt,WEBRTC_ERROR:qt},Symbol.toStringTag,{value:"Module"})),x="incomingCall",G="declinedIncomingCall",$="failedIncomingCall",X="terminatedIncomingCall",W="connecting",O="connected",u="disconnected",M="newRTCSession",f="registered",J="unregistered",p="registrationFailed",Ve="newMessage",z="sipEvent",Q="availableSecondRemoteStream",K="notAvailableSecondRemoteStream",j="mustStopPresentation",v="shareState",Z="enterRoom",ee="useLicense",te="peerconnection:confirmed",ne="peerconnection:ontrack",b="channels",se="channels:notify",ie="ended:fromserver",re="main-cam-control",oe="admin-stop-main-cam",ae="admin-start-main-cam",ce="admin-stop-mic",Ee="admin-start-mic",y="admin-force-sync-media-state",_e="participant:added-to-list-moderators",he="participant:removed-from-list-moderators",le="participant:move-request-to-stream",de="participant:move-request-to-spectators",Te="participation:accepting-word-request",Se="participation:cancelling-word-request",ue="webcast:started",Ne="webcast:stopped",Ce="account:changed",ge="account:deleted",Ae="conference:participant-token-issued",D="ended",Ye="sending",xe="reinvite",Ge="replaces",$e="refer",Xe="progress",Je="accepted",w="confirmed",U="peerconnection",g="failed",ze="muted",Qe="unmuted",Re="newDTMF",Ie="newInfo",Ke="hold",je="unhold",Ze="update",et="sdp",tt="icecandidate",nt="getusermediafailed",st="peerconnection:createofferfailed",it="peerconnection:createanswerfailed",rt="peerconnection:setlocaldescriptionfailed",ot="peerconnection:setremotedescriptionfailed",at="presentation:start",ct="presentation:started",Et="presentation:end",me="presentation:ended",L="presentation:failed",_t="SPECTATOR",Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Je,ACCOUNT_CHANGED:Ce,ACCOUNT_DELETED:ge,ADMIN_FORCE_SYNC_MEDIA_STATE:y,ADMIN_START_MAIN_CAM:ae,ADMIN_START_MIC:Ee,ADMIN_STOP_MAIN_CAM:oe,ADMIN_STOP_MIC:ce,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Q,CHANNELS:b,CHANNELS_NOTIFY:se,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ae,CONFIRMED:w,CONNECTED:O,CONNECTING:W,DECLINED_INCOMING_CALL:G,DISCONNECTED:u,ENDED:D,ENDED_FROM_SERVER:ie,ENTER_ROOM:Z,FAILED:g,FAILED_INCOMING_CALL:$,GET_USER_MEDIA_FAILED:nt,HOLD:Ke,ICE_CANDIDATE:tt,INCOMING_CALL:x,MAIN_CAM_CONTROL:re,MUST_STOP_PRESENTATION_EVENT:j,MUTED:ze,NEW_DTMF:Re,NEW_INFO:Ie,NEW_MESSAGE:Ve,NEW_RTC_SESSION:M,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:K,PARTICIPANT_ADDED_TO_LIST_MODERATORS:_e,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:de,PARTICIPANT_MOVE_REQUEST_TO_STREAM:le,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:he,PARTICIPATION_ACCEPTING_WORD_REQUEST:Te,PARTICIPATION_CANCELLING_WORD_REQUEST:Se,PEER_CONNECTION:U,PEER_CONNECTION_CONFIRMED:te,PEER_CONNECTION_CREATE_ANSWER_FAILED:it,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:ne,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:rt,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:ot,PRESENTATION_END:Et,PRESENTATION_ENDED:me,PRESENTATION_FAILED:L,PRESENTATION_START:at,PRESENTATION_STARTED:ct,PROGRESS:Xe,REFER:$e,REGISTERED:f,REGISTRATION_FAILED:p,REINVITE:xe,REPLACES:Ge,SDP:et,SENDING:Ye,SHARE_STATE:v,SIP_EVENT:z,SPECTATOR:_t,TERMINATED_INCOMING_CALL:X,UNHOLD:je,UNMUTED:Qe,UNREGISTERED:J,UPDATE:Ze,USE_LICENSE:ee,WEBCAST_STARTED:ue,WEBCAST_STOPPED:Ne},Symbol.toStringTag,{value:"Module"})),ht=[x,G,X,$,Te,Se,le,se,Ae,Ce,ge,ue,Ne,_e,he],Oe=[W,O,u,M,f,J,p,Ve,z],lt=[Q,K,j,v,Z,ee,te,ne,b,ie,re,ae,oe,ce,Ee,y,de],fe=[D,W,Ye,xe,Ge,$e,Xe,Je,w,U,g,ze,Qe,Re,Ie,Ke,je,Ze,et,tt,nt,st,it,rt,ot,at,ct,Et,me,L],pe=[...Oe,...ht],De=[...fe,...lt],$t=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:De,SESSION_JSSIP_EVENT_NAMES:fe,SESSION_SYNTHETICS_EVENT_NAMES:lt,UA_EVENT_NAMES:pe,UA_JSSIP_EVENT_NAMES:Oe,UA_SYNTHETICS_EVENT_NAMES:ht},Symbol.toStringTag,{value:"Module"})),Xt=r=>{const e=[];return r&&e.push(`X-Vinteo-Remote: ${r}`),e},Jt="content-type",zt="x-webrtc-enter-room",P="application/vinteo.webrtc.sharedesktop",Qt="application/vinteo.webrtc.roomname",Kt="application/vinteo.webrtc.channels",jt="application/vinteo.webrtc.mediastate",Zt="application/vinteo.webrtc.refusal",be="application/vinteo.webrtc.maincam",en="application/vinteo.webrtc.mic",tn="application/vinteo.webrtc.uselic",nn="X-WEBRTC-USE-LICENSE",sn="X-WEBRTC-PARTICIPANT-NAME",ye="X-WEBRTC-INPUT-CHANNELS",we="X-WEBRTC-OUTPUT-CHANNELS",rn="X-WEBRTC-MAINCAM",on="X-WEBRTC-MIC",Ue="X-WEBRTC-SYNC",an="X-WEBRTC-MAINCAM-RESOLUTION",cn="X-WEBRTC-MEDIA-STATE",En="X-Vinteo-Media-Type",_n="X-Vinteo-MainCam-State",hn="X-Vinteo-Mic-State",ln="application/vinteo.webrtc.partstate",dn="X-WEBRTC-PARTSTATE",Tn="application/vinteo.webrtc.notify",Sn="X-VINTEO-NOTIFY",R="x-webrtc-share-state",un=`${R}: LETMESTARTPRESENTATION`,Nn=`${R}: STOPPRESENTATION`,dt="YOUCANRECEIVECONTENT",Tt="CONTENTEND",St="YOUMUSTSTOPSENDCONTENT",Cn=`${R}: ${St}`,gn=`${R}: ${dt}`,An=`${R}: ${Tt}`,Rn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",In=`${Rn}: LETMESTARTMAINCAM`,Pe="sip-connector",F=V(Pe),mn=()=>{V.enable(Pe)},On=()=>{V.enable(`-${Pe}`)};var A=(r=>(r.PAUSE_MAIN_CAM="PAUSEMAINCAM",r.RESUME_MAIN_CAM="RESUMEMAINCAM",r.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",r.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",r.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",r))(A||{}),H=(r=>(r.ADMIN_STOP_MIC="ADMINSTOPMIC",r.ADMIN_START_MIC="ADMINSTARTMIC",r))(H||{}),q=(r=>(r.ADMIN_SYNC_FORCED="1",r.ADMIN_SYNC_NOT_FORCED="0",r))(q||{}),ut=(r=>(r.AUDIO="AUDIO",r.VIDEO="VIDEO",r.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",r))(ut||{});function fn(r){return e=>`sip:${e}@${r}`}const pn=(r,e)=>()=>Math.floor(Math.random()*(e-r))+r,Le=r=>r.trim().replaceAll(" ","_"),Dn=pn(1e5,99999999),k=(r,{videoMode:e,audioMode:t}={})=>{if(!r||e==="recvonly"&&t==="recvonly")return;const n=t==="recvonly"?[]:r.getAudioTracks(),s=e==="recvonly"?[]:r.getVideoTracks(),o=[...n,...s],a=new MediaStream(o);return a.getTracks=()=>[...a.getAudioTracks(),...a.getVideoTracks()],a},Pn=r=>r.some(t=>{const{kind:n}=t;return n==="video"}),Mn="Error decline with 603",vn=1006,bn=r=>typeof r=="object"&&r!==null&&"code"in r&&r.code===vn,yn=r=>r.message===Mn,wn=(r,e)=>r.find(t=>t.track&&e.getTracks().includes(t.track)),Nt=1,Ct=r=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==r,Un=Ct(Nt),Ln=(r,e)=>{const t=r===void 0?void 0:Math.max(r,Nt);if(t!==void 0&&Un(t,e))return t},Hn=Ct(),qn=(r,e)=>{if(Hn(r,e))return r},gt=async(r,e,t)=>{const n=r.getParameters();(n.encodings===void 0||n.encodings.length===0)&&(n.encodings=[{}]);const[s]=n.encodings,o=s.scaleResolutionDownBy,a=Ln(e.scaleResolutionDownBy,o);let c=!1;a!==void 0&&(n.encodings[0].scaleResolutionDownBy=a,c=!0);const _=s.maxBitrate,E=qn(e.maxBitrate,_);return E!==void 0&&(n.encodings[0].maxBitrate=E,c=!0),c?(t&&t(n),r.setParameters(n).then(()=>({parameters:n,isChanged:c}))):{parameters:n,isChanged:c}},Wn=async(r,e,t)=>{const n=wn(r,e);if(n)return gt(n,{maxBitrate:t})},kn=486,Fn=487,B="local",He="remote",Bn=3,Vn=(r=new Error)=>{const{originator:e,cause:t}=r;return N.isCanceledError(r)?!0:typeof t=="string"?t===qe||t===Y||e===B&&(t===Fe||t===ke):!1},C="SipConnector",Yn="channels",xn="WebcastStarted",Gn="WebcastStopped",$n="accountChanged",Xn="accountDeleted",Jn="addedToListModerators",zn="removedFromListModerators",Qn="ParticipationRequestAccepted",Kn="ParticipationRequestRejected",jn="ParticipantMovedToWebcast",Zn="ConferenceParticipantTokenIssued";class es{constructor({JsSIP:e}){i(this,"_isRegisterConfig",!1);i(this,"_connectionConfiguration",{});i(this,"_remoteStreams",{});i(this,"JsSIP");i(this,"_sessionEvents");i(this,"_uaEvents");i(this,"_cancelableConnect");i(this,"_cancelableConnectWithRepeatedCalls");i(this,"_cancelableInitUa");i(this,"_cancelableDisconnect");i(this,"_cancelableSet");i(this,"_cancelableCall");i(this,"_cancelableAnswer");i(this,"_cancelableSendDTMF");i(this,"getSipServerUrl",e=>e);i(this,"promisePendingStartPresentation");i(this,"promisePendingStopPresentation");i(this,"ua");i(this,"session");i(this,"incomingSession");i(this,"_streamPresentationCurrent");i(this,"socket");i(this,"connect",async(e,t)=>(this._cancelRequests(),this._connectWithDuplicatedCalls(e,t)));i(this,"initUa",async e=>this._cancelableInitUa.request(e));i(this,"set",async e=>this._cancelableSet.request(e));i(this,"call",async e=>this._cancelableCall.request(e));i(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));i(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));i(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));i(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));i(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(W,void 0);try{await this.unregister()}catch(e){F("tryRegister",e)}return this.register()});i(this,"declineToIncomingCall",async({statusCode:e=Fn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingSession"));return}const s=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(G,o),t(s.terminate({status_code:e}))}));i(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:kn}));i(this,"removeIncomingSession",()=>{delete this.incomingSession});i(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=Bn}={})=>{let n=!0;const s=async()=>(n=!1,this._cancelableConnect.request(e)),o=a=>{var h;const c=!!((h=this.ua)!=null&&h.isConnected()),_=!n&&c&&this.hasEqualConnectionConfiguration(e),E=!!a&&!bn(a);return _||E};return this._cancelableConnectWithRepeatedCalls=pt.repeatedCallsAsync({targetFunction:s,isComplete:o,callLimit:t,isRejectAsValid:!0,onAfterCancel:()=>{this._cancelableConnect.cancelRequest()}}),this._cancelableConnectWithRepeatedCalls.then(a=>{if(a instanceof this.JsSIP.UA)return a;throw a})});i(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===He){this.incomingSession=t;const n=this.remoteCallerData;t.on(g,s=>{this.removeIncomingSession(),s.originator===B?this._uaEvents.trigger(X,n):this._uaEvents.trigger($,n)}),this._uaEvents.trigger(x,n)}});i(this,"_connect",async e=>this.initUa(e).then(async()=>this._start()));i(this,"_initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:s,remoteAddress:o,sdpSemantics:a,sessionTimers:c,registerExpires:_,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:h,userAgent:d,displayName:l="",register:T=!1,extraHeaders:S=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!s)throw new Error("sipWebSocketServerURL is required");if(T&&!e)throw new Error("user is required for authorized connection");if(T&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:l,register:T,user:e,password:t};const{configuration:I,helpers:m}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:s,password:t,displayName:l,register:T,sdpSemantics:a,sessionTimers:c,registerExpires:_,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:h,userAgent:d});this.getSipServerUrl=m.getSipServerUrl,this.socket=m.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!T,this.ua=this._createUa(I),this._uaEvents.eachTriggers((Rt,It)=>{const Me=Oe.find(mt=>mt===It);Me&&this.ua&&this.ua.on(Me,Rt)});const At=[...Xt(o),...S];return this.ua.registrator().setExtraHeaders(At),this.ua});i(this,"_createUa",e=>new this.JsSIP.UA(e));i(this,"_start",async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const s=()=>{c(),e(n)},o=_=>{c(),t(_)},a=()=>{this.isRegisterConfig?(this.on(f,s),this.on(p,o)):this.on(O,s),this.on(u,o)},c=()=>{this.off(f,s),this.off(p,o),this.off(O,s),this.off(u,o)};a(),this.on(M,this.handleNewRTCSession),n.start()}));i(this,"_set",async({displayName:e,password:t})=>new Promise((n,s)=>{const{ua:o}=this;if(!o){s(new Error("this.ua is not initialized"));return}let a=!1,c=!1;e!==void 0&&e!==this._connectionConfiguration.displayName&&(a=o.set("display_name",Le(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const _=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(_)}).catch(E=>{s(E)}):_?n(_):s(new Error("nothing changed"))}));i(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());i(this,"_disconnect",async()=>{this.off(M,this.handleNewRTCSession);const e=new Promise(t=>{this.once(u,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(u,void 0)):this._uaEvents.trigger(u,void 0),e});i(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:s,iceServers:o,videoMode:a,audioMode:c,degradationPreference:_,offerToReceiveAudio:E=!0,offerToReceiveVideo:h=!0})=>new Promise((d,l)=>{const{ua:T}=this;if(!T){l(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:s}).then(d).catch(S=>{l(S)}),this.session=T.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:k(t,{videoMode:a,audioMode:c}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,degradationPreference:_,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:E,offerToReceiveVideo:h}})}));i(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:s,videoMode:o,audioMode:a,degradationPreference:c})=>new Promise((_,E)=>{if(!this.isAvailableIncomingCall){E(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:h}=this;if(!h){E(new Error("No session established"));return}this._sessionEvents.eachTriggers((l,T)=>{const S=fe.find(I=>I===T);S&&h.on(S,l)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=h.remote_identity.uri.user,this._handleCall({ontrack:t}).then(_).catch(l=>{E(l)});const d=k(e,{videoMode:o,audioMode:a});h.answer({extraHeaders:n,videoMode:o,audioMode:a,degradationPreference:c,mediaStream:d,pcConfig:{iceServers:s}})}));i(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const s=()=>{this.onSession(U,h),this.onSession(w,d)},o=()=>{this.offSession(U,h),this.offSession(w,d)},a=()=>{this.onSession(g,_),this.onSession(D,_)},c=()=>{this.offSession(g,_),this.offSession(D,_)},_=l=>{o(),c(),n(l)};let E;const h=({peerconnection:l})=>{E=l,E.ontrack=T=>{this._sessionEvents.trigger(ne,E),e&&e(T)}},d=()=>{E&&this._sessionEvents.trigger(te,E),o(),c(),t(E)};s(),a()}));i(this,"_restoreSession",()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});i(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{session:s}=this;if(!s){n(new Error("No session established"));return}this.onceSession(Re,({originator:o})=>{o===B&&t()}),s.sendDTMF(e,{duration:120,interToneGap:600})}));i(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent&&await this.stopPresentation(),this._restoreSession(),!e.isEnded())return e.terminateAsync()}});i(this,"_handleShareState",e=>{switch(e){case dt:{this._sessionEvents.trigger(Q,void 0);break}case Tt:{this._sessionEvents.trigger(K,void 0);break}case St:{this._sessionEvents.trigger(j,void 0);break}}});i(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(ye),n=e.getHeader(we);if(t&&n){const s={inputChannels:t,outputChannels:n};this._sessionEvents.trigger(b,s)}});i(this,"_handleNotify",e=>{switch(e.cmd){case Yn:{const t=e;this._triggerChannelsNotify(t);break}case xn:{const t=e;this._triggerWebcastStartedNotify(t);break}case Gn:{const t=e;this._triggerWebcastStoppedNotify(t);break}case Jn:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case zn:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case Qn:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case Kn:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case jn:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case $n:{this._triggerAccountChangedNotify();break}case Xn:{this._triggerAccountDeletedNotify();break}case Zn:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:F("unknown cmd",e.cmd)}});i(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(he,t)});i(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(_e,t)});i(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(ue,n)});i(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ne,n)});i(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ce,void 0)});i(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(ge,void 0)});i(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const s={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Ae,s)});i(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,s={inputChannels:t,outputChannels:n};this._uaEvents.trigger(se,s)});i(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Te,t)});i(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Se,t)});i(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(le,t)});i(this,"_triggerEnterRoom",e=>{const t=e.getHeader(zt),n=e.getHeader(sn);this._sessionEvents.trigger(Z,{room:t,participantName:n})});i(this,"_triggerShareState",e=>{const t=e.getHeader(R);this._sessionEvents.trigger(v,t)});i(this,"_maybeTriggerParticipantMoveRequestToSpectators",e=>{e.getHeader(dn)===_t&&this._sessionEvents.trigger(de,void 0)});i(this,"_triggerMainCamControl",e=>{const t=e.getHeader(rn),n=e.getHeader(Ue),s=n===q.ADMIN_SYNC_FORCED;if(t===A.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(ae,{isSyncForced:s});return}if(t===A.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(oe,{isSyncForced:s});return}(t===A.RESUME_MAIN_CAM||t===A.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(y,{isSyncForced:s});const o=e.getHeader(an);this._sessionEvents.trigger(re,{mainCam:t,resolutionMainCam:o})});i(this,"_triggerMicControl",e=>{const t=e.getHeader(on),s=e.getHeader(Ue)===q.ADMIN_SYNC_FORCED;t===H.ADMIN_START_MIC?this._sessionEvents.trigger(Ee,{isSyncForced:s}):t===H.ADMIN_STOP_MIC&&this._sessionEvents.trigger(ce,{isSyncForced:s})});i(this,"_triggerUseLicense",e=>{const t=e.getHeader(nn);this._sessionEvents.trigger(ee,t)});i(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,s=n.getHeader(Jt);if(s)switch(s){case Qt:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case Tn:{this._maybeHandleNotify(n);break}case P:{this._triggerShareState(n);break}case be:{this._triggerMainCamControl(n);break}case en:{this._triggerMicControl(n);break}case tn:{this._triggerUseLicense(n);break}case ln:{this._maybeTriggerParticipantMoveRequestToSpectators(n);break}}});i(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});i(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Sn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});i(this,"_handleEnded",e=>{const{originator:t}=e;t===He&&this._sessionEvents.trigger(ie,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new ve(De),this._uaEvents=new ve(pe),this._cancelableConnect=new N.CancelableRequest(this._connect,{moduleName:C,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new N.CancelableRequest(this._initUa,{moduleName:C}),this._cancelableDisconnect=new N.CancelableRequest(this._disconnect,{moduleName:C}),this._cancelableSet=new N.CancelableRequest(this._set,{moduleName:C}),this._cancelableCall=new N.CancelableRequest(this._call,{moduleName:C}),this._cancelableAnswer=new N.CancelableRequest(this._answer,{moduleName:C}),this._cancelableSendDTMF=new N.CancelableRequest(this._sendDTMF,{moduleName:C}),this.onSession(v,this._handleShareState),this.onSession(Ie,this._handleNewInfo),this.on(z,this._handleSipEvent),this.onSession(g,this._handleEnded),this.onSession(D,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(f,e),this.ua.on(p,t),this.ua.register()):t(new Error("Config is not registered"))})}async unregister(){return new Promise((e,t)=>{this.isRegistered&&this.ua?(this.ua.on(J,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,n){if(!this.ua)throw new Error("is not connected");return new Promise((s,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{s()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var s;if(!((s=this.ua)!=null&&s.configuration.uri))throw new Error("is not connected");const n=this.ua.configuration.uri;return this.sendOptions(n,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:n,sipWebSocketServerURL:s,sdpSemantics:o}){return new Promise((a,c)=>{const{configuration:_}=this.createUaConfiguration({sipWebSocketServerURL:s,displayName:t,sdpSemantics:o,userAgent:e,sipServerUrl:n}),E=this._createUa(_),h=()=>{const l=new Error("Telephony is not available");c(l)};E.once(u,h);const d=()=>{E.removeAllListeners(),E.once(u,a),E.stop()};E.once(O,d),E.start()})}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[In];return this.session.sendInfo(be,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(yn(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}hasEqualConnectionConfiguration(e){var s;const{configuration:t}=this.createUaConfiguration(e),n=(s=this.ua)==null?void 0:s.configuration;return(n==null?void 0:n.password)===t.password&&(n==null?void 0:n.register)===t.register&&(n==null?void 0:n.uri.toString())===t.uri&&(n==null?void 0:n.display_name)===t.display_name&&(n==null?void 0:n.user_agent)===t.user_agent&&(n==null?void 0:n.sdpSemantics)===t.sdp_semantics&&(n==null?void 0:n.sockets)===t.sockets&&(n==null?void 0:n.session_timers)===t.session_timers&&(n==null?void 0:n.register_expires)===t.register_expires&&(n==null?void 0:n.connection_recovery_min_interval)===t.connection_recovery_min_interval&&(n==null?void 0:n.connection_recovery_max_interval)===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:s="",sipServerUrl:o,register:a=!1,sdpSemantics:c="plan-b",sessionTimers:_=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:d=6,userAgent:l}){if(a&&!t)throw new Error("password is required for authorized connection");const T=a&&e?e.trim():`${Dn()}`,S=fn(o),I=S(T),m=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:I,display_name:Le(s),user_agent:l,sdp_semantics:c,sockets:[m],session_timers:_,register_expires:E,connection_recovery_min_interval:h,connection_recovery_max_interval:d},helpers:{socket:m,getSipServerUrl:S}}}async _sendPresentation(e,t,{maxBitrate:n,degradationPreference:s,isNeedReinvite:o=!0,isP2P:a=!1}){const c=k(t);this._streamPresentationCurrent=c;const _=a?[gn]:[un],E=e.sendInfo(P,void 0,{extraHeaders:_}).then(async()=>e.startPresentation(c,o,s)).then(async()=>{const{connection:h}=this;if(!h||n===void 0)return;const d=h.getSenders();await Wn(d,t,n)}).then(()=>t).catch(h=>{throw this._sessionEvents.trigger(L,h),h});return this.promisePendingStartPresentation=E,E.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t=!0,isP2P:n=!1,maxBitrate:s,degradationPreference:o}={}){const a=this.establishedSession;if(!a)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(a),this._sendPresentation(a,e,{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o})}async sendMustStopPresentation(e){await e.sendInfo(P,void 0,{extraHeaders:[Cn]})}async stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const s=e?[An]:[Nn],o=this.establishedSession;return o&&t&&(n=n.then(async()=>o.sendInfo(P,void 0,{extraHeaders:s})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(L,a),a})),!o&&t&&this._sessionEvents.trigger(me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t=!1,maxBitrate:n,degradationPreference:s}={}){const o=this.establishedSession;if(!o)throw new Error("No session established");if(!this._streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this._sendPresentation(o,e,{isP2P:t,maxBitrate:n,degradationPreference:s,isNeedReinvite:!1})}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}async wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}async waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return{...this._connectionConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:n})=>n);return Pn(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,s,o,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(s=(n=this.incomingSession)==null?void 0:n.remote_identity)==null?void 0:s.uri.host,incomingNumber:(a=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:a.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){var e;return(e=this.session)!=null&&e.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_generateStream(e,t){const{id:n}=e,s=this._remoteStreams[n]||new MediaStream;return t&&s.addTrack(t),s.addTrack(e),this._remoteStreams[n]=s,s}_generateAudioStream(e){const{id:t}=e,n=this._remoteStreams[t]||new MediaStream;return n.addTrack(e),this._remoteStreams[t]=n,n}_generateStreams(e){const t=[];return e.forEach((n,s)=>{if(n.kind==="audio")return;const o=n,a=e[s-1];let c;a&&a.kind==="audio"&&(c=a);const _=this._generateStream(o,c);t.push(_)}),t}_generateAudioStreams(e){return e.map(n=>this._generateAudioStream(n))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectWithRepeatedCalls()}_cancelConnectWithRepeatedCalls(){var e;(e=this._cancelableConnectWithRepeatedCalls)==null||e.cancel()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(b)}async waitSyncMediaState(){return this.waitSession(y)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=`${ye}: ${e}`,s=`${we}: ${t}`,o=[n,s];return this.session.sendInfo(Kt,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.session)throw new Error("No session established");const s=`${cn}: currentstate`,o=`${_n}: ${Number(e)}`,a=`${hn}: ${Number(t)}`,c=[s,o,a];return this.session.sendInfo(jt,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${En}: ${e==="mic"?0:1}`];return this.session.sendInfo(Zt,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}exports.BAD_MEDIA_DESCRIPTION=Be;exports.EEventsMainCAM=A;exports.EEventsMic=H;exports.EEventsSyncMediaState=q;exports.EUseLicense=ut;exports.NOT_FOUND=We;exports.REJECTED=Y;exports.SESSION_EVENT_NAMES=De;exports.SipConnector=es;exports.UA_EVENT_NAMES=pe;exports.causes=xt;exports.constants=Gt;exports.disableDebug=On;exports.enableDebug=mn;exports.eventNames=$t;exports.hasCanceledCallError=Vn;exports.logger=F;exports.setEncodingsToSender=gt;
@@ -1,4 +1,4 @@
1
- import { IncomingInfoEvent, IncomingRTCSessionEvent, IncomingRequest, OutgoingInfoEvent, RTCSession, RegisteredEvent, UA, URI, UnRegisteredEvent, WebSocketInterface } from '@krivega/jssip';
1
+ import { IncomingInfoEvent, IncomingRTCSessionEvent, IncomingRequest, OutgoingInfoEvent, RTCSession, RegisteredEvent, UA, UAConfigurationParams, URI, UnRegisteredEvent, WebSocketInterface } from '@krivega/jssip';
2
2
  import { TEventSession, TEventUA } from './eventNames';
3
3
  import { TCustomError, TJsSIP } from './types';
4
4
 
@@ -75,7 +75,6 @@ type TOptionsExtraHeaders = {
75
75
  extraHeaders?: string[];
76
76
  };
77
77
  type TOntrack = (track: RTCTrackEvent) => void;
78
- type TGetServerUrl = (id: string) => string;
79
78
  type TParametersConnection = TOptionsExtraHeaders & {
80
79
  displayName?: string;
81
80
  user?: string;
@@ -91,20 +90,6 @@ type TParametersConnection = TOptionsExtraHeaders & {
91
90
  connectionRecoveryMaxInterval?: number;
92
91
  userAgent?: string;
93
92
  };
94
- type TParametersCreateUa = {
95
- socket: WebSocketInterface;
96
- displayName: string;
97
- getSipServerUrl: TGetServerUrl;
98
- user?: string;
99
- register?: boolean;
100
- password?: string;
101
- sdpSemantics?: 'plan-b' | 'unified-plan';
102
- sessionTimers?: boolean;
103
- registerExpires?: number;
104
- connectionRecoveryMinInterval?: number;
105
- connectionRecoveryMaxInterval?: number;
106
- userAgent?: string;
107
- };
108
93
  type TParametersCheckTelephony = {
109
94
  displayName: string;
110
95
  sipServerUrl: string;
@@ -112,9 +97,11 @@ type TParametersCheckTelephony = {
112
97
  sdpSemantics?: 'plan-b' | 'unified-plan';
113
98
  userAgent?: string;
114
99
  };
115
- type TConnect = (parameters: TParametersConnection) => Promise<UA>;
100
+ type TConnect = (parameters: TParametersConnection, options?: {
101
+ callLimit?: number;
102
+ }) => Promise<UA>;
116
103
  type TInitUa = (parameters: TParametersConnection) => Promise<UA>;
117
- type TCreateUa = (parameters: TParametersCreateUa) => UA;
104
+ type TCreateUa = (parameters: UAConfigurationParams) => UA;
118
105
  type TStart = () => Promise<UA>;
119
106
  type TSet = ({ displayName, password, }: {
120
107
  displayName?: string;
@@ -154,6 +141,7 @@ export default class SipConnector {
154
141
  private readonly _sessionEvents;
155
142
  private readonly _uaEvents;
156
143
  private readonly _cancelableConnect;
144
+ private _cancelableConnectWithRepeatedCalls;
157
145
  private readonly _cancelableInitUa;
158
146
  private readonly _cancelableDisconnect;
159
147
  private readonly _cancelableSet;
@@ -198,6 +186,9 @@ export default class SipConnector {
198
186
  removeIncomingSession: () => void;
199
187
  askPermissionToEnableCam(options?: TOptionsInfoMediaState): Promise<void>;
200
188
  get isPendingPresentation(): boolean;
189
+ private readonly _connectWithDuplicatedCalls;
190
+ private hasEqualConnectionConfiguration;
191
+ private createUaConfiguration;
201
192
  private _sendPresentation;
202
193
  startPresentation(stream: MediaStream, { isNeedReinvite, isP2P, maxBitrate, degradationPreference, }?: {
203
194
  isNeedReinvite?: boolean;
@@ -270,7 +261,7 @@ export default class SipConnector {
270
261
  _generateAudioStreams(remoteTracks: MediaStreamTrack[]): MediaStream[];
271
262
  _hangUpWithoutCancelRequests: THangUp;
272
263
  _cancelRequests(): void;
273
- _cancelConnectRequests(): void;
264
+ _cancelConnectWithRepeatedCalls(): void;
274
265
  _cancelCallRequests(): void;
275
266
  _cancelActionsRequests(): void;
276
267
  _handleShareState: (eventName: string) => void;
@@ -7,8 +7,26 @@ import { default as Session } from './Session.mock';
7
7
  export declare const PASSWORD_CORRECT = "PASSWORD_CORRECT";
8
8
  export declare const PASSWORD_CORRECT_2 = "PASSWORD_CORRECT_2";
9
9
  export declare const NAME_INCORRECT = "NAME_INCORRECT";
10
+ export declare const createWebsocketHandshakeTimeoutError: (sipServerUrl: string) => {
11
+ socket: {
12
+ _url: string;
13
+ _sip_uri: string;
14
+ _via_transport: string;
15
+ _ws: null;
16
+ };
17
+ error: boolean;
18
+ code: number;
19
+ reason: string;
20
+ };
10
21
  declare class UA implements IUA {
11
22
  private static isAvailableTelephony;
23
+ private static startError?;
24
+ private static countStartError;
25
+ private static countStarts;
26
+ static setStartError(startError: unknown, { count }?: {
27
+ count?: number;
28
+ }): void;
29
+ static resetStartError(): void;
12
30
  static setAvailableTelephony(): void;
13
31
  static setNotAvailableTelephony(): void;
14
32
  _events: Events<typeof UA_EVENT_NAMES>;
@@ -20,6 +38,7 @@ declare class UA implements IUA {
20
38
  configuration: UAConfiguration;
21
39
  _registrator: Registrator;
22
40
  constructor(_configuration: UAConfigurationParams);
41
+ isConnected(): boolean;
23
42
  /**
24
43
  * start
25
44
  *
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var k=Object.defineProperty;var D=(o,t,e)=>t in o?k(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>(D(o,typeof t!="symbol"?t+"":t,e),e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("./SipConnector-DxGNVRHG.cjs"),b=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),P=require("node:events"),F=require("@krivega/jssip/lib/SIPMessage"),C=require("webrtc-mock"),T=require("events-constructor"),M=require("@krivega/jssip");class S extends F.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class U{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new T(u.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}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 remote_identity(){return this._remote_identity}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.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class V{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e={track:t};return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function z(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const p=400,y="777",q=o=>o.getVideoTracks().length>0;class A extends U{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:s}){super({originator:s,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"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)},p)}));this.url=e,this.initPeerconnection(n)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=C.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(q(e)){const c=C.createVideoMediaStreamTrackMock();c.id="mainvideo1",i.push(c)}this._connection=new V(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},p)}connect(e){const n=z(e);setTimeout(()=>{this.url.includes(y)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:u.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},p)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}}class x{constructor(){r(this,"extraHeaders")}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const a="PASSWORD_CORRECT",w="PASSWORD_CORRECT_2",I="NAME_INCORRECT",h=400,m=class m{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new A({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new T(u.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,s]=n.split("@"),c={...t,uri:new M.URI(e,i,s)};this.configuration=c,this._registrator=new x}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}start(){this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},h):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(I)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},h)):!this._isRegistered&&e&&(t===a||t===w)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},h)):e&&t!==a&&t!==w&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},h)),m.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(m,"isAvailableTelephony",!0);let E=m;class H{constructor(t){r(this,"url");this.url=t}}class j extends P.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const f="remote",B=(o,t)=>{const e=new S(t),n={originator:f,request:e,info:new j("","")};o.newInfo(n)},K=(o,t)=>{const n={request:new S(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new A({originator:f}),s=new L("sip",t,n);i._remote_identity=new b(s,e),o.trigger("newRTCSession",{originator:f,session:i})},J=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},N={triggerNewInfo:B,triggerNewSipEvent:K,triggerIncomingSession:$,triggerFailIncomingSession:J,WebSocketInterface:H,UA:E,C:{INVITE:"INVITE"}},l="user",d="displayName",g="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",Y=new N.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:g,sipWebSocketServerURL:R},G={...v},O={...v,user:l,password:a,register:!0},X={...O,displayName:d},Q={...v,displayName:d,register:!1},_={session_timers:!1,sockets:[Y],user_agent:"Chrome",sdp_semantics:"plan-b",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Z={..._,password:a,uri:new M.URI("sip",l,g),display_name:"",register:!0},ee={..._,password:a,uri:new M.URI("sip",l,g),display_name:d,register:!0},te={..._,display_name:d,register:!1},re={..._,display_name:"",register:!1},W="10.10.10.10",ne=[`X-Vinteo-Remote: ${W}`],oe=()=>new u.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=y;exports.NAME_INCORRECT=I;exports.PASSWORD_CORRECT=a;exports.PASSWORD_CORRECT_2=w;exports.SIP_SERVER_URL=g;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=X;exports.dataForConnectionWithoutAuthorization=Q;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=G;exports.default=oe;exports.displayName=d;exports.extraHeadersRemoteAddress=ne;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=Z;exports.uaConfigurationWithAuthorizationWithDisplayName=ee;exports.uaConfigurationWithoutAuthorization=te;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=re;exports.user=l;
1
+ "use strict";var b=Object.defineProperty;var k=(o,t,e)=>t in o?b(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>k(o,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const m=require("./SipConnector-3pnvrFP5.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),P=require("@krivega/jssip/lib/URI"),L=require("node:events"),F=require("@krivega/jssip/lib/SIPMessage"),T=require("webrtc-mock"),v=require("events-constructor"),M=require("@krivega/jssip");class C extends F.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class V{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new v(m.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}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 remote_identity(){return this._remote_identity}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.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class z{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e={track:t};return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function U(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const p=400,I="777",q=o=>o.getVideoTracks().length>0;class y extends V{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:a}){super({originator:a,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"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)},p)}));this.url=e,this.initPeerconnection(n)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=T.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(q(e)){const h=T.createVideoMediaStreamTrackMock();h.id="mainvideo1",i.push(h)}this._connection=new z(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},p)}connect(e){const n=U(e);setTimeout(()=>{this.url.includes(I)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:m.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},p)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}}class x{constructor(){r(this,"extraHeaders")}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const d="PASSWORD_CORRECT",w="PASSWORD_CORRECT_2",N="NAME_INCORRECT",u=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new y({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new v(m.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,a]=n.split("@"),h={...t,uri:new M.URI(e,i,a)};this.configuration=h,this._registrator=new x}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},u):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(N)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},u)):!this._isRegistered&&e&&(t===d||t===w)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},u)):e&&t!==d&&t!==w&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},u)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let E=s;class H{constructor(t){r(this,"url");this.url=t}}class j extends L.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const f="remote",B=(o,t)=>{const e=new C(t),n={originator:f,request:e,info:new j("","")};o.newInfo(n)},Y=(o,t)=>{const n={request:new C(t)};o.newSipEvent(n)},K=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new y({originator:f}),a=new P("sip",t,n);i._remote_identity=new D(a,e),o.trigger("newRTCSession",{originator:f,session:i})},$=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:B,triggerNewSipEvent:Y,triggerIncomingSession:K,triggerFailIncomingSession:$,WebSocketInterface:H,UA:E,C:{INVITE:"INVITE"}},l="user",c="displayName",g="SIP_SERVER_URL",S="SIP_WEB_SOCKET_SERVER_URL",J=new A.WebSocketInterface(S),R={userAgent:"Chrome",sipServerUrl:g,sipWebSocketServerURL:S},G={...R},O={...R,user:l,password:d,register:!0},X={...O,displayName:c},Q={...R,displayName:c,register:!1},_={session_timers:!1,sockets:[J],user_agent:"Chrome",sdp_semantics:"plan-b",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Z={..._,password:d,uri:new M.URI("sip",l,g),display_name:"",register:!0},ee={..._,password:d,uri:new M.URI("sip",l,g),display_name:c,register:!0},te={..._,display_name:c,register:!1},re={..._,display_name:"",register:!1},W="10.10.10.10",ne=[`X-Vinteo-Remote: ${W}`],oe=()=>new m.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=I;exports.NAME_INCORRECT=N;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=w;exports.SIP_SERVER_URL=g;exports.SIP_WEB_SOCKET_SERVER_URL=S;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=X;exports.dataForConnectionWithoutAuthorization=Q;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=G;exports.default=oe;exports.displayName=c;exports.extraHeadersRemoteAddress=ne;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=Z;exports.uaConfigurationWithAuthorizationWithDisplayName=ee;exports.uaConfigurationWithoutAuthorization=te;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=re;exports.user=l;
package/dist/doMock.js CHANGED
@@ -1,15 +1,15 @@
1
- var y = Object.defineProperty;
2
- var I = (o, t, e) => t in o ? y(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
- var r = (o, t, e) => (I(o, typeof t != "symbol" ? t + "" : t, e), e);
4
- import { j as A, R as O, U as k, S as N } from "./SipConnector-CxSB1Bmp.js";
1
+ var I = Object.defineProperty;
2
+ var y = (o, t, e) => t in o ? I(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
+ var r = (o, t, e) => y(o, typeof t != "symbol" ? t + "" : t, e);
4
+ import { j as N, R as O, U as A, S as k } from "./SipConnector-3gRIidBJ.js";
5
5
  import b from "@krivega/jssip/lib/NameAddrHeader";
6
6
  import D from "@krivega/jssip/lib/URI";
7
7
  import { EventEmitter as L } from "node:events";
8
- import { IncomingRequest as W } from "@krivega/jssip/lib/SIPMessage";
9
- import { createAudioMediaStreamTrackMock as P, createVideoMediaStreamTrackMock as V } from "webrtc-mock";
8
+ import { IncomingRequest as P } from "@krivega/jssip/lib/SIPMessage";
9
+ import { createAudioMediaStreamTrackMock as W, createVideoMediaStreamTrackMock as V } from "webrtc-mock";
10
10
  import v from "events-constructor";
11
11
  import { URI as p } from "@krivega/jssip";
12
- class T extends W {
12
+ class T extends P {
13
13
  constructor(e) {
14
14
  super();
15
15
  r(this, "headers");
@@ -19,7 +19,7 @@ class T extends W {
19
19
  return this.headers.get(e) || "";
20
20
  }
21
21
  }
22
- class U {
22
+ class F {
23
23
  // @ts-expect-error
24
24
  constructor({ originator: t = "local", eventHandlers: e }) {
25
25
  r(this, "originator");
@@ -27,7 +27,7 @@ class U {
27
27
  r(this, "_events");
28
28
  r(this, "_remote_identity");
29
29
  r(this, "_mutedOptions", { audio: !1, video: !1 });
30
- this.originator = t, this._events = new v(A), this.initEvents(e);
30
+ this.originator = t, this._events = new v(N), this.initEvents(e);
31
31
  }
32
32
  // @ts-expect-error
33
33
  get C() {
@@ -294,21 +294,21 @@ class x {
294
294
  throw new Error("Method not implemented.");
295
295
  }
296
296
  }
297
- function F(o) {
297
+ function U(o) {
298
298
  const t = o.match(/(purgatory)|[\d.]+/g);
299
299
  if (!t)
300
300
  throw new Error("wrong sip url");
301
301
  return t[0];
302
302
  }
303
- const u = 400, H = "777", z = (o) => o.getVideoTracks().length > 0;
304
- class R extends U {
303
+ const l = 400, H = "777", z = (o) => o.getVideoTracks().length > 0;
304
+ class S extends F {
305
305
  constructor({
306
306
  url: e = "",
307
307
  mediaStream: n,
308
308
  eventHandlers: i,
309
- originator: s
309
+ originator: a
310
310
  }) {
311
- super({ originator: s, eventHandlers: i });
311
+ super({ originator: a, eventHandlers: i });
312
312
  r(this, "url");
313
313
  r(this, "status_code");
314
314
  r(this, "_isEnded", !1);
@@ -330,7 +330,7 @@ class R extends U {
330
330
  }, 100), setTimeout(() => {
331
331
  this.trigger("confirmed");
332
332
  }, 200);
333
- }, u);
333
+ }, l);
334
334
  }));
335
335
  this.url = e, this.initPeerconnection(n);
336
336
  }
@@ -338,19 +338,19 @@ class R extends U {
338
338
  return e ? (this.createPeerconnection(e), !0) : !1;
339
339
  }
340
340
  createPeerconnection(e) {
341
- const n = P();
341
+ const n = W();
342
342
  n.id = "mainaudio1";
343
343
  const i = [n];
344
344
  if (z(e)) {
345
- const d = V();
346
- d.id = "mainvideo1", i.push(d);
345
+ const c = V();
346
+ c.id = "mainvideo1", i.push(c);
347
347
  }
348
348
  this._connection = new x(void 0, i), this._addStream(e), setTimeout(() => {
349
349
  this.trigger("peerconnection", { peerconnection: this.connection });
350
- }, u);
350
+ }, l);
351
351
  }
352
352
  connect(e) {
353
- const n = F(e);
353
+ const n = U(e);
354
354
  setTimeout(() => {
355
355
  this.url.includes(H) ? this.trigger("failed", {
356
356
  originator: "remote",
@@ -363,7 +363,7 @@ class R extends U {
363
363
  }, 200), setTimeout(() => {
364
364
  this.trigger("confirmed");
365
365
  }, 300));
366
- }, u);
366
+ }, l);
367
367
  }
368
368
  terminate({ status_code: e } = {}) {
369
369
  return this.status_code = e, this.trigger("ended", { status_code: e }), this._isEnded = !1, this;
@@ -434,7 +434,7 @@ class q {
434
434
  setExtraContactParams() {
435
435
  }
436
436
  }
437
- const a = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", c = 400, h = class h {
437
+ const d = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", h = 400, s = class s {
438
438
  constructor(t) {
439
439
  r(this, "_events");
440
440
  r(this, "_startedTimeout");
@@ -447,14 +447,20 @@ const a = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", c
447
447
  // @ts-expect-error
448
448
  r(this, "call", jest.fn((t, e) => {
449
449
  const { mediaStream: n, eventHandlers: i } = e;
450
- return this.session = new R({ url: t, mediaStream: n, eventHandlers: i, originator: "local" }), this.session.connect(t), this.session;
450
+ return this.session = new S({ url: t, mediaStream: n, eventHandlers: i, originator: "local" }), this.session.connect(t), this.session;
451
451
  }));
452
- this._events = new v(k);
453
- const [e, n] = t.uri.split(":"), [i, s] = n.split("@"), d = {
452
+ this._events = new v(A);
453
+ const [e, n] = t.uri.split(":"), [i, a] = n.split("@"), c = {
454
454
  ...t,
455
- uri: new p(e, i, s)
455
+ uri: new p(e, i, a)
456
456
  };
457
- this.configuration = d, this._registrator = new q();
457
+ this.configuration = c, this._registrator = new q();
458
+ }
459
+ static setStartError(t, { count: e = Number.POSITIVE_INFINITY } = {}) {
460
+ this.startError = t, this.countStartError = e;
461
+ }
462
+ static resetStartError() {
463
+ this.startError = void 0, this.countStartError = Number.POSITIVE_INFINITY, this.countStarts = 0;
458
464
  }
459
465
  static setAvailableTelephony() {
460
466
  this.isAvailableTelephony = !0;
@@ -462,12 +468,19 @@ const a = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", c
462
468
  static setNotAvailableTelephony() {
463
469
  this.isAvailableTelephony = !1;
464
470
  }
471
+ isConnected() {
472
+ return !!this._isConnected;
473
+ }
465
474
  /**
466
475
  * start
467
476
  *
468
477
  * @returns {undefined}
469
478
  */
470
479
  start() {
480
+ if (s.countStarts += 1, s.startError && s.countStarts < s.countStartError) {
481
+ this.trigger("disconnected", s.startError);
482
+ return;
483
+ }
471
484
  this.register();
472
485
  }
473
486
  /**
@@ -478,7 +491,7 @@ const a = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", c
478
491
  stop() {
479
492
  this._startedTimeout && clearTimeout(this._startedTimeout), this._stopedTimeout && clearTimeout(this._stopedTimeout), this.unregister(), this.isStarted() ? this._stopedTimeout = setTimeout(() => {
480
493
  this.trigger("disconnected", { error: new Error("stoped") });
481
- }, c) : this.trigger("disconnected", { error: new Error("stoped") });
494
+ }, h) : this.trigger("disconnected", { error: new Error("stoped") });
482
495
  }
483
496
  // @ts-expect-error
484
497
  on(t, e) {
@@ -527,11 +540,11 @@ const a = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", c
527
540
  const { password: t, register: e, uri: n } = this.configuration;
528
541
  e && n.user.includes(j) ? (this._isRegistered = !1, this._isConnected = !1, this._startedTimeout = setTimeout(() => {
529
542
  this.trigger("registrationFailed", { response: null, cause: "Request Timeout" });
530
- }, c)) : !this._isRegistered && e && (t === a || t === M) ? (this._isRegistered = !0, this._startedTimeout = setTimeout(() => {
543
+ }, h)) : !this._isRegistered && e && (t === d || t === M) ? (this._isRegistered = !0, this._startedTimeout = setTimeout(() => {
531
544
  this.trigger("registered");
532
- }, c)) : e && t !== a && t !== M && (this._isRegistered = !1, this._isConnected = !1, this._startedTimeout = setTimeout(() => {
545
+ }, h)) : e && t !== d && t !== M && (this._isRegistered = !1, this._isConnected = !1, this._startedTimeout = setTimeout(() => {
533
546
  this.trigger("registrationFailed", { response: null, cause: "Wrong credentials" });
534
- }, c)), h.isAvailableTelephony ? (this.trigger("connected"), this._isConnected = !0) : this.stop();
547
+ }, h)), s.isAvailableTelephony ? (this.trigger("connected"), this._isConnected = !0) : this.stop();
535
548
  }
536
549
  /**
537
550
  * unregister
@@ -564,15 +577,15 @@ const a = "PASSWORD_CORRECT", M = "PASSWORD_CORRECT_2", j = "NAME_INCORRECT", c
564
577
  this.trigger("sipEvent", t);
565
578
  }
566
579
  };
567
- r(h, "isAvailableTelephony", !0);
568
- let g = h;
569
- class B {
580
+ r(s, "isAvailableTelephony", !0), r(s, "startError"), r(s, "countStartError", Number.POSITIVE_INFINITY), r(s, "countStarts", 0);
581
+ let g = s;
582
+ class Y {
570
583
  constructor(t) {
571
584
  r(this, "url");
572
585
  this.url = t;
573
586
  }
574
587
  }
575
- class K extends L {
588
+ class B extends L {
576
589
  constructor(e, n) {
577
590
  super();
578
591
  r(this, "contentType");
@@ -580,36 +593,36 @@ class K extends L {
580
593
  this.contentType = e, this.body = n;
581
594
  }
582
595
  }
583
- const _ = "remote", $ = (o, t) => {
596
+ const _ = "remote", K = (o, t) => {
584
597
  const e = new T(t), n = {
585
598
  originator: _,
586
599
  request: e,
587
- info: new K("", "")
600
+ info: new B("", "")
588
601
  };
589
602
  o.newInfo(n);
590
- }, J = (o, t) => {
603
+ }, $ = (o, t) => {
591
604
  const n = { request: new T(t) };
592
605
  o.newSipEvent(n);
593
- }, Y = (o, {
606
+ }, J = (o, {
594
607
  incomingNumber: t = "1234",
595
608
  displayName: e,
596
609
  host: n
597
610
  }) => {
598
- const i = new R({ originator: _ }), s = new D("sip", t, n);
599
- i._remote_identity = new b(s, e), o.trigger("newRTCSession", { originator: _, session: i });
611
+ const i = new S({ originator: _ }), a = new D("sip", t, n);
612
+ i._remote_identity = new b(a, e), o.trigger("newRTCSession", { originator: _, session: i });
600
613
  }, G = (o, t) => {
601
614
  t ? o.trigger("failed", t) : o.trigger("failed", o);
602
- }, S = {
603
- triggerNewInfo: $,
604
- triggerNewSipEvent: J,
605
- triggerIncomingSession: Y,
615
+ }, R = {
616
+ triggerNewInfo: K,
617
+ triggerNewSipEvent: $,
618
+ triggerIncomingSession: J,
606
619
  triggerFailIncomingSession: G,
607
- WebSocketInterface: B,
620
+ WebSocketInterface: Y,
608
621
  UA: g,
609
622
  C: {
610
623
  INVITE: "INVITE"
611
624
  }
612
- }, w = "user", m = "displayName", E = "SIP_SERVER_URL", C = "SIP_WEB_SOCKET_SERVER_URL", X = new S.WebSocketInterface(C), f = {
625
+ }, w = "user", m = "displayName", E = "SIP_SERVER_URL", C = "SIP_WEB_SOCKET_SERVER_URL", X = new R.WebSocketInterface(C), f = {
613
626
  userAgent: "Chrome",
614
627
  sipServerUrl: E,
615
628
  sipWebSocketServerURL: C
@@ -618,7 +631,7 @@ const _ = "remote", $ = (o, t) => {
618
631
  }, Q = {
619
632
  ...f,
620
633
  user: w,
621
- password: a,
634
+ password: d,
622
635
  register: !0
623
636
  }, he = {
624
637
  ...Q,
@@ -627,7 +640,7 @@ const _ = "remote", $ = (o, t) => {
627
640
  ...f,
628
641
  displayName: m,
629
642
  register: !1
630
- }, l = {
643
+ }, u = {
631
644
  session_timers: !1,
632
645
  sockets: [X],
633
646
  user_agent: "Chrome",
@@ -635,33 +648,33 @@ const _ = "remote", $ = (o, t) => {
635
648
  register_expires: 300,
636
649
  connection_recovery_max_interval: 6,
637
650
  connection_recovery_min_interval: 2
638
- }, le = {
639
- ...l,
640
- password: a,
651
+ }, ue = {
652
+ ...u,
653
+ password: d,
641
654
  uri: new p("sip", w, E),
642
655
  display_name: "",
643
656
  register: !0
644
- }, ue = {
645
- ...l,
646
- password: a,
657
+ }, le = {
658
+ ...u,
659
+ password: d,
647
660
  uri: new p("sip", w, E),
648
661
  display_name: m,
649
662
  register: !0
650
663
  }, ge = {
651
- ...l,
664
+ ...u,
652
665
  display_name: m,
653
666
  register: !1
654
667
  }, _e = {
655
- ...l,
668
+ ...u,
656
669
  display_name: "",
657
670
  register: !1
658
- }, Z = "10.10.10.10", pe = [`X-Vinteo-Remote: ${Z}`], we = () => new N({
659
- JsSIP: S
671
+ }, Z = "10.10.10.10", pe = [`X-Vinteo-Remote: ${Z}`], we = () => new k({
672
+ JsSIP: R
660
673
  });
661
674
  export {
662
675
  H as FAILED_CONFERENCE_NUMBER,
663
676
  j as NAME_INCORRECT,
664
- a as PASSWORD_CORRECT,
677
+ d as PASSWORD_CORRECT,
665
678
  M as PASSWORD_CORRECT_2,
666
679
  E as SIP_SERVER_URL,
667
680
  C as SIP_WEB_SOCKET_SERVER_URL,
@@ -673,8 +686,8 @@ export {
673
686
  m as displayName,
674
687
  pe as extraHeadersRemoteAddress,
675
688
  Z as remoteAddress,
676
- le as uaConfigurationWithAuthorization,
677
- ue as uaConfigurationWithAuthorizationWithDisplayName,
689
+ ue as uaConfigurationWithAuthorization,
690
+ le as uaConfigurationWithAuthorizationWithDisplayName,
678
691
  ge as uaConfigurationWithoutAuthorization,
679
692
  _e as uaConfigurationWithoutAuthorizationWithoutDisplayName,
680
693
  w as user