sip-connector 8.2.1 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/SipConnector-BCc5pokv.cjs +1 -0
  2. package/dist/{SipConnector-CpJaoOHN.js → SipConnector-DagL4rCl.js} +216 -205
  3. package/dist/SipConnector.d.ts +5 -5
  4. package/dist/__fixtures__/BaseSession.mock.d.ts +0 -1
  5. package/dist/__fixtures__/RTCPeerConnectionMock.d.ts +0 -1
  6. package/dist/__fixtures__/Registrator.mock.d.ts +0 -1
  7. package/dist/__fixtures__/Request.mock.d.ts +0 -1
  8. package/dist/__fixtures__/Session.mock.d.ts +0 -1
  9. package/dist/__fixtures__/UA.mock.d.ts +0 -1
  10. package/dist/__fixtures__/index.d.ts +0 -1
  11. package/dist/__fixtures__/jssip.mock.d.ts +0 -1
  12. package/dist/constants.d.ts +1 -0
  13. package/dist/doMock.cjs +1 -1
  14. package/dist/doMock.d.ts +0 -1
  15. package/dist/doMock.js +2 -1
  16. package/dist/index.cjs +1 -1
  17. package/dist/index.d.ts +0 -1
  18. package/dist/index.js +141 -137
  19. package/dist/logger.d.ts +0 -1
  20. package/dist/tools/__fixtures__/call.d.ts +0 -1
  21. package/dist/tools/__fixtures__/connectToServer.d.ts +0 -1
  22. package/dist/tools/__fixtures__/hasValidUri.d.ts +0 -1
  23. package/dist/tools/__fixtures__/processRequest.d.ts +0 -1
  24. package/dist/tools/answerIncomingCall.d.ts +0 -1
  25. package/dist/tools/callToServer.d.ts +0 -1
  26. package/dist/tools/connectToServer.d.ts +0 -1
  27. package/dist/tools/disconnectFromServer.d.ts +0 -1
  28. package/dist/tools/error/getLinkError.d.ts +0 -1
  29. package/dist/tools/error/getTypeFromError.d.ts +0 -1
  30. package/dist/tools/error/getValuesFromError.d.ts +0 -1
  31. package/dist/tools/prepareMediaStream.d.ts +7 -0
  32. package/dist/tools/resolveAskPermissionToEnableCam.d.ts +0 -1
  33. package/dist/tools/resolveGetRemoteStreams.d.ts +0 -1
  34. package/dist/tools/resolveOnMoveToSpectators.d.ts +0 -1
  35. package/dist/tools/resolveOnMustStopPresentation.d.ts +0 -1
  36. package/dist/tools/resolveOnUseLicense.d.ts +0 -1
  37. package/dist/tools/resolveSendMediaState.d.ts +0 -1
  38. package/dist/tools/resolveSendRefusalToTurnOnCam.d.ts +0 -1
  39. package/dist/tools/resolveSendRefusalToTurnOnMic.d.ts +0 -1
  40. package/dist/tools/resolveStartPresentation.d.ts +5 -5
  41. package/dist/tools/resolveStopShareSipConnector.d.ts +1 -4
  42. package/dist/tools/resolveUpdatePresentation.d.ts +5 -5
  43. package/dist/tools/resolveUpdateRemoteStreams.d.ts +1 -1
  44. package/dist/tools/setVideoTrackContentHints.d.ts +3 -0
  45. package/dist/tools/syncMediaState/index.d.ts +0 -1
  46. package/dist/tools/syncMediaState/resolveOnStartMainCam.d.ts +0 -1
  47. package/dist/tools/syncMediaState/resolveOnStartMic.d.ts +0 -1
  48. package/dist/tools/syncMediaState/resolveOnStopMainCam.d.ts +0 -1
  49. package/dist/tools/syncMediaState/resolveOnStopMic.d.ts +0 -1
  50. package/dist/types.d.ts +2 -1
  51. package/dist/utils.d.ts +0 -4
  52. package/dist/videoSendingBalancer/balance.d.ts +0 -1
  53. package/dist/videoSendingBalancer/index.d.ts +0 -1
  54. package/dist/videoSendingBalancer/processSender.d.ts +0 -1
  55. package/package.json +19 -17
  56. package/dist/SipConnector-Dg0Vq0lq.cjs +0 -1
@@ -0,0 +1 @@
1
+ "use strict";var Pt=Object.defineProperty;var Ot=(r,e,t)=>e in r?Pt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var i=(r,e,t)=>Ot(r,typeof e!="symbol"?e+"":e,t);const C=require("@krivega/cancelable-promise"),Me=require("events-constructor"),ve=require("repeated-calls"),B=require("debug"),ft="Connection Error",We="Request Timeout",Dt="SIP Failure Code",Mt="Internal Error",vt="Busy",V="Rejected",bt="Redirected",yt="Unavailable",qe="Not Found",wt="Address Incomplete",Ut="Incompatible SDP",Lt="Missing SDP",Ht="Authentication Error",ke="Terminated",Wt="WebRTC Error",Fe="Canceled",qt="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:ft,DIALOG_ERROR:Bt,EXPIRES:kt,INCOMPATIBLE_SDP:Ut,INTERNAL_ERROR:Mt,MISSING_SDP:Lt,NOT_FOUND:qe,NO_ACK:Ft,NO_ANSWER:qt,REDIRECTED:bt,REJECTED:V,REQUEST_TIMEOUT:We,RTP_TIMEOUT:Yt,SIP_FAILURE_CODE:Dt,UNAVAILABLE:yt,USER_DENIED_MEDIA_ACCESS:Vt,WEBRTC_ERROR:Wt},Symbol.toStringTag,{value:"Module"})),Y="incomingCall",x="declinedIncomingCall",G="failedIncomingCall",$="terminatedIncomingCall",q="connecting",m="connected",u="disconnected",M="newRTCSession",p="registered",X="unregistered",P="registrationFailed",Ve="newMessage",J="sipEvent",z="availableSecondRemoteStream",Q="notAvailableSecondRemoteStream",j="mustStopPresentation",v="shareState",K="enterRoom",Z="useLicense",ee="peerconnection:confirmed",te="peerconnection:ontrack",b="channels",ne="channels:notify",se="ended:fromserver",ie="main-cam-control",re="admin-stop-main-cam",oe="admin-start-main-cam",ae="admin-stop-mic",ce="admin-start-mic",y="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Ee="participant:removed-from-list-moderators",le="participant:move-request-to-stream",he="participant:move-request-to-spectators",de="participation:accepting-word-request",Te="participation:cancelling-word-request",ue="webcast:started",Se="webcast:stopped",Ce="account:changed",Ne="account:deleted",ge="conference:participant-token-issued",O="ended",Ye="sending",xe="reinvite",Ge="replaces",$e="refer",Xe="progress",Je="accepted",w="confirmed",U="peerconnection",A="failed",ze="muted",Qe="unmuted",Ae="newDTMF",Re="newInfo",je="hold",Ke="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",_t="presentation:end",Ie="presentation:ended",L="presentation:failed",Et="SPECTATOR",lt=1e6,Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Je,ACCOUNT_CHANGED:Ce,ACCOUNT_DELETED:Ne,ADMIN_FORCE_SYNC_MEDIA_STATE:y,ADMIN_START_MAIN_CAM:oe,ADMIN_START_MIC:ce,ADMIN_STOP_MAIN_CAM:re,ADMIN_STOP_MIC:ae,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:z,CHANNELS:b,CHANNELS_NOTIFY:ne,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:ge,CONFIRMED:w,CONNECTED:m,CONNECTING:q,DECLINED_INCOMING_CALL:x,DISCONNECTED:u,ENDED:O,ENDED_FROM_SERVER:se,ENTER_ROOM:K,FAILED:A,FAILED_INCOMING_CALL:G,GET_USER_MEDIA_FAILED:nt,HOLD:je,ICE_CANDIDATE:tt,INCOMING_CALL:Y,MAIN_CAM_CONTROL:ie,MUST_STOP_PRESENTATION_EVENT:j,MUTED:ze,NEW_DTMF:Ae,NEW_INFO:Re,NEW_MESSAGE:Ve,NEW_RTC_SESSION:M,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Q,ONE_MEGABIT_IN_BITS:lt,PARTICIPANT_ADDED_TO_LIST_MODERATORS:_e,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:he,PARTICIPANT_MOVE_REQUEST_TO_STREAM:le,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Ee,PARTICIPATION_ACCEPTING_WORD_REQUEST:de,PARTICIPATION_CANCELLING_WORD_REQUEST:Te,PEER_CONNECTION:U,PEER_CONNECTION_CONFIRMED:ee,PEER_CONNECTION_CREATE_ANSWER_FAILED:it,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:te,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:rt,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:ot,PRESENTATION_END:_t,PRESENTATION_ENDED:Ie,PRESENTATION_FAILED:L,PRESENTATION_START:at,PRESENTATION_STARTED:ct,PROGRESS:Xe,REFER:$e,REGISTERED:p,REGISTRATION_FAILED:P,REINVITE:xe,REPLACES:Ge,SDP:et,SENDING:Ye,SHARE_STATE:v,SIP_EVENT:J,SPECTATOR:Et,TERMINATED_INCOMING_CALL:$,UNHOLD:Ke,UNMUTED:Qe,UNREGISTERED:X,UPDATE:Ze,USE_LICENSE:Z,WEBCAST_STARTED:ue,WEBCAST_STOPPED:Se},Symbol.toStringTag,{value:"Module"})),ht=[Y,x,$,G,de,Te,le,ne,ge,Ce,Ne,ue,Se,_e,Ee],me=[q,m,u,M,p,X,P,Ve,J],dt=[z,Q,j,v,K,Z,ee,te,b,se,ie,oe,re,ae,ce,y,he],pe=[O,q,Ye,xe,Ge,$e,Xe,Je,w,U,A,ze,Qe,Ae,Re,je,Ke,Ze,et,tt,nt,st,it,rt,ot,at,ct,_t,Ie,L],Pe=[...me,...ht],Oe=[...pe,...dt],$t=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:Oe,SESSION_JSSIP_EVENT_NAMES:pe,SESSION_SYNTHETICS_EVENT_NAMES:dt,UA_EVENT_NAMES:Pe,UA_JSSIP_EVENT_NAMES:me,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",f="application/vinteo.webrtc.sharedesktop",Qt="application/vinteo.webrtc.roomname",jt="application/vinteo.webrtc.channels",Kt="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",_n="X-Vinteo-Media-Type",En="X-Vinteo-MainCam-State",ln="X-Vinteo-Mic-State",hn="application/vinteo.webrtc.partstate",dn="X-WEBRTC-PARTSTATE",Tn="application/vinteo.webrtc.notify",un="X-VINTEO-NOTIFY",I="x-webrtc-share-state",Sn=`${I}: LETMESTARTPRESENTATION`,Cn=`${I}: STOPPRESENTATION`,Tt="YOUCANRECEIVECONTENT",ut="CONTENTEND",St="YOUMUSTSTOPSENDCONTENT",Nn=`${I}: ${St}`,gn=`${I}: ${Tt}`,An=`${I}: ${ut}`,Rn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",In=`${Rn}: LETMESTARTMAINCAM`,fe="sip-connector",D=B(fe),mn=()=>{B.enable(fe)},pn=()=>{B.enable(`-${fe}`)},Pn=(r,e)=>{r.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},k=(r,{videoMode:e,audioMode:t,contentHint:n}={})=>{if(!r||e==="recvonly"&&t==="recvonly")return;const s=t==="recvonly"?[]:r.getAudioTracks(),o=e==="recvonly"?[]:r.getVideoTracks(),a=[...s,...o],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Pn(c,n),c};var R=(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))(R||{}),H=(r=>(r.ADMIN_STOP_MIC="ADMINSTOPMIC",r.ADMIN_START_MIC="ADMINSTARTMIC",r))(H||{}),W=(r=>(r.ADMIN_SYNC_FORCED="1",r.ADMIN_SYNC_NOT_FORCED="0",r))(W||{}),Ct=(r=>(r.AUDIO="AUDIO",r.VIDEO="VIDEO",r.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",r))(Ct||{});function On(r){return e=>`sip:${e}@${r}`}const fn=(r,e)=>()=>Math.floor(Math.random()*(e-r))+r,Le=r=>r.trim().replaceAll(" ","_"),Dn=fn(1e5,99999999),Mn=r=>r.some(t=>{const{kind:n}=t;return n==="video"}),vn="Error decline with 603",bn=1006,yn=r=>typeof r=="object"&&r!==null&&"code"in r&&r.code===bn,wn=r=>r.message===vn,Un=(r,e)=>r.find(t=>t.track&&e.getTracks().includes(t.track)),Nt=1,gt=r=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==r,Ln=gt(Nt),Hn=(r,e)=>{const t=r===void 0?void 0:Math.max(r,Nt);if(t!==void 0&&Ln(t,e))return t},Wn=gt(),qn=(r,e)=>{if(Wn(r,e))return r},At=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=Hn(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}},kn=async(r,e,t)=>{const n=Un(r,e);if(n)return At(n,{maxBitrate:t})},Fn=486,Bn=487,F="local",He="remote",Vn=3,Yn=1,xn=(r=new Error)=>{const{originator:e,cause:t}=r;return C.isCanceledError(r)?!0:typeof t=="string"?t===We||t===V||e===F&&(t===Fe||t===ke):!1},g="SipConnector",Gn="channels",$n="WebcastStarted",Xn="WebcastStopped",Jn="accountChanged",zn="accountDeleted",Qn="addedToListModerators",jn="removedFromListModerators",Kn="ParticipationRequestAccepted",Zn="ParticipationRequestRejected",es="ParticipantMovedToWebcast",ts="ConferenceParticipantTokenIssued";class ns{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,"_cancelableSendPresentationWithRepeatedCalls");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(q,void 0);try{await this.unregister()}catch(e){D("tryRegister",e)}return this.register()});i(this,"declineToIncomingCall",async({statusCode:e=Bn}={})=>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(x,o),t(s.terminate({status_code:e}))}));i(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Fn}));i(this,"removeIncomingSession",()=>{delete this.incomingSession});i(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=Vn}={})=>{let n=!0;const s=async()=>(n=!1,this._cancelableConnect.request(e)),o=a=>{var l;const c=!!((l=this.ua)!=null&&l.isConnected()),_=!n&&c&&this.hasEqualConnectionConfiguration(e),E=!!a&&!yn(a);return _||E};return this._cancelableConnectWithRepeatedCalls=ve.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(A,s=>{this.removeIncomingSession(),s.originator===F?this._uaEvents.trigger($,n):this._uaEvents.trigger(G,n)}),this._uaEvents.trigger(Y,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,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:E,userAgent:l,displayName:d="",register:h=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!s)throw new Error("sipWebSocketServerURL is required");if(h&&!e)throw new Error("user is required for authorized connection");if(h&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:d,register:h,user:e,password:t};const{configuration:S,helpers:N}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:s,password:t,displayName:d,register:h,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:E,userAgent:l});this.getSipServerUrl=N.getSipServerUrl,this.socket=N.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!h,this.ua=this._createUa(S),this._uaEvents.eachTriggers((It,mt)=>{const De=me.find(pt=>pt===mt);De&&this.ua&&this.ua.on(De,It)});const Rt=[...Xt(o),...T];return this.ua.registrator().setExtraHeaders(Rt),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(p,s),this.on(P,o)):this.on(m,s),this.on(u,o)},c=()=>{this.off(p,s),this.off(P,o),this.off(m,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:l=!0})=>new Promise((d,h)=>{const{ua:T}=this;if(!T){h(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:s}).then(d).catch(S=>{h(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:l}})}));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:l}=this;if(!l){E(new Error("No session established"));return}this._sessionEvents.eachTriggers((h,T)=>{const S=pe.find(N=>N===T);S&&l.on(S,h)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=l.remote_identity.uri.user,this._handleCall({ontrack:t}).then(_).catch(h=>{E(h)});const d=k(e,{videoMode:o,audioMode:a});l.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,l),this.onSession(w,d)},o=()=>{this.offSession(U,l),this.offSession(w,d)},a=()=>{this.onSession(A,_),this.onSession(O,_)},c=()=>{this.offSession(A,_),this.offSession(O,_)},_=h=>{o(),c(),n(h)};let E;const l=({peerconnection:h})=>{E=h,E.ontrack=T=>{this._sessionEvents.trigger(te,E),e&&e(T)}},d=()=>{E&&this._sessionEvents.trigger(ee,E),o(),c(),t(E)};s(),a()}));i(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),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(Ae,({originator:o})=>{o===F&&t()}),s.sendDTMF(e,{duration:120,interToneGap:600})}));i(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){D("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});i(this,"_handleShareState",e=>{switch(e){case Tt:{this._sessionEvents.trigger(z,void 0);break}case ut:{this._sessionEvents.trigger(Q,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 Gn:{const t=e;this._triggerChannelsNotify(t);break}case $n:{const t=e;this._triggerWebcastStartedNotify(t);break}case Xn:{const t=e;this._triggerWebcastStoppedNotify(t);break}case Qn:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case jn:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case Kn:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case Zn:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case es:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case Jn:{this._triggerAccountChangedNotify();break}case zn:{this._triggerAccountDeletedNotify();break}case ts:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:D("unknown cmd",e.cmd)}});i(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Ee,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(Se,n)});i(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ce,void 0)});i(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(Ne,void 0)});i(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const s={conference:e,participant:t,jwt:n};this._uaEvents.trigger(ge,s)});i(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,s={inputChannels:t,outputChannels:n};this._uaEvents.trigger(ne,s)});i(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(de,t)});i(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Te,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(K,{room:t,participantName:n})});i(this,"_triggerShareState",e=>{const t=e.getHeader(I);this._sessionEvents.trigger(v,t)});i(this,"_maybeTriggerParticipantMoveRequestToSpectators",e=>{e.getHeader(dn)===Et&&this._sessionEvents.trigger(he,void 0)});i(this,"_triggerMainCamControl",e=>{const t=e.getHeader(rn),n=e.getHeader(Ue),s=n===W.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(oe,{isSyncForced:s});return}if(t===R.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(re,{isSyncForced:s});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(y,{isSyncForced:s});const o=e.getHeader(an);this._sessionEvents.trigger(ie,{mainCam:t,resolutionMainCam:o})});i(this,"_triggerMicControl",e=>{const t=e.getHeader(on),s=e.getHeader(Ue)===W.ADMIN_SYNC_FORCED;t===H.ADMIN_START_MIC?this._sessionEvents.trigger(ce,{isSyncForced:s}):t===H.ADMIN_STOP_MIC&&this._sessionEvents.trigger(ae,{isSyncForced:s})});i(this,"_triggerUseLicense",e=>{const t=e.getHeader(nn);this._sessionEvents.trigger(Z,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 f:{this._triggerShareState(n);break}case be:{this._triggerMainCamControl(n);break}case en:{this._triggerMicControl(n);break}case tn:{this._triggerUseLicense(n);break}case hn:{this._maybeTriggerParticipantMoveRequestToSpectators(n);break}}});i(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});i(this,"_maybeHandleNotify",e=>{const t=e.getHeader(un);if(t){const n=JSON.parse(t);this._handleNotify(n)}});i(this,"_handleEnded",e=>{const{originator:t}=e;t===He&&this._sessionEvents.trigger(se,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new Me(Oe),this._uaEvents=new Me(Pe),this._cancelableConnect=new C.CancelableRequest(this._connect,{moduleName:g,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new C.CancelableRequest(this._initUa,{moduleName:g}),this._cancelableDisconnect=new C.CancelableRequest(this._disconnect,{moduleName:g}),this._cancelableSet=new C.CancelableRequest(this._set,{moduleName:g}),this._cancelableCall=new C.CancelableRequest(this._call,{moduleName:g}),this._cancelableAnswer=new C.CancelableRequest(this._answer,{moduleName:g}),this._cancelableSendDTMF=new C.CancelableRequest(this._sendDTMF,{moduleName:g}),this.onSession(v,this._handleShareState),this.onSession(Re,this._handleNewInfo),this.on(J,this._handleSipEvent),this.onSession(A,this._handleEnded),this.onSession(O,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(p,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(X,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}){return new Promise((o,a)=>{const{configuration:c}=this.createUaConfiguration({sipWebSocketServerURL:s,displayName:t,userAgent:e,sipServerUrl:n}),_=this._createUa(c),E=()=>{const d=new Error("Telephony is not available");a(d)};_.once(u,E);const l=()=>{_.removeAllListeners(),_.once(u,o),_.stop()};_.once(m,l),_.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(wn(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({session:e,stream:t,presentationOptions:n,options:s={callLimit:Yn}}){const o=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=ve.repeatedCallsAsync({targetFunction:o,isComplete:a,isRejectAsValid:!0,...s}),this._cancelableSendPresentationWithRepeatedCalls.then(c=>c)}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.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,sessionTimers:c=!1,registerExpires:_=60*5,connectionRecoveryMinInterval:E=2,connectionRecoveryMaxInterval:l=6,userAgent:d}){if(a&&!t)throw new Error("password is required for authorized connection");const h=a&&e?e.trim():`${Dn()}`,T=On(o),S=T(h),N=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:S,display_name:Le(s),user_agent:d,sdp_semantics:"unified-plan",sockets:[N],session_timers:c,register_expires:_,connection_recovery_min_interval:E,connection_recovery_max_interval:l},helpers:{socket:N,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=lt,degradationPreference:s="maintain-resolution",isNeedReinvite:o=!0,isP2P:a=!1,contentHint:c="detail"}){const _=k(t,{contentHint:c});this._streamPresentationCurrent=_;const E=a?[gn]:[Sn],l=e.sendInfo(f,void 0,{extraHeaders:E}).then(async()=>e.startPresentation(_,o,s)).then(async()=>{const{connection:d}=this;if(!d||n===void 0)return;const h=d.getSenders();await kn(h,t,n)}).then(()=>t).catch(d=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(L,d),d});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o,contentHint:a}={},c){const _=this.establishedSession;if(!_)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(_),this._sendPresentationWithDuplicatedCalls({session:_,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:s,degradationPreference:o,contentHint:a},options:c})}async sendMustStopPresentation(e){await e.sendInfo(f,void 0,{extraHeaders:[Nn]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const s=e?[An]:[Cn],o=this.establishedSession;return o&&t&&(n=n.then(async()=>o.sendInfo(f,void 0,{extraHeaders:s})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(L,a),a})),!o&&t&&this._sessionEvents.trigger(Ie,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,degradationPreference:s,contentHint:o}={}){const a=this.establishedSession;if(!a)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(a,e,{isP2P:t,maxBitrate:n,degradationPreference:s,contentHint:o,isNeedReinvite:!1})}_removeStreamPresentationCurrent(){delete this._streamPresentationCurrent}_resetPresentation(){this._removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}_cancelRequestsAndResetPresentation(){this._cancelSendPresentationWithRepeatedCalls(),this._resetPresentation()}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 Mn(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()}_cancelSendPresentationWithRepeatedCalls(){var e;(e=this._cancelableSendPresentationWithRepeatedCalls)==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(jt,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=`${En}: ${Number(e)}`,a=`${ln}: ${Number(t)}`,c=[s,o,a];return this.session.sendInfo(Kt,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${_n}: ${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=R;exports.EEventsMic=H;exports.EEventsSyncMediaState=W;exports.EUseLicense=Ct;exports.NOT_FOUND=qe;exports.REJECTED=V;exports.SESSION_EVENT_NAMES=Oe;exports.SipConnector=ns;exports.UA_EVENT_NAMES=Pe;exports.causes=xt;exports.constants=Gt;exports.disableDebug=pn;exports.enableDebug=mn;exports.eventNames=$t;exports.hasCanceledCallError=xn;exports.logger=D;exports.setEncodingsToSender=At;