sip-connector 9.2.0 → 10.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.
- package/dist/SipConnector-93CcnqPF.cjs +1 -0
- package/dist/{SipConnector-xflR79mb.js → SipConnector-P-kMtUcq.js} +457 -414
- package/dist/SipConnector.d.ts +9 -9
- package/dist/__fixtures__/RTCPeerConnectionMock.d.ts +2 -1
- package/dist/__fixtures__/RTCRtpSenderMock.d.ts +4 -1
- package/dist/doMock.cjs +1 -1
- package/dist/doMock.js +87 -51
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +178 -175
- package/dist/setParametersToSender/configureDegradationPreference.d.ts +3 -0
- package/dist/setParametersToSender/configureEmptyEncodings.d.ts +2 -0
- package/dist/setParametersToSender/configureEncodings.d.ts +10 -0
- package/dist/setParametersToSender/configureMaxBitrate.d.ts +2 -0
- package/dist/setParametersToSender/configureScaleResolutionDownBy.d.ts +2 -0
- package/dist/setParametersToSender/hasChangedRTCRtpSendParameters.d.ts +2 -0
- package/dist/setParametersToSender/index.d.ts +1 -0
- package/dist/setParametersToSender/resolveHasNeedToUpdateItemEncoding.d.ts +2 -0
- package/dist/setParametersToSender/setParametersToSender.d.ts +7 -0
- package/dist/tools/answerIncomingCall.d.ts +2 -3
- package/dist/tools/callToServer.d.ts +2 -3
- package/dist/tools/resolveHandleAddedSender.d.ts +3 -0
- package/dist/tools/resolveStartPresentation.d.ts +3 -3
- package/dist/tools/resolveUpdatePresentation.d.ts +3 -3
- package/dist/types.d.ts +2 -1
- package/package.json +13 -13
- package/dist/SipConnector-lgvJyyG7.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Pt=Object.defineProperty;var Ot=(s,e,t)=>e in s?Pt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var r=(s,e,t)=>Ot(s,typeof e!="symbol"?e+"":e,t);const N=require("@krivega/cancelable-promise"),ve=require("events-constructor"),ye=require("repeated-calls"),V=require("debug"),Dt="Connection Error",qe="Request Timeout",pt="SIP Failure Code",Mt="Internal Error",vt="Busy",x="Rejected",yt="Redirected",bt="Unavailable",ke="Not Found",wt="Address Incomplete",Ut="Incompatible SDP",Lt="Missing SDP",Ht="Authentication Error",Be="Terminated",Wt="WebRTC Error",Fe="Canceled",qt="No Answer",kt="Expires",Bt="No ACK",Ft="Dialog Error",Vt="User Denied Media Access",Ve="Bad Media Description",xt="RTP Timeout",Yt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:wt,AUTHENTICATION_ERROR:Ht,BAD_MEDIA_DESCRIPTION:Ve,BUSY:vt,BYE:Be,CANCELED:Fe,CONNECTION_ERROR:Dt,DIALOG_ERROR:Ft,EXPIRES:kt,INCOMPATIBLE_SDP:Ut,INTERNAL_ERROR:Mt,MISSING_SDP:Lt,NOT_FOUND:ke,NO_ACK:Bt,NO_ANSWER:qt,REDIRECTED:yt,REJECTED:x,REQUEST_TIMEOUT:qe,RTP_TIMEOUT:xt,SIP_FAILURE_CODE:pt,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Vt,WEBRTC_ERROR:Wt},Symbol.toStringTag,{value:"Module"})),Y="incomingCall",G="declinedIncomingCall",$="failedIncomingCall",X="terminatedIncomingCall",k="connecting",f="connected",S="disconnected",v="newRTCSession",m="registered",J="unregistered",P="registrationFailed",xe="newMessage",z="sipEvent",Q="availableSecondRemoteStream",j="notAvailableSecondRemoteStream",K="mustStopPresentation",y="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",w="admin-force-sync-media-state",_e="participant:added-to-list-moderators",le="participant:removed-from-list-moderators",de="participant:move-request-to-stream",he="participant:move-request-to-spectators",ue="participation:accepting-word-request",Te="participation:cancelling-word-request",Se="webcast:started",Ce="webcast:stopped",Ne="account:changed",ge="account:deleted",Ae="conference:participant-token-issued",O="ended",Ye="sending",Ge="reinvite",$e="replaces",Xe="refer",Je="progress",ze="accepted",U="confirmed",L="peerconnection",A="failed",Qe="muted",je="unmuted",Re="newDTMF",Ie="newInfo",Ke="hold",Ze="unhold",et="update",tt="sdp",nt="icecandidate",st="getusermediafailed",it="peerconnection:createofferfailed",rt="peerconnection:createanswerfailed",ot="peerconnection:setlocaldescriptionfailed",at="peerconnection:setremotedescriptionfailed",ct="presentation:start",Et="presentation:started",_t="presentation:end",fe="presentation:ended",H="presentation:failed",lt="SPECTATOR",dt=1e6,Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:ze,ACCOUNT_CHANGED:Ne,ACCOUNT_DELETED:ge,ADMIN_FORCE_SYNC_MEDIA_STATE:w,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:U,CONNECTED:f,CONNECTING:k,DECLINED_INCOMING_CALL:G,DISCONNECTED:S,ENDED:O,ENDED_FROM_SERVER:ie,ENTER_ROOM:Z,FAILED:A,FAILED_INCOMING_CALL:$,GET_USER_MEDIA_FAILED:st,HOLD:Ke,ICE_CANDIDATE:nt,INCOMING_CALL:Y,MAIN_CAM_CONTROL:re,MUST_STOP_PRESENTATION_EVENT:K,MUTED:Qe,NEW_DTMF:Re,NEW_INFO:Ie,NEW_MESSAGE:xe,NEW_RTC_SESSION:v,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:j,ONE_MEGABIT_IN_BITS:dt,PARTICIPANT_ADDED_TO_LIST_MODERATORS:_e,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:he,PARTICIPANT_MOVE_REQUEST_TO_STREAM:de,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:le,PARTICIPATION_ACCEPTING_WORD_REQUEST:ue,PARTICIPATION_CANCELLING_WORD_REQUEST:Te,PEER_CONNECTION:L,PEER_CONNECTION_CONFIRMED:te,PEER_CONNECTION_CREATE_ANSWER_FAILED:rt,PEER_CONNECTION_CREATE_OFFER_FAILED:it,PEER_CONNECTION_ONTRACK:ne,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ot,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:at,PRESENTATION_END:_t,PRESENTATION_ENDED:fe,PRESENTATION_FAILED:H,PRESENTATION_START:ct,PRESENTATION_STARTED:Et,PROGRESS:Je,REFER:Xe,REGISTERED:m,REGISTRATION_FAILED:P,REINVITE:Ge,REPLACES:$e,SDP:tt,SENDING:Ye,SHARE_STATE:y,SIP_EVENT:z,SPECTATOR:lt,TERMINATED_INCOMING_CALL:X,UNHOLD:Ze,UNMUTED:je,UNREGISTERED:J,UPDATE:et,USE_LICENSE:ee,WEBCAST_STARTED:Se,WEBCAST_STOPPED:Ce},Symbol.toStringTag,{value:"Module"})),ht=[Y,G,X,$,ue,Te,de,se,Ae,Ne,ge,Se,Ce,_e,le],me=[k,f,S,v,m,J,P,xe,z],ut=[Q,j,K,y,Z,ee,te,ne,b,ie,re,ae,oe,ce,Ee,w,he],Pe=[O,k,Ye,Ge,$e,Xe,Je,ze,U,L,A,Qe,je,Re,Ie,Ke,Ze,et,tt,nt,st,it,rt,ot,at,ct,Et,_t,fe,H],Oe=[...me,...ht],De=[...Pe,...ut],$t=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:De,SESSION_JSSIP_EVENT_NAMES:Pe,SESSION_SYNTHETICS_EVENT_NAMES:ut,UA_EVENT_NAMES:Oe,UA_JSSIP_EVENT_NAMES:me,UA_SYNTHETICS_EVENT_NAMES:ht},Symbol.toStringTag,{value:"Module"})),Xt=s=>{const e=[];return s&&e.push(`X-Vinteo-Remote: ${s}`),e},Jt="content-type",zt="x-webrtc-enter-room",D="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",we="X-WEBRTC-INPUT-CHANNELS",Ue="X-WEBRTC-OUTPUT-CHANNELS",rn="X-WEBRTC-MAINCAM",on="X-WEBRTC-MIC",Le="X-WEBRTC-SYNC",an="X-WEBRTC-MAINCAM-RESOLUTION",cn="X-WEBRTC-MEDIA-STATE",En="X-Vinteo-Media-Type",_n="X-Vinteo-MainCam-State",ln="X-Vinteo-Mic-State",dn="application/vinteo.webrtc.partstate",hn="X-WEBRTC-PARTSTATE",un="application/vinteo.webrtc.notify",Tn="X-VINTEO-NOTIFY",I="x-webrtc-share-state",Sn=`${I}: LETMESTARTPRESENTATION`,Cn=`${I}: STOPPRESENTATION`,Tt="YOUCANRECEIVECONTENT",St="CONTENTEND",Ct="YOUMUSTSTOPSENDCONTENT",Nn=`${I}: ${Ct}`,gn=`${I}: ${Tt}`,An=`${I}: ${St}`,Rn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",In=`${Rn}: LETMESTARTMAINCAM`,pe="sip-connector",M=V(pe),fn=()=>{V.enable(pe)},mn=()=>{V.enable(`-${pe}`)},Pn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(s,{videoMode:e,audioMode:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),o=e==="recvonly"?[]:s.getVideoTracks(),a=[...i,...o],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Pn(c,n),c};var R=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(R||{}),W=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(W||{}),q=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(q||{}),Nt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Nt||{});function On(s){return e=>`sip:${e}@${s}`}const Dn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,He=s=>s.trim().replaceAll(" ","_"),pn=Dn(1e5,99999999),Mn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),vn="Error decline with 603",yn=1006,bn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===yn,wn=s=>s.message===vn,Un=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Ln=(s,e)=>({...s,degradationPreference:e.degradationPreference}),Hn=(s,e)=>{let{encodings:t}=s;t===void 0&&(t=[]);for(let n=t.length;n<e;n+=1)t.push({});return{...s,encodings:t}},gt=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,Wn=gt(),qn=(s,e)=>{if(Wn(s,e))return s},kn=(s,e)=>{const t=s.maxBitrate,n=qn(e,t);return n!==void 0?{...s,maxBitrate:n}:s},At=1,Bn=gt(At),Fn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,At);if(t!==void 0&&Bn(t,e))return t},Vn=(s,e)=>{const t=s.scaleResolutionDownBy,n=Fn(e,t);return n!==void 0?{...s,scaleResolutionDownBy:n}:s},xn=(s,e)=>{var o;const t=((o=e.encodings)==null?void 0:o.length)??0,n=Hn(s,t),i=n.encodings.map((a,c)=>{const E=((e==null?void 0:e.encodings)??[])[c],l=E==null?void 0:E.maxBitrate,_=E==null?void 0:E.scaleResolutionDownBy;let d=kn(a,l);return d=Vn(d,_),d});return{...n,encodings:i}},Yn=(s,e)=>{var t,n,i,o,a,c,E,l;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let _=0;_<(((i=s.codecs)==null?void 0:i.length)??0);_++)if(JSON.stringify(s.codecs[_])!==JSON.stringify(e.codecs[_]))return!0;if(((o=s.headerExtensions)==null?void 0:o.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let _=0;_<(((c=s.headerExtensions)==null?void 0:c.length)??0);_++)if(JSON.stringify(s.headerExtensions[_])!==JSON.stringify(e.headerExtensions[_]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((l=e.encodings)==null?void 0:l.length))return!0;for(let _=0;_<(s.encodings.length??0);_++)if(JSON.stringify(s.encodings[_])!==JSON.stringify(e.encodings[_]))return!0;return s.rtcp.cname!==e.rtcp.cname||s.rtcp.reducedSize!==e.rtcp.reducedSize||s.degradationPreference!==e.degradationPreference},Rt=async(s,e)=>{const t=s.getParameters();let n=xn(t,e);n=Ln(n,e);const i=Yn(t,n);return i&&await s.setParameters(n),{parameters:n,isChanged:i}},It=async(s,e,t)=>{const{isChanged:n,parameters:i}=await Rt(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}},Gn=async(s,e,t)=>{const n=Un(s,e);if(n)return It(n,{maxBitrate:t})},$n=486,Xn=487,F="local",We="remote",Jn=3,zn=1,Qn=(s=new Error)=>{const{originator:e,cause:t}=s;return N.isCanceledError(s)?!0:typeof t=="string"?t===qe||t===x||e===F&&(t===Fe||t===Be):!1},g="SipConnector",jn="channels",Kn="WebcastStarted",Zn="WebcastStopped",es="accountChanged",ts="accountDeleted",ns="addedToListModerators",ss="removedFromListModerators",is="ParticipationRequestAccepted",rs="ParticipationRequestRejected",os="ParticipantMovedToWebcast",as="ConferenceParticipantTokenIssued";class cs{constructor({JsSIP:e}){r(this,"_isRegisterConfig",!1);r(this,"_connectionConfiguration",{});r(this,"_remoteStreams",{});r(this,"JsSIP");r(this,"_sessionEvents");r(this,"_uaEvents");r(this,"_cancelableConnect");r(this,"_cancelableConnectWithRepeatedCalls");r(this,"_cancelableSendPresentationWithRepeatedCalls");r(this,"_cancelableInitUa");r(this,"_cancelableDisconnect");r(this,"_cancelableSet");r(this,"_cancelableCall");r(this,"_cancelableAnswer");r(this,"_cancelableSendDTMF");r(this,"getSipServerUrl",e=>e);r(this,"promisePendingStartPresentation");r(this,"promisePendingStopPresentation");r(this,"ua");r(this,"session");r(this,"incomingSession");r(this,"_streamPresentationCurrent");r(this,"socket");r(this,"connect",async(e,t)=>(this._cancelRequests(),this._connectWithDuplicatedCalls(e,t)));r(this,"initUa",async e=>this._cancelableInitUa.request(e));r(this,"set",async e=>this._cancelableSet.request(e));r(this,"call",async e=>this._cancelableCall.request(e));r(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));r(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));r(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));r(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));r(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(k,void 0);try{await this.unregister()}catch(e){M("tryRegister",e)}return this.register()});r(this,"declineToIncomingCall",async({statusCode:e=Xn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingSession"));return}const i=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(G,o),t(i.terminate({status_code:e}))}));r(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:$n}));r(this,"removeIncomingSession",()=>{delete this.incomingSession});r(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=Jn}={})=>{const n=async()=>this._cancelableConnect.request(e),i=o=>{var l;const c=!!((l=this.ua)!=null&&l.isConnected())&&this.hasEqualConnectionConfiguration(e),E=!!o&&!bn(o);return c||E};return this._cancelableConnectWithRepeatedCalls=ye.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1,onAfterCancel:()=>{this._cancelableConnect.cancelRequest()}}),this._cancelableConnectWithRepeatedCalls.then(o=>{if(o instanceof this.JsSIP.UA)return o;throw o})});r(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===We){this.incomingSession=t;const n=this.remoteCallerData;t.on(A,i=>{this.removeIncomingSession(),i.originator===F?this._uaEvents.trigger(X,n):this._uaEvents.trigger($,n)}),this._uaEvents.trigger(Y,n)}});r(this,"_connect",async e=>this.initUa(e).then(async()=>this._start()));r(this,"_initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:o,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:l,userAgent:_,displayName:d="",register:h=!1,extraHeaders:u=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)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:C,helpers:T}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:d,register:h,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:l,userAgent:_});return this.getSipServerUrl=T.getSipServerUrl,this.socket=T.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!h,this.ua=this._createUa({...C,remoteAddress:o,extraHeaders:u}),this._uaEvents.eachTriggers((B,ft)=>{const Me=me.find(mt=>mt===ft);Me&&this.ua&&this.ua.on(Me,B)}),this.ua});r(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e?Xt(e):[],...t];return a.length>0&&i.registrator().setExtraHeaders(a),i});r(this,"_start",async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const i=()=>{c(),e(n)},o=E=>{c(),t(E)},a=()=>{this.isRegisterConfig?(this.on(m,i),this.on(P,o)):this.on(f,i),this.on(S,o)},c=()=>{this.off(m,i),this.off(P,o),this.off(f,i),this.off(S,o)};a(),this.on(v,this.handleNewRTCSession),n.start()}));r(this,"_set",async({displayName:e,password:t})=>new Promise((n,i)=>{const{ua:o}=this;if(!o){i(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",He(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const E=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(E)}).catch(l=>{i(l)}):E?n(E):i(new Error("nothing changed"))}));r(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());r(this,"_disconnect",async()=>{this.off(v,this.handleNewRTCSession);const e=new Promise(t=>{this.once(S,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(S,void 0)):this._uaEvents.trigger(S,void 0),e});r(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:o,videoMode:a,audioMode:c,onAddedSender:E,contentHint:l,offerToReceiveAudio:_=!0,offerToReceiveVideo:d=!0})=>new Promise((h,u)=>{const{ua:C}=this;if(!C){u(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(h).catch(T=>{u(T)}),this.session=C.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{videoMode:a,audioMode:c,contentHint:l}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,onAddedSender:E,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:_,offerToReceiveVideo:d}})}));r(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,videoMode:o,audioMode:a,onAddedSender:c,contentHint:E})=>new Promise((l,_)=>{if(!this.isAvailableIncomingCall){_(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:d}=this;if(!d){_(new Error("No session established"));return}this._sessionEvents.eachTriggers((u,C)=>{const T=Pe.find(B=>B===C);T&&d.on(T,u)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(l).catch(u=>{_(u)});const h=p(e,{videoMode:o,audioMode:a,contentHint:E});d.answer({extraHeaders:n,videoMode:o,audioMode:a,onAddedSender:c,mediaStream:h,pcConfig:{iceServers:i}})}));r(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(L,_),this.onSession(U,d)},o=()=>{this.offSession(L,_),this.offSession(U,d)},a=()=>{this.onSession(A,E),this.onSession(O,E)},c=()=>{this.offSession(A,E),this.offSession(O,E)},E=h=>{o(),c(),n(h)};let l;const _=({peerconnection:h})=>{l=h,l.ontrack=u=>{this._sessionEvents.trigger(ne,l),e&&e(u)}},d=()=>{l&&this._sessionEvents.trigger(te,l),o(),c(),t(l)};i(),a()}));r(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});r(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{session:i}=this;if(!i){n(new Error("No session established"));return}this.onceSession(Re,({originator:o})=>{o===F&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));r(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){M("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});r(this,"_handleShareState",e=>{switch(e){case Tt:{this._sessionEvents.trigger(Q,void 0);break}case St:{this._sessionEvents.trigger(j,void 0);break}case Ct:{this._sessionEvents.trigger(K,void 0);break}}});r(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(we),n=e.getHeader(Ue);if(t&&n){const i={inputChannels:t,outputChannels:n};this._sessionEvents.trigger(b,i)}});r(this,"_handleNotify",e=>{switch(e.cmd){case jn:{const t=e;this._triggerChannelsNotify(t);break}case Kn:{const t=e;this._triggerWebcastStartedNotify(t);break}case Zn:{const t=e;this._triggerWebcastStoppedNotify(t);break}case ns:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case ss:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case is:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case rs:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case os:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case es:{this._triggerAccountChangedNotify();break}case ts:{this._triggerAccountDeletedNotify();break}case as:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:M("unknown cmd",e.cmd)}});r(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(le,t)});r(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(_e,t)});r(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Se,n)});r(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ce,n)});r(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ne,void 0)});r(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(ge,void 0)});r(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Ae,i)});r(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this._uaEvents.trigger(se,i)});r(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});r(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Te,t)});r(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(de,t)});r(this,"_triggerEnterRoom",e=>{const t=e.getHeader(zt),n=e.getHeader(sn);this._sessionEvents.trigger(Z,{room:t,participantName:n})});r(this,"_triggerShareState",e=>{const t=e.getHeader(I);this._sessionEvents.trigger(y,t)});r(this,"_maybeTriggerParticipantMoveRequestToSpectators",e=>{e.getHeader(hn)===lt&&this._sessionEvents.trigger(he,void 0)});r(this,"_triggerMainCamControl",e=>{const t=e.getHeader(rn),n=e.getHeader(Le),i=n===q.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(ae,{isSyncForced:i});return}if(t===R.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(oe,{isSyncForced:i});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(w,{isSyncForced:i});const o=e.getHeader(an);this._sessionEvents.trigger(re,{mainCam:t,resolutionMainCam:o})});r(this,"_triggerMicControl",e=>{const t=e.getHeader(on),i=e.getHeader(Le)===q.ADMIN_SYNC_FORCED;t===W.ADMIN_START_MIC?this._sessionEvents.trigger(Ee,{isSyncForced:i}):t===W.ADMIN_STOP_MIC&&this._sessionEvents.trigger(ce,{isSyncForced:i})});r(this,"_triggerUseLicense",e=>{const t=e.getHeader(nn);this._sessionEvents.trigger(ee,t)});r(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,i=n.getHeader(Jt);if(i)switch(i){case Qt:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case un:{this._maybeHandleNotify(n);break}case D:{this._triggerShareState(n);break}case be:{this._triggerMainCamControl(n);break}case en:{this._triggerMicControl(n);break}case tn:{this._triggerUseLicense(n);break}case dn:{this._maybeTriggerParticipantMoveRequestToSpectators(n);break}}});r(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});r(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Tn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});r(this,"_handleEnded",e=>{const{originator:t}=e;t===We&&this._sessionEvents.trigger(ie,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new ve(De),this._uaEvents=new ve(Oe),this._cancelableConnect=new N.CancelableRequest(this._connect,{moduleName:g,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new N.CancelableRequest(this._initUa,{moduleName:g}),this._cancelableDisconnect=new N.CancelableRequest(this._disconnect,{moduleName:g}),this._cancelableSet=new N.CancelableRequest(this._set,{moduleName:g}),this._cancelableCall=new N.CancelableRequest(this._call,{moduleName:g}),this._cancelableAnswer=new N.CancelableRequest(this._answer,{moduleName:g}),this._cancelableSendDTMF=new N.CancelableRequest(this._sendDTMF,{moduleName:g}),this.onSession(y,this._handleShareState),this.onSession(Ie,this._handleNewInfo),this.on(z,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(m,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((i,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{i()},failed:o}})}catch(a){o(a)}})}async ping(e,t){var i;if(!((i=this.ua)!=null&&i.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:i,remoteAddress:o,extraHeaders:a}){return new Promise((c,E)=>{const{configuration:l}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),_=this._createUa({...l,remoteAddress:o,extraHeaders:a}),d=()=>{const u=new Error("Telephony is not available");E(u)};_.once(S,d);const h=()=>{_.removeAllListeners(),_.once(S,c),_.stop()};_.once(f,h),_.start()})}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");const{contentHint:n}=t||{},i=p(e,{contentHint:n});return this.session.replaceMediaStream(i,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:i={callLimit:zn}}){const o=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=ye.repeatedCallsAsync({targetFunction:o,isComplete:a,isRejectAsValid:!0,...i}),this._cancelableSendPresentationWithRepeatedCalls.then(c=>c)}hasEqualConnectionConfiguration(e){var i;const{configuration:t}=this.createUaConfiguration(e),n=(i=this.ua)==null?void 0:i.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:i="",sipServerUrl:o,register:a=!1,sessionTimers:c=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:_=6,userAgent:d}){if(a&&!t)throw new Error("password is required for authorized connection");const h=a&&e?e.trim():`${pn()}`,u=On(o),C=u(h),T=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:C,display_name:He(i),user_agent:d,sdp_semantics:"unified-plan",sockets:[T],session_timers:c,register_expires:E,connection_recovery_min_interval:l,connection_recovery_max_interval:_},helpers:{socket:T,getSipServerUrl:u}}}async _sendPresentation(e,t,{maxBitrate:n=dt,onAddedSender:i,isNeedReinvite:o=!0,isP2P:a=!1,contentHint:c="detail"}){const E=p(t,{contentHint:c});this._streamPresentationCurrent=E;const l=a?[gn]:[Sn],_=e.sendInfo(D,void 0,{extraHeaders:l}).then(async()=>e.startPresentation(E,o,i)).then(async()=>{const{connection:d}=this;if(!d||n===void 0)return;const h=d.getSenders();await Gn(h,t,n)}).then(()=>t).catch(d=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(H,d),d});return this.promisePendingStartPresentation=_,_.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,onAddedSender:o,contentHint:a}={},c){const E=this.establishedSession;if(!E)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(E),this._sendPresentationWithDuplicatedCalls({session:E,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,onAddedSender:o,contentHint:a},options:c})}async sendMustStopPresentation(e){await e.sendInfo(D,void 0,{extraHeaders:[Nn]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const i=e?[An]:[Cn],o=this.establishedSession;return o&&t&&(n=n.then(async()=>o.sendInfo(D,void 0,{extraHeaders:i})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(H,a),a})),!o&&t&&this._sessionEvents.trigger(fe,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,onAddedSender:i,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,onAddedSender:i,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,i,o,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(i=(n=this.incomingSession)==null?void 0:n.remote_identity)==null?void 0:i.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,i=this._remoteStreams[n]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[n]=i,i}_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,i)=>{if(n.kind==="audio")return;const o=n,a=e[i-1];let c;a&&a.kind==="audio"&&(c=a);const E=this._generateStream(o,c);t.push(E)}),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(w)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=`${we}: ${e}`,i=`${Ue}: ${t}`,o=[n,i];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 i=`${cn}: currentstate`,o=`${_n}: ${Number(e)}`,a=`${ln}: ${Number(t)}`,c=[i,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=[`${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=Ve;exports.EEventsMainCAM=R;exports.EEventsMic=W;exports.EEventsSyncMediaState=q;exports.EUseLicense=Nt;exports.NOT_FOUND=ke;exports.REJECTED=x;exports.SESSION_EVENT_NAMES=De;exports.SipConnector=cs;exports.UA_EVENT_NAMES=Oe;exports.causes=Yt;exports.constants=Gt;exports.disableDebug=mn;exports.enableDebug=fn;exports.eventNames=$t;exports.hasCanceledCallError=Qn;exports.logger=M;exports.setEncodingsToSender=It;exports.setParametersToSender=Rt;
|