sip-connector 14.1.1 → 14.1.2-0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/SipConnector-BHvTGgmw.js +1352 -0
- package/dist/SipConnector-ChW25Tx9.cjs +1 -0
- package/dist/doMock.cjs +1 -1
- package/dist/doMock.js +302 -298
- package/dist/index.cjs +1 -1
- package/dist/index.js +533 -522
- package/package.json +6 -5
- package/dist/SipConnector-DRjfFGAZ.js +0 -1339
- package/dist/SipConnector-EXAO9Z-2.cjs +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const Pt=require("@krivega/cancelable-promise"),ye=require("events-constructor"),$=require("repeated-calls"),G=require("debug"),Ot="Connection Error",We="Request Timeout",mt="SIP Failure Code",Mt="Internal Error",Dt="Busy",J="Rejected",pt="Redirected",vt="Unavailable",ke="Not Found",yt="Address Incomplete",wt="Incompatible SDP",bt="Missing SDP",Ut="Authentication Error",Be="Terminated",Lt="WebRTC Error",X="Canceled",Ht="No Answer",Wt="Expires",kt="No ACK",Bt="Dialog Error",Ft="User Denied Media Access",Fe="Bad Media Description",xt="RTP Timeout",Vt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:yt,AUTHENTICATION_ERROR:Ut,BAD_MEDIA_DESCRIPTION:Fe,BUSY:Dt,BYE:Be,CANCELED:X,CONNECTION_ERROR:Ot,DIALOG_ERROR:Bt,EXPIRES:Wt,INCOMPATIBLE_SDP:wt,INTERNAL_ERROR:Mt,MISSING_SDP:bt,NOT_FOUND:ke,NO_ACK:kt,NO_ANSWER:Ht,REDIRECTED:pt,REJECTED:J,REQUEST_TIMEOUT:We,RTP_TIMEOUT:xt,SIP_FAILURE_CODE:mt,UNAVAILABLE:vt,USER_DENIED_MEDIA_ACCESS:Ft,WEBRTC_ERROR:Lt},Symbol.toStringTag,{value:"Module"})),Q="incomingCall",z="declinedIncomingCall",j="failedIncomingCall",K="terminatedIncomingCall",B="connecting",I="connected",g="disconnected",v="newRTCSession",P="registered",Z="unregistered",O="registrationFailed",xe="newMessage",ee="sipEvent",te="availableSecondRemoteStream",ne="notAvailableSecondRemoteStream",se="mustStopPresentation",y="shareState",ie="enterRoom",re="useLicense",oe="peerconnection:confirmed",ae="peerconnection:ontrack",w="channels",ce="channels:notify",Ee="ended:fromserver",de="main-cam-control",he="admin-stop-main-cam",Se="admin-start-main-cam",Te="admin-stop-mic",le="admin-start-mic",b="admin-force-sync-media-state",ue="participant:added-to-list-moderators",ge="participant:removed-from-list-moderators",Ce="participant:move-request-to-stream",F="participant:move-request-to-spectators",x="participant:move-request-to-participants",_e="participation:accepting-word-request",Ne="participation:cancelling-word-request",Ae="webcast:started",Re="webcast:stopped",fe="account:changed",Ie="account:deleted",Pe="conference:participant-token-issued",m="ended",Ve="sending",Ye="reinvite",qe="replaces",$e="refer",Ge="progress",Je="accepted",U="confirmed",L="peerconnection",N="failed",Xe="muted",Qe="unmuted",Oe="newDTMF",me="newInfo",ze="hold",je="unhold",Ke="update",Ze="sdp",et="icecandidate",tt="getusermediafailed",nt="peerconnection:createofferfailed",st="peerconnection:createanswerfailed",it="peerconnection:setlocaldescriptionfailed",rt="peerconnection:setremotedescriptionfailed",ot="presentation:start",at="presentation:started",ct="presentation:end",Me="presentation:ended",H="presentation:failed",Et="SPECTATOR",dt="PARTICIPANT",ht=1e6;var C=(s=>(s.LOCAL="local",s.REMOTE="remote",s.SYSTEM="system",s))(C||{});const Yt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Je,ACCOUNT_CHANGED:fe,ACCOUNT_DELETED:Ie,ADMIN_FORCE_SYNC_MEDIA_STATE:b,ADMIN_START_MAIN_CAM:Se,ADMIN_START_MIC:le,ADMIN_STOP_MAIN_CAM:he,ADMIN_STOP_MIC:Te,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:te,CHANNELS:w,CHANNELS_NOTIFY:ce,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Pe,CONFIRMED:U,CONNECTED:I,CONNECTING:B,DECLINED_INCOMING_CALL:z,DISCONNECTED:g,ENDED:m,ENDED_FROM_SERVER:Ee,ENTER_ROOM:ie,FAILED:N,FAILED_INCOMING_CALL:j,GET_USER_MEDIA_FAILED:tt,HOLD:ze,ICE_CANDIDATE:et,INCOMING_CALL:Q,MAIN_CAM_CONTROL:de,MUST_STOP_PRESENTATION_EVENT:se,MUTED:Xe,NEW_DTMF:Oe,NEW_INFO:me,NEW_MESSAGE:xe,NEW_RTC_SESSION:v,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,ONE_MEGABIT_IN_BITS:ht,Originator:C,PARTICIPANT:dt,PARTICIPANT_ADDED_TO_LIST_MODERATORS:ue,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:x,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:F,PARTICIPANT_MOVE_REQUEST_TO_STREAM:Ce,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:ge,PARTICIPATION_ACCEPTING_WORD_REQUEST:_e,PARTICIPATION_CANCELLING_WORD_REQUEST:Ne,PEER_CONNECTION:L,PEER_CONNECTION_CONFIRMED:oe,PEER_CONNECTION_CREATE_ANSWER_FAILED:st,PEER_CONNECTION_CREATE_OFFER_FAILED:nt,PEER_CONNECTION_ONTRACK:ae,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:it,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:rt,PRESENTATION_END:ct,PRESENTATION_ENDED:Me,PRESENTATION_FAILED:H,PRESENTATION_START:ot,PRESENTATION_STARTED:at,PROGRESS:Ge,REFER:$e,REGISTERED:P,REGISTRATION_FAILED:O,REINVITE:Ye,REPLACES:qe,SDP:Ze,SENDING:Ve,SHARE_STATE:y,SIP_EVENT:ee,SPECTATOR:Et,TERMINATED_INCOMING_CALL:K,UNHOLD:je,UNMUTED:Qe,UNREGISTERED:Z,UPDATE:Ke,USE_LICENSE:re,WEBCAST_STARTED:Ae,WEBCAST_STOPPED:Re},Symbol.toStringTag,{value:"Module"})),St=[Q,z,K,j,_e,Ne,Ce,ce,Pe,fe,Ie,Ae,Re,ue,ge],V=[B,I,g,v,P,Z,O,xe,ee],Tt=[te,ne,se,y,ie,re,oe,ae,w,Ee,de,Se,he,Te,le,b,F,x],De=[m,B,Ve,Ye,qe,$e,Ge,Je,U,L,N,Xe,Qe,Oe,me,ze,je,Ke,Ze,et,tt,nt,st,it,rt,ot,at,ct,Me,H],lt=[...V,...St],pe=[...De,...Tt],qt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:pe,SESSION_JSSIP_EVENT_NAMES:De,SESSION_SYNTHETICS_EVENT_NAMES:Tt,UA_EVENT_NAMES:lt,UA_JSSIP_EVENT_NAMES:V,UA_SYNTHETICS_EVENT_NAMES:St},Symbol.toStringTag,{value:"Module"})),ve="sip-connector",p=G(ve),$t=()=>{G.enable(ve)},Gt=()=>{G.enable(`-${ve}`)},Jt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),Xt=(s,e)=>{s.encodings??=[];for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},ut=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,Qt=ut(),zt=(s,e)=>{if(Qt(s,e))return s},jt=(s,e)=>{const t=s.maxBitrate,n=zt(e,t);return n!==void 0&&(s.maxBitrate=n),s},gt=1,Kt=ut(gt),Zt=(s,e)=>{const t=s===void 0?void 0:Math.max(s,gt);if(t!==void 0&&Kt(t,e))return t},en=(s,e)=>{const t=s.scaleResolutionDownBy,n=Zt(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},tn=(s,e)=>{const t=e.encodings?.length??0;return Xt(s,t),s.encodings.forEach((n,i)=>{const r=(e?.encodings??[])[i],o=r?.maxBitrate,a=r?.scaleResolutionDownBy;jt(n,o),en(n,a)}),s},nn=(s,e)=>{if(s.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(s.codecs?.length??0);t++)if(JSON.stringify(s.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(s.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(s.headerExtensions?.length??0);t++)if(JSON.stringify(s.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(s.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(s.encodings.length??0);t++)if(JSON.stringify(s.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return s.rtcp?.cname!==e.rtcp?.cname||s.rtcp?.reducedSize!==e.rtcp?.reducedSize||s.degradationPreference!==e.degradationPreference},Ct=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));tn(t,e),Jt(t,e);const i=nn(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var A=(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))(A||{}),W=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(W||{}),k=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(k||{}),_t=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(_t||{}),Nt=(s=>(s.VP8="video/VP8",s.VP9="video/VP9",s.H264="video/H264",s.AV1="video/AV1",s.rtx="video/rtx",s.red="video/red",s.flexfec03="video/flexfec-03",s))(Nt||{});const At=async(s,e,t)=>{const{isChanged:n,parameters:i}=await Ct(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}};function sn(s){return e=>`sip:${e}@${s}`}const rn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,we=s=>s.trim().replaceAll(" ","_"),on=rn(1e5,99999999),an=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),cn=s=>{const e=[];return s!==void 0&&s!==""&&e.push(`X-Vinteo-Remote: ${s}`),e},En="content-type",dn="x-webrtc-enter-room",M="application/vinteo.webrtc.sharedesktop",hn="application/vinteo.webrtc.roomname",Sn="application/vinteo.webrtc.channels",Tn="application/vinteo.webrtc.mediastate",ln="application/vinteo.webrtc.refusal",be="application/vinteo.webrtc.maincam",un="application/vinteo.webrtc.mic",gn="application/vinteo.webrtc.uselic",Cn="X-WEBRTC-USE-LICENSE",_n="X-WEBRTC-PARTICIPANT-NAME",Ue="X-WEBRTC-INPUT-CHANNELS",Le="X-WEBRTC-OUTPUT-CHANNELS",Nn="X-WEBRTC-MAINCAM",An="X-WEBRTC-MIC",He="X-WEBRTC-SYNC",Rn="X-WEBRTC-MAINCAM-RESOLUTION",fn="X-WEBRTC-MEDIA-STATE",In="X-Vinteo-Media-Type",Pn="X-Vinteo-MainCam-State",On="X-Vinteo-Mic-State",mn="application/vinteo.webrtc.partstate",Mn="X-WEBRTC-PARTSTATE",Dn="application/vinteo.webrtc.notify",pn="X-VINTEO-NOTIFY",R="x-webrtc-share-state",vn=`${R}: LETMESTARTPRESENTATION`,yn=`${R}: STOPPRESENTATION`,Rt="YOUCANRECEIVECONTENT",ft="CONTENTEND",It="YOUMUSTSTOPSENDCONTENT",wn=`${R}: ${It}`,bn=`${R}: ${Rt}`,Un=`${R}: ${ft}`,Ln="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Hn=`${Ln}: LETMESTARTMAINCAM`,Wn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},D=(s,{directionVideo:e,directionAudio:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),r=e==="recvonly"?[]:s.getVideoTracks(),o=[...i,...r],a=new MediaStream(o);return a.getTracks=()=>[...a.getAudioTracks(),...a.getVideoTracks()],n&&n!=="none"&&Wn(a,n),a},kn="Error decline with 603",Bn=1006,Fn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Bn,xn=s=>s.message===kn,Vn=(s,e)=>s.find(t=>t.track!==null&&e.getTracks().includes(t.track)),Yn=async(s,e,t)=>{const n=Vn(s,e);if(n)return At(n,{maxBitrate:t})},qn=486,$n=487,Gn=3,Jn=1,Xn=s=>s instanceof Object&&("originator"in s||"cause"in s),Qn=s=>{if(Pt.isCanceledError(s))return!0;if(!Xn(s))return!1;const{originator:e,cause:t}=s;return typeof t=="string"?t===We||t===J||e===C.LOCAL&&(t===X||t===Be):!1},zn=s=>$.hasCanceledError(s),jn="channels",Kn="WebcastStarted",Zn="WebcastStopped",es="accountChanged",ts="accountDeleted",ns="addedToListModerators",ss="removedFromListModerators",is="ParticipationRequestAccepted",rs="ParticipationRequestRejected",os="ParticipantMovedToWebcast",as="ConferenceParticipantTokenIssued";class cs{promisePendingStartPresentation;promisePendingStopPresentation;ua;rtcSession;incomingRTCSession;streamPresentationCurrent;socket;isRegisterConfigInner=!1;connectionConfiguration={};remoteStreams={};JsSIP;sessionEvents;uaEvents;cancelableConnectWithRepeatedCalls;cancelableSendPresentationWithRepeatedCalls;isPendingConnect=!1;isPendingInitUa=!1;isPendingCall=!1;isPendingAnswer=!1;constructor({JsSIP:e}){this.JsSIP=e,this.sessionEvents=new ye(pe),this.uaEvents=new ye(lt),this.onSession(y,this.handleShareState),this.onSession(me,this.handleNewInfo),this.on(ee,this.handleSipEvent),this.onSession(N,this.handleEnded),this.onSession(m,this.handleEnded)}get connection(){return this.rtcSession?.connection}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this.isPendingInitUa||this.isPendingConnect||this.isPendingCall||this.isPendingAnswer}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this.isRegisterConfigInner}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));hangUp=async()=>(this.cancelRequests(),this.hangUpWithoutCancelRequests());async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(P,e),this.ua.on(O,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(Z,e),this.ua.unregister()):t(new Error("ua is not registered"))})}tryRegister=async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this.uaEvents.trigger(B,void 0);try{await this.unregister()}catch(e){p("tryRegister",e)}return this.register()};async sendOptions(e,t,n){if(!this.ua)throw new Error("is not connected");return new Promise((i,r)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{i()},failed:r}})}catch(o){r(o)}})}async ping(e,t){if(!this.ua?.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:r,extraHeaders:o}){return new Promise((a,c)=>{const{configuration:E}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),h=this.createUa({...E,remoteAddress:r,extraHeaders:o}),S=()=>{const T=new Error("Telephony is not available");c(T)};h.once(g,S);const d=()=>{h.removeAllListeners(),h.once(g,a),h.stop()};h.once(I,d),h.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=D(e,{contentHint:n});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}declineToIncomingCall=async({statusCode:e=$n}={})=>new Promise((t,n)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.uaEvents.trigger(z,r),i.terminate({status_code:e}),t()}catch(i){n(i)}});busyIncomingCall=async()=>this.declineToIncomingCall({statusCode:qn});async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Hn];return this.rtcSession.sendInfo(be,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(xn(n))throw n})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:o,onAddedTransceiver:a}={},c){const E=this.establishedRTCSession;if(!E)throw new Error("No rtcSession established");if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return n===!0&&await this.sendMustStopPresentation(),this.sendPresentationWithDuplicatedCalls({rtcSession:E,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:o,onAddedTransceiver:a},options:c})}async stopPresentation({isP2P:e=!1}={}){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=e?[Un]:[yn],r=this.establishedRTCSession;return r&&t&&(n=n.then(async()=>r.sendInfo(M,void 0,{extraHeaders:i})).then(async()=>r.stopPresentation(t)).catch(o=>{throw this.sessionEvents.trigger(H,o),o})),!r&&t&&this.sessionEvents.trigger(Me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this.resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:r,onAddedTransceiver:o}={}){const a=this.establishedRTCSession;if(!a)throw new Error("No rtcSession 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,contentHint:i,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:o})}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 an(t)?this.generateStreams(t):this.generateAudioStreams(t)}getIncomingRTCSession(){const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e}set=async({displayName:e,password:t})=>new Promise((n,i)=>{const{ua:r}=this;if(!r){i(new Error("this.ua is not initialized"));return}let o=!1,a=!1;e!==void 0&&e!==this.connectionConfiguration.displayName&&(o=r.set("display_name",we(e)),this.connectionConfiguration.displayName=e),t!==void 0&&t!==this.connectionConfiguration.password&&(a=r.set("password",t),this.connectionConfiguration.password=t);const c=o||a;a&&this.isRegisterConfig?this.register().then(()=>{n(c)}).catch(E=>{i(E)}):c?n(c):i(new Error("nothing changed"))});disconnect=async()=>{this.off(v,this.handleNewRTCSession);const e=new Promise(n=>{this.once(g,()=>{n()})}),{ua:t}=this;return t?(await this.hangUpWithoutCancelRequests(),t.stop()):this.uaEvents.trigger(g,void 0),e.finally(()=>{delete this.ua})};call=async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:r,directionVideo:o,directionAudio:a,contentHint:c,offerToReceiveAudio:E=!0,offerToReceiveVideo:h=!0,sendEncodings:S,onAddedTransceiver:d})=>(this.isPendingCall=!0,new Promise((T,l)=>{const{ua:u}=this;if(!u){l(new Error("this.ua is not initialized"));return}this.connectionConfiguration.number=e,this.connectionConfiguration.answer=!1,this.handleCall({ontrack:i}).then(T).catch(_=>{l(_)}),this.rtcSession=u.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:D(t,{directionVideo:o,directionAudio:a,contentHint:c}),eventHandlers:this.sessionEvents.triggers,directionVideo:o,directionAudio:a,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:E,offerToReceiveVideo:h},sendEncodings:S,onAddedTransceiver:d})}).finally(()=>{this.isPendingCall=!1}));answerToIncomingCall=async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:r,directionAudio:o,offerToReceiveAudio:a,offerToReceiveVideo:c,contentHint:E,sendEncodings:h,onAddedTransceiver:S})=>(this.isPendingAnswer=!0,new Promise((d,T)=>{try{const l=this.getIncomingRTCSession();this.rtcSession=l,this.removeIncomingSession(),this.sessionEvents.eachTriggers((_,Y)=>{const f=De.find(q=>q===Y);f&&l.on(f,_)}),this.connectionConfiguration.answer=!0,this.connectionConfiguration.number=l.remote_identity.uri.user,this.handleCall({ontrack:t}).then(d).catch(_=>{T(_)});const u=D(e,{directionVideo:r,directionAudio:o,contentHint:E});l.answer({extraHeaders:n,directionVideo:r,directionAudio:o,mediaStream:u,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:a,offerToReceiveVideo:c},sendEncodings:h,onAddedTransceiver:S})}catch(l){T(l)}}).finally(()=>{this.isPendingAnswer=!1}));sendDTMF=async e=>new Promise((t,n)=>{const{rtcSession:i}=this;if(!i){n(new Error("No rtcSession established"));return}this.onceSession(Oe,({originator:r})=>{r===C.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})});cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.cancel()}async waitChannels(){return this.waitSession(w)}async waitSyncMediaState(){return this.waitSession(b)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${Ue}: ${e}`,i=`${Le}: ${t}`,r=[n,i];return this.rtcSession.sendInfo(Sn,void 0,{extraHeaders:r})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${fn}: currentstate`,r=`${Pn}: ${Number(e)}`,o=`${On}: ${Number(t)}`,a=[i,r,o];return this.rtcSession.sendInfo(Tn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:a})}async sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const a=[`${In}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(ln,void 0,{noTerminateWhenError:!0,...t,extraHeaders:a})}async sendRefusalToTurnOnMic(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}removeIncomingSession=()=>{delete this.incomingRTCSession};getSipServerUrl=e=>e;async sendMustStopPresentation(){const e=this.establishedRTCSession;if(!e)throw new Error("No rtcSession established");await e.sendInfo(M,void 0,{extraHeaders:[wn]})}connectWithDuplicatedCalls=async(e,{callLimit:t=Gn}={})=>{const n=async()=>this.connectInner(e),i=r=>{const a=this.ua?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),c=r!=null&&!Fn(r);return a||c};return this.isPendingConnect=!0,this.cancelableConnectWithRepeatedCalls=$.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r}).finally(()=>{this.isPendingConnect=!1})};async sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:Jn}}){const r=async()=>this.sendPresentation(e,t,n),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=$.repeatedCallsAsync({targetFunction:r,isComplete:o,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(a=>a)}hasEqualConnectionConfiguration(e){const{configuration:t}=this.createUaConfiguration(e),n=this.ua?.configuration;return n?.password===t.password&&n?.register===t.register&&n.uri.toString()===t.uri&&n.display_name===t.display_name&&n.user_agent===t.user_agent&&n.sockets===t.sockets&&n.session_timers===t.session_timers&&n.register_expires===t.register_expires&&n.connection_recovery_min_interval===t.connection_recovery_min_interval&&n.connection_recovery_max_interval===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:r,register:o=!1,sessionTimers:a=!1,registerExpires:c=60*5,connectionRecoveryMinInterval:E=2,connectionRecoveryMaxInterval:h=6,userAgent:S}){if(o&&(t===void 0||t===""))throw new Error("password is required for authorized connection");const d=o&&e!==void 0&&e.trim()!==""?e.trim():`${on()}`,T=sn(r),l=T(d),u=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:o,uri:l,display_name:we(i),user_agent:S,sdp_semantics:"unified-plan",sockets:[u],session_timers:a,register_expires:c,connection_recovery_min_interval:E,connection_recovery_max_interval:h},helpers:{socket:u,getSipServerUrl:T}}}async sendPresentation(e,t,{maxBitrate:n=ht,isNeedReinvite:i=!0,isP2P:r=!1,contentHint:o="detail",sendEncodings:a,onAddedTransceiver:c}){const E=D(t,{contentHint:o});if(E===void 0)throw new Error("No streamPresentationCurrent");this.streamPresentationCurrent=E;const h=r?[bn]:[vn],S=e.sendInfo(M,void 0,{extraHeaders:h}).then(async()=>e.startPresentation(E,i,{sendEncodings:a,onAddedTransceiver:c})).then(async()=>{const{connection:d}=this;if(!d)return;const T=d.getSenders();await Yn(T,t,n)}).then(()=>t).catch(d=>{throw this.removeStreamPresentationCurrent(),this.sessionEvents.trigger(H,d),d});return this.promisePendingStartPresentation=S,S.finally(()=>{this.promisePendingStartPresentation=void 0})}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}cancelRequestsAndResetPresentation(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}handleNewRTCSession=({originator:e,session:t})=>{if(e===C.REMOTE){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(N,i=>{this.removeIncomingSession(),i.originator===C.LOCAL?this.uaEvents.trigger(K,n):this.uaEvents.trigger(j,n)}),this.uaEvents.trigger(Q,n)}};connectInner=async e=>this.initUa(e).then(async()=>this.start());initUa=async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:r,sessionTimers:o,registerExpires:a,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:E,userAgent:h,displayName:S="",register:d=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(d&&(e===void 0||e===""))throw new Error("user is required for authorized connection");if(d&&(t===void 0||t===""))throw new Error("password is required for authorized connection");this.isPendingInitUa=!0;try{this.connectionConfiguration={sipServerUrl:n,displayName:S,register:d,user:e,password:t};const{configuration:l,helpers:u}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:S,register:d,sessionTimers:o,registerExpires:a,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:E,userAgent:h});return this.getSipServerUrl=u.getSipServerUrl,this.socket=u.socket,this.ua&&await this.disconnect(),this.isRegisterConfigInner=!!d,this.ua=this.createUa({...l,remoteAddress:r,extraHeaders:T}),this.uaEvents.eachTriggers((_,Y)=>{const f=V.find(q=>q===Y);f&&this.ua&&this.ua.on(f,_)}),this.ua}finally{this.isPendingInitUa=!1}};createUa=({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),o=[...e!==void 0&&e!==""?cn(e):[],...t];return o.length>0&&i.registrator().setExtraHeaders(o),i};start=async()=>new Promise((e,t)=>{const{ua:n}=this;if(!n){t(new Error("this.ua is not initialized"));return}const i=()=>{a(),e(n)},r=c=>{a(),t(c)},o=()=>{this.isRegisterConfig?(this.on(P,i),this.on(O,r)):this.on(I,i),this.on(g,r)},a=()=>{this.off(P,i),this.off(O,r),this.off(I,i),this.off(g,r)};o(),this.on(v,this.handleNewRTCSession),n.start()});handleCall=async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(L,h),this.onSession(U,S)},r=()=>{this.offSession(L,h),this.offSession(U,S)},o=()=>{this.onSession(N,c),this.onSession(m,c)},a=()=>{this.offSession(N,c),this.offSession(m,c)},c=d=>{r(),a(),n(d)};let E;const h=({peerconnection:d})=>{E=d,E.ontrack=T=>{this.sessionEvents.trigger(ae,E),e&&e(T)}},S=()=>{E!==void 0&&this.sessionEvents.trigger(oe,E),r(),a(),t(E)};i(),o()});restoreSession=()=>{this.cancelRequestsAndResetPresentation(),delete this.connectionConfiguration.number,delete this.rtcSession,this.remoteStreams={}};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 r=n,o=e[i-1];let a;o?.kind==="audio"&&(a=o);const c=this.generateStream(r,a);t.push(c)}),t}generateAudioStreams(e){return e.map(n=>this.generateAudioStream(n))}hangUpWithoutCancelRequests=async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this.streamPresentationCurrent)try{await this.stopPresentation()}catch(t){p("error stop presentation: ",t)}if(this.restoreSession(),!e.isEnded())return e.terminateAsync({cause:X})}};cancelRequests(){this.cancelConnectWithRepeatedCalls()}cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}handleShareState=e=>{switch(e){case Rt:{this.sessionEvents.trigger(te,void 0);break}case ft:{this.sessionEvents.trigger(ne,void 0);break}case It:{this.sessionEvents.trigger(se,void 0);break}}};maybeTriggerChannels=e=>{const t=e.getHeader(Ue),n=e.getHeader(Le);if(t&&n){const i={inputChannels:t,outputChannels:n};this.sessionEvents.trigger(w,i)}};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:p("unknown cmd",e.cmd)}};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.uaEvents.trigger(ge,t)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.uaEvents.trigger(ue,t)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(Ae,n)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(Re,n)};triggerAccountChangedNotify=()=>{this.uaEvents.trigger(fe,void 0)};triggerAccountDeletedNotify=()=>{this.uaEvents.trigger(Ie,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this.uaEvents.trigger(Pe,i)};triggerChannelsNotify=e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this.uaEvents.trigger(ce,i)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(_e,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ne,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ce,t)};triggerEnterRoom=e=>{const t=e.getHeader(dn),n=e.getHeader(_n);this.sessionEvents.trigger(ie,{room:t,participantName:n})};triggerShareState=e=>{const t=e.getHeader(R);this.sessionEvents.trigger(y,t)};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(Mn);t===Et&&this.sessionEvents.trigger(F,void 0),t===dt&&this.sessionEvents.trigger(x,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(Nn),n=e.getHeader(He),i=n===k.ADMIN_SYNC_FORCED;if(t===A.ADMIN_START_MAIN_CAM){this.sessionEvents.trigger(Se,{isSyncForced:i});return}if(t===A.ADMIN_STOP_MAIN_CAM){this.sessionEvents.trigger(he,{isSyncForced:i});return}(t===A.RESUME_MAIN_CAM||t===A.PAUSE_MAIN_CAM)&&n!==void 0&&this.sessionEvents.trigger(b,{isSyncForced:i});const r=e.getHeader(Rn);this.sessionEvents.trigger(de,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(An),i=e.getHeader(He)===k.ADMIN_SYNC_FORCED;t===W.ADMIN_START_MIC?this.sessionEvents.trigger(le,{isSyncForced:i}):t===W.ADMIN_STOP_MIC&&this.sessionEvents.trigger(Te,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(Cn);this.sessionEvents.trigger(re,t)};handleNewInfo=e=>{const{originator:t}=e;if(t!==C.REMOTE)return;const{request:n}=e,i=n.getHeader(En);if(i)switch(i){case hn:{this.triggerEnterRoom(n),this.maybeTriggerChannels(n);break}case Dn:{this.maybeHandleNotify(n);break}case M:{this.triggerShareState(n);break}case be:{this.triggerMainCamControl(n);break}case un:{this.triggerMicControl(n);break}case gn:{this.triggerUseLicense(n);break}case mn:{this.maybeTriggerParticipantMoveRequest(n);break}}};handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{const t=e.getHeader(pn);if(t){const n=JSON.parse(t);this.handleNotify(n)}};handleEnded=e=>{const{originator:t}=e;t===C.REMOTE&&this.sessionEvents.trigger(Ee,e),this.restoreSession()}}exports.BAD_MEDIA_DESCRIPTION=Fe;exports.EEventsMainCAM=A;exports.EEventsMic=W;exports.EEventsSyncMediaState=k;exports.EMimeTypesVideoCodecs=Nt;exports.EUseLicense=_t;exports.NOT_FOUND=ke;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=x;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=F;exports.REJECTED=J;exports.SESSION_EVENT_NAMES=pe;exports.SipConnector=cs;exports.UA_JSSIP_EVENT_NAMES=V;exports.causes=Vt;exports.constants=Yt;exports.disableDebug=Gt;exports.enableDebug=$t;exports.eventNames=qt;exports.hasCanceledCallError=Qn;exports.hasCanceledStartPresentationError=zn;exports.logger=p;exports.setEncodingsToSender=At;exports.setParametersToSender=Ct;
|