sip-connector 6.9.2 → 6.10.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/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@krivega/cancelable-promise"),require("events-constructor"),require("stack-promises")):"function"==typeof define&&define.amd?define(["exports","@krivega/cancelable-promise","events-constructor","stack-promises"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sipConnector={},e.cancelablePromise,e.Events,e.createStackPromises)}(this,(function(e,t,s,i){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(s),o=n(i);const a=e=>e.getStats().then((e=>{const t=(s="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===s)));var s;return null==t?void 0:t.mimeType}));function c(e,t,s,i){return new(s||(s=Promise))((function(n,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}const d=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,h=d(1),l=d(void 0),u=(e,t,s)=>{const i=e.getParameters();i.encodings&&0!==i.encodings.length||(i.encodings=[{}]);const[n]=i.encodings,r=n.scaleResolutionDownBy,o=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&h(s,t))return s})(t.scaleResolutionDownBy,r);let a=!1;void 0!==o&&(i.encodings[0].scaleResolutionDownBy=o,a=!0);const c=n.maxBitrate,d=((e,t)=>{if(l(e,t))return e})(t.maxBitrate,c);return void 0!==d&&(i.encodings[0].maxBitrate=d,a=!0),a?(s&&s(i),e.setParameters(i).then((()=>({parameters:i,isChanged:a})))):Promise.resolve({parameters:i,isChanged:a})},g="incomingCall",_="declinedIncomingCall",m="failedIncomingCall",S="terminatedIncomingCall",f="connecting",E="connected",C="disconnected",v="newRTCSession",p="registered",N="unregistered",R="registrationFailed",T="sipEvent",A="availableSecondRemoteStream",M="notAvailableSecondRemoteStream",I="mustStopPresentation",w="shareState",b="enterRoom",P="useLicense",y="peerconnection:confirmed",D="peerconnection:ontrack",O="channels",U="channels:notify",q="ended:fromserver",k="main-cam-control",x="admin-stop-main-cam",B="admin-start-main-cam",L="admin-stop-mic",W="admin-start-mic",H="admin-force-sync-media-state",F="participant:added-to-list-moderators",V="participant:removed-from-list-moderators",j="participant:move-request-to-conference",X="participant:move-request-to-stream",Y="participant:canceling-word-request",J="webcast:started",$="webcast:stopped",z="account:changed",G="account:deleted",K="conference:participant-token-issued",Q="ended",Z="confirmed",ee="peerconnection",te="failed",se="newDTMF",ie="newInfo",ne="presentation:ended",re="presentation:failed",oe=[g,_,S,m,Y,X,j,U,K,z,G,J,$,F,V],ae=[f,E,C,v,p,N,R,"newMessage",T],ce=[A,M,I,w,b,P,y,D,O,q,k,B,x,L,W,H],de=[Q,f,"sending","reinvite","replaces","refer","progress","accepted",Z,ee,te,"muted","unmuted",se,ie,"hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end",ne,re],he=[...ae,...oe],le=[...de,...ce];var ue=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:oe,UA_JSSIP_EVENT_NAMES:ae,SESSION_SYNTHETICS_EVENT_NAMES:ce,SESSION_JSSIP_EVENT_NAMES:de,UA_EVENT_NAMES:he,SESSION_EVENT_NAMES:le});const ge="Request Timeout",_e="Rejected",me="Terminated",Se="Canceled";var fe=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:ge,SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:_e,REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:me,WEBRTC_ERROR:"WebRTC Error",CANCELED:Se,NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"});const Ee="application/vinteo.webrtc.sharedesktop",Ce="application/vinteo.webrtc.maincam",ve="X-WEBRTC-INPUT-CHANNELS",pe="X-WEBRTC-OUTPUT-CHANNELS",Ne="X-WEBRTC-SYNC",Re="x-webrtc-share-state",Te="YOUCANRECEIVECONTENT",Ae="CONTENTEND";const Me=e=>e.trim().replace(/ /g,"_"),Ie=(we=1e5,be=99999999,()=>Math.floor(Math.random()*(be-we))+we);var we,be;const Pe=(e,{videoMode:t,audioMode:s}={})=>{if(!e||"recvonly"===t&&"recvonly"===s)return;const i=[..."recvonly"===s?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],n=new MediaStream(i);return n.getTracks=()=>[...n.getAudioTracks(),...n.getVideoTracks()],n},ye="local",De="remote";var Oe,Ue,qe,ke;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(Oe||(Oe={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(Ue||(Ue={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}(qe||(qe={})),e.EUseLicense=void 0,(ke=e.EUseLicense||(e.EUseLicense={})).AUDIO="AUDIO",ke.VIDEO="VIDEO",ke.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION";const xe="SipConnector";const Be=e=>1e6*e,Le=Be(.06),We=Be(4),He=o.default(),Fe=e=>(He.add(e),He().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),Ve=({sender:e,scaleResolutionDownBy:t,maxBitrate:s,onSetParameters:i})=>Fe((()=>u(e,{scaleResolutionDownBy:t,maxBitrate:s},i))),je=(e,{track:t,resolution:s},i)=>{const n=t.getSettings(),r=n.width,o=n.height,[a,c]=s.split("x"),d=r/+a,h=o/+c,l=Math.max(d,h,1),u=(g=+a)<=64?Le:g<=128?Be(.12):g<=256?Be(.25):g<=384?Be(.32):g<=426?Be(.38):g<=640?Be(.5):g<=848?Be(.7):g<=1280?Be(1):g<=1920?Be(2):We;var g;return Ve({sender:e,maxBitrate:u,onSetParameters:i,scaleResolutionDownBy:l})},Xe=({mainCam:e,resolutionMainCam:t,sender:s,track:i},n)=>{switch(e){case Oe.PAUSE_MAIN_CAM:return((e,t)=>Ve({sender:e,maxBitrate:Le,onSetParameters:t,scaleResolutionDownBy:200}))(s,n);case Oe.RESUME_MAIN_CAM:return((e,t)=>Ve({sender:e,maxBitrate:We,onSetParameters:t,scaleResolutionDownBy:1}))(s,n);case Oe.MAX_MAIN_CAM_RESOLUTION:if(t)return je(s,{track:i,resolution:t},n)}return Promise.resolve({isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}})};e.causes=fe,e.default=class{constructor({JsSIP:e}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger(f,void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const i=this.incomingSession,n=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(_,n),t(i.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if(e===De){this.incomingSession=t;const e=this.remoteCallerData;t.on(te,(({originator:t})=>{this.removeIncomingSession(),t!==ye?this._uaEvents.trigger(m,e):this._uaEvents.trigger(S,e)})),this._uaEvents.trigger(g,e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:i=!1,sipServerUrl:n,sipWebSocketServerURL:r,remoteAddress:o,extraHeaders:a=[],sdpSemantics:d="plan-b",sessionTimers:h=!1,registerExpires:l=300,connectionRecoveryMinInterval:u=2,connectionRecoveryMaxInterval:g=6,userAgent:_})=>c(this,void 0,void 0,(function*(){if(!n)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(i&&!t)throw new Error("user is required for authorized connection");if(i&&!s)throw new Error("password is required for authorized connection");let c;this._connectionConfiguration={sipServerUrl:n,displayName:e,register:i,user:t,password:s},this._init({sipServerUrl:n,sipWebSocketServerURL:r}),c=i&&t?t.trim():Ie();const m={password:s,register:i,display_name:Me(e),user_agent:_,sdp_semantics:d,sockets:[this.socket],uri:this.getSipServerUrl(c),session_timers:h,register_expires:l,connection_recovery_min_interval:u,connection_recovery_max_interval:g};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!m.register,this.ua=new this.JsSIP.UA(m),this._uaEvents.eachTriggers(((e,t)=>{const s=ae.find((e=>e===t));s&&this.ua.on(s,e)}));const S=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(o),f=[...S,...a];return this.ua.registrator().setExtraHeaders(f),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{n(),e(this.ua)},i=e=>{n(),t(e)},n=()=>{this.off(p,s),this.off(R,i),this.off(E,s),this.off(C,i)};(()=>{this.isRegisterConfig?(this.on(p,s),this.on(R,i)):this.on(E,s),this.on(C,i)})(),this.on(v,this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,i)=>{let n=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(n=this.ua.set("display_name",Me(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=n||r;r&&this.isRegisterConfig?this.register().then((()=>s(o))).catch(i):o?s(o):i(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>c(this,void 0,void 0,(function*(){this.off(v,this.handleNewRTCSession);const e=new Promise((e=>{this.once(C,(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(C,void 0)):this._uaEvents.trigger(C,void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:i,iceServers:n,videoMode:r,audioMode:o,degradationPreference:a,offerToReceiveAudio:c=!0,offerToReceiveVideo:d=!0})=>new Promise(((h,l)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(h).catch(l),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Pe(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:n},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:i,videoMode:n,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const s=de.find((e=>e===t));s&&d.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const h=Pe(e,{videoMode:n,audioMode:r});d.answer({extraHeaders:s,videoMode:n,audioMode:r,degradationPreference:o,mediaStream:h,pcConfig:{iceServers:i}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const i=()=>{this.offSession(ee,a),this.offSession(Z,c)},n=()=>{this.offSession(te,r),this.offSession(Q,r)},r=e=>{i(),n(),s(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger(D,o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger(y,o),i(),n(),t(o)};(()=>{this.onSession(ee,a),this.onSession(Z,c)})(),(()=>{this.onSession(te,r),this.onSession(Q,r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{const i=this.session;i?(this.onceSession(se,(({originator:e})=>{e===ye&&t()})),i.sendDTMF(e,{duration:120,interToneGap:600})):s(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>c(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case Te:this._sessionEvents.trigger(A,void 0);break;case Ae:this._sessionEvents.trigger(M,void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger(I,void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader(ve),s=e.getHeader(pe);if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger(O,e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(V,t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(F,t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(J,s)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger($,s)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger(z,void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger(G,void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this._uaEvents.trigger(K,i)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger(U,t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(j,t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Y,t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(X,t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger(b,t)},this._triggerShareState=e=>{const t=e.getHeader(Re);this._sessionEvents.trigger(w,t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader(Ne),i=s===qe.ADMIN_SYNC_FORCED;if(t===Oe.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(B,{isSyncForced:i});else if(t===Oe.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(x,{isSyncForced:i});else if(t!==Oe.RESUME_MAIN_CAM&&t!==Oe.PAUSE_MAIN_CAM||!s){const s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger(k,{mainCam:t,resolutionMainCam:s})}else this._sessionEvents.trigger(H,{isSyncForced:i})},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC"),s=e.getHeader(Ne)===qe.ADMIN_SYNC_FORCED;t===Ue.ADMIN_START_MIC?this._sessionEvents.trigger(W,{isSyncForced:s}):t===Ue.ADMIN_STOP_MIC&&this._sessionEvents.trigger(L,{isSyncForced:s})},this._triggerUseLicense=e=>{const t=e.getHeader("X-WEBRTC-USE-LICENSE");this._sessionEvents.trigger(P,t)},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,i=s.getHeader("content-type");if(i)switch(i){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case Ee:this._triggerShareState(s);break;case Ce:this._triggerMainCamControl(s);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(s);break;case"application/vinteo.webrtc.uselic":this._triggerUseLicense(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;t===De&&this._sessionEvents.trigger(q,e),this._restoreSession()},this.JsSIP=e,this._sessionEvents=new r.default(le),this._uaEvents=new r.default(he),this._cancelableConnect=new t.CancelableRequest(this._connect,{moduleName:xe,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new t.CancelableRequest(this._createUa,{moduleName:xe}),this._cancelableDisconnect=new t.CancelableRequest(this._disconnect,{moduleName:xe}),this._cancelableSet=new t.CancelableRequest(this._set,{moduleName:xe}),this._cancelableCall=new t.CancelableRequest(this._call,{moduleName:xe}),this._cancelableAnswer=new t.CancelableRequest(this._answer,{moduleName:xe}),this._cancelableSendDTMF=new t.CancelableRequest(this._sendDTMF,{moduleName:xe}),this.onSession(w,this._handleShareState),this.onSession(ie,this._handleNewInfo),this.on(T,this._handleSipEvent),this.onSession(te,this._handleEnded),this.onSession(Q,this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on(p,e),this.ua.on(R,t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on(N,e),this.ua.unregister()):t(new Error("ua is not registered"))}))}sendOptions(e,t,s){return this.ua?new Promise(((i,n)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{i()},failed:e=>{n(e)}}})}catch(e){n(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo(Ce,void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:i,degradationPreference:n}={}){const r=this.establishedSession;if(!r)return Promise.reject(new Error("No session established"));if(this._streamPresentationCurrent)return Promise.reject(new Error("Presentation is already started"));const o=Pe(e);this._streamPresentationCurrent=o;const a=s?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"],c=r.sendInfo(Ee,void 0,{extraHeaders:a}).then((()=>r.startPresentation(o,t,n))).then((()=>{const{connection:t}=this;if(!t||void 0===i)return;return((e,t,s)=>{const i=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return i?u(i,{maxBitrate:s}):Promise.resolve()})(t.getSenders(),e,i)})).then((()=>e)).catch((e=>{throw this._sessionEvents.trigger(re,e),e}));return this.promisePendingStartPresentation=c,c.finally((()=>{this.promisePendingStartPresentation=void 0}))}stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation||Promise.resolve();const i=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],n=this.establishedSession;return n&&t&&(s=s.then((()=>n.sendInfo(Ee,void 0,{extraHeaders:i}))).then((()=>n.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger(re,e),e}))),!n&&t&&this._sessionEvents.trigger(ne,t),this.promisePendingStopPresentation=s,s.finally((()=>{this._resetPresentation()}))}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}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)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,i,n,r;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(i=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===i?void 0:i.uri.host,incomingNumber:null===(r=null===(n=null==this?void 0:this.incomingSession)||void 0===n?void 0:n.remote_identity)||void 0===r?void 0:r.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.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}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,i=this._remoteStreams[s]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[s]=i,i}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,i)=>{if("audio"===s.kind)return;const n=s,r=e[i-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(n,o);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession(O)}waitSyncMediaState(){return this.waitSession(H)}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}sendMediaState({cam:e,mic:t},s={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const i=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},s),{extraHeaders:i}))}},e.eventNames=ue,e.getCodecFromSender=a,e.hasCanceledCallError=(e=new Error)=>{const{originator:s,cause:i}=e;return!!t.isCanceledError(e)||"string"==typeof i&&(i===ge||i===_e||s===ye&&(i===Se||i===me))},e.resolveVideoSendingBalancer=(e,{ignoreForCodec:t,onSetParameters:s}={})=>{let i=()=>{};const n=n=>{i=()=>{const{mainCam:i,resolutionMainCam:r}=n,{connection:o}=e;o&&void 0!==i&&(({mainCam:e,resolutionMainCam:t,connection:s,onSetParameters:i,ignoreForCodec:n})=>{c(void 0,void 0,void 0,(function*(){const r=s.getSenders().find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)}));if(r&&r.track){if(n){const e=yield a(r);if(c=n,(o=e)&&c&&o.toLowerCase().includes(c.toLowerCase()))return}var o,c;Xe({mainCam:e,resolutionMainCam:t,sender:r,track:r.track},i)}}))})({mainCam:i,resolutionMainCam:r,connection:o,onSetParameters:s,ignoreForCodec:t})},i()};return{subscribe:()=>{e.onSession("main-cam-control",n)},unsubscribe:()=>{e.offSession("main-cam-control",n)},reBalance:i}},Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@krivega/cancelable-promise"),require("events-constructor"),require("stack-promises")):"function"==typeof define&&define.amd?define(["exports","@krivega/cancelable-promise","events-constructor","stack-promises"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sipConnector={},e.cancelablePromise,e.Events,e.createStackPromises)}(this,(function(e,t,s,n){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=i(s),o=i(n);const a=e=>e.getStats().then((e=>{const t=(s="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===s)));var s;return null==t?void 0:t.mimeType}));function c(e,t,s,n){return new(s||(s=Promise))((function(i,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}const d=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,h=d(1),l=d(void 0),u=(e,t,s)=>{const n=e.getParameters();n.encodings&&0!==n.encodings.length||(n.encodings=[{}]);const[i]=n.encodings,r=i.scaleResolutionDownBy,o=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&h(s,t))return s})(t.scaleResolutionDownBy,r);let a=!1;void 0!==o&&(n.encodings[0].scaleResolutionDownBy=o,a=!0);const c=i.maxBitrate,d=((e,t)=>{if(l(e,t))return e})(t.maxBitrate,c);return void 0!==d&&(n.encodings[0].maxBitrate=d,a=!0),a?(s&&s(n),e.setParameters(n).then((()=>({parameters:n,isChanged:a})))):Promise.resolve({parameters:n,isChanged:a})},g="incomingCall",_="declinedIncomingCall",m="failedIncomingCall",S="terminatedIncomingCall",f="connecting",E="connected",C="disconnected",v="newRTCSession",p="registered",N="unregistered",T="registrationFailed",R="sipEvent",M="availableSecondRemoteStream",A="notAvailableSecondRemoteStream",w="mustStopPresentation",b="shareState",I="enterRoom",P="useLicense",y="peerconnection:confirmed",O="peerconnection:ontrack",D="channels",U="channels:notify",q="ended:fromserver",k="main-cam-control",x="admin-stop-main-cam",B="admin-start-main-cam",W="admin-stop-mic",L="admin-start-mic",H="admin-force-sync-media-state",F="participant:added-to-list-moderators",V="participant:removed-from-list-moderators",j="participant:move-request-to-conference",X="participant:move-request-to-stream",Y="participant:canceling-word-request",J="webcast:started",$="webcast:stopped",z="account:changed",G="account:deleted",K="conference:participant-token-issued",Q="ended",Z="confirmed",ee="peerconnection",te="failed",se="newDTMF",ne="newInfo",ie="presentation:ended",re="presentation:failed",oe=[g,_,S,m,Y,X,j,U,K,z,G,J,$,F,V],ae=[f,E,C,v,p,N,T,"newMessage",R],ce=[M,A,w,b,I,P,y,O,D,q,k,B,x,W,L,H],de=[Q,f,"sending","reinvite","replaces","refer","progress","accepted",Z,ee,te,"muted","unmuted",se,ne,"hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end",ie,re],he=[...ae,...oe],le=[...de,...ce];var ue=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:oe,UA_JSSIP_EVENT_NAMES:ae,SESSION_SYNTHETICS_EVENT_NAMES:ce,SESSION_JSSIP_EVENT_NAMES:de,UA_EVENT_NAMES:he,SESSION_EVENT_NAMES:le});const ge="Request Timeout",_e="Rejected",me="Terminated",Se="Canceled";var fe=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:ge,SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:_e,REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:me,WEBRTC_ERROR:"WebRTC Error",CANCELED:Se,NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"});const Ee="application/vinteo.webrtc.sharedesktop",Ce="application/vinteo.webrtc.maincam",ve="X-WEBRTC-INPUT-CHANNELS",pe="X-WEBRTC-OUTPUT-CHANNELS",Ne="X-WEBRTC-SYNC",Te="x-webrtc-share-state",Re="YOUCANRECEIVECONTENT",Me="CONTENTEND";const Ae=e=>e.trim().replace(/ /g,"_"),we=(be=1e5,Ie=99999999,()=>Math.floor(Math.random()*(Ie-be))+be);var be,Ie;const Pe=(e,{videoMode:t,audioMode:s}={})=>{if(!e||"recvonly"===t&&"recvonly"===s)return;const n=[..."recvonly"===s?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],i=new MediaStream(n);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},ye="local",Oe="remote";var De,Ue,qe,ke;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(De||(De={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(Ue||(Ue={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}(qe||(qe={})),e.EUseLicense=void 0,(ke=e.EUseLicense||(e.EUseLicense={})).AUDIO="AUDIO",ke.VIDEO="VIDEO",ke.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION";const xe="SipConnector";const Be=e=>1e6*e,We=Be(.06),Le=Be(4),He=o.default(),Fe=e=>(He.add(e),He().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),Ve=({sender:e,scaleResolutionDownBy:t,maxBitrate:s,onSetParameters:n})=>Fe((()=>u(e,{scaleResolutionDownBy:t,maxBitrate:s},n))),je=(e,{track:t,resolution:s},n)=>{const i=t.getSettings(),r=i.width,o=i.height,[a,c]=s.split("x"),d=r/+a,h=o/+c,l=Math.max(d,h,1),u=(g=+a)<=64?We:g<=128?Be(.12):g<=256?Be(.25):g<=384?Be(.32):g<=426?Be(.38):g<=640?Be(.5):g<=848?Be(.7):g<=1280?Be(1):g<=1920?Be(2):Le;var g;return Ve({sender:e,maxBitrate:u,onSetParameters:n,scaleResolutionDownBy:l})},Xe=({mainCam:e,resolutionMainCam:t,sender:s,track:n},i)=>{switch(e){case De.PAUSE_MAIN_CAM:return((e,t)=>Ve({sender:e,maxBitrate:We,onSetParameters:t,scaleResolutionDownBy:200}))(s,i);case De.RESUME_MAIN_CAM:return((e,t)=>Ve({sender:e,maxBitrate:Le,onSetParameters:t,scaleResolutionDownBy:1}))(s,i);case De.MAX_MAIN_CAM_RESOLUTION:if(t)return je(s,{track:n,resolution:t},i)}return Promise.resolve({isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}})};e.causes=fe,e.default=class{constructor({JsSIP:e}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger(f,void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const n=this.incomingSession,i=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(_,i),t(n.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if(e===Oe){this.incomingSession=t;const e=this.remoteCallerData;t.on(te,(({originator:t})=>{this.removeIncomingSession(),t!==ye?this._uaEvents.trigger(m,e):this._uaEvents.trigger(S,e)})),this._uaEvents.trigger(g,e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:n=!1,sipServerUrl:i,sipWebSocketServerURL:r,remoteAddress:o,extraHeaders:a=[],sdpSemantics:d="plan-b",sessionTimers:h=!1,registerExpires:l=300,connectionRecoveryMinInterval:u=2,connectionRecoveryMaxInterval:g=6,userAgent:_})=>c(this,void 0,void 0,(function*(){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!s)throw new Error("password is required for authorized connection");let c;this._connectionConfiguration={sipServerUrl:i,displayName:e,register:n,user:t,password:s},this._init({sipServerUrl:i,sipWebSocketServerURL:r}),c=n&&t?t.trim():we();const m={password:s,register:n,display_name:Ae(e),user_agent:_,sdp_semantics:d,sockets:[this.socket],uri:this.getSipServerUrl(c),session_timers:h,register_expires:l,connection_recovery_min_interval:u,connection_recovery_max_interval:g};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!m.register,this.ua=new this.JsSIP.UA(m),this._uaEvents.eachTriggers(((e,t)=>{const s=ae.find((e=>e===t));s&&this.ua.on(s,e)}));const S=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(o),f=[...S,...a];return this.ua.registrator().setExtraHeaders(f),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{i(),e(this.ua)},n=e=>{i(),t(e)},i=()=>{this.off(p,s),this.off(T,n),this.off(E,s),this.off(C,n)};(()=>{this.isRegisterConfig?(this.on(p,s),this.on(T,n)):this.on(E,s),this.on(C,n)})(),this.on(v,this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,n)=>{let i=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(i=this.ua.set("display_name",Ae(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=i||r;r&&this.isRegisterConfig?this.register().then((()=>s(o))).catch(n):o?s(o):n(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>c(this,void 0,void 0,(function*(){this.off(v,this.handleNewRTCSession);const e=new Promise((e=>{this.once(C,(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(C,void 0)):this._uaEvents.trigger(C,void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:n,iceServers:i,videoMode:r,audioMode:o,degradationPreference:a,offerToReceiveAudio:c=!0,offerToReceiveVideo:d=!0})=>new Promise(((h,l)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(h).catch(l),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Pe(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:n,videoMode:i,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const s=de.find((e=>e===t));s&&d.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const h=Pe(e,{videoMode:i,audioMode:r});d.answer({extraHeaders:s,videoMode:i,audioMode:r,degradationPreference:o,mediaStream:h,pcConfig:{iceServers:n}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const n=()=>{this.offSession(ee,a),this.offSession(Z,c)},i=()=>{this.offSession(te,r),this.offSession(Q,r)},r=e=>{n(),i(),s(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger(O,o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger(y,o),n(),i(),t(o)};(()=>{this.onSession(ee,a),this.onSession(Z,c)})(),(()=>{this.onSession(te,r),this.onSession(Q,r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{const n=this.session;n?(this.onceSession(se,(({originator:e})=>{e===ye&&t()})),n.sendDTMF(e,{duration:120,interToneGap:600})):s(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>c(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case Re:this._sessionEvents.trigger(M,void 0);break;case Me:this._sessionEvents.trigger(A,void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger(w,void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader(ve),s=e.getHeader(pe);if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger(D,e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(V,t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(F,t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(J,s)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger($,s)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger(z,void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger(G,void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const n={conference:e,participant:t,jwt:s};this._uaEvents.trigger(K,n)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger(U,t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(j,t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Y,t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(X,t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger(I,t)},this._triggerShareState=e=>{const t=e.getHeader(Te);this._sessionEvents.trigger(b,t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader(Ne),n=s===qe.ADMIN_SYNC_FORCED;if(t===De.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(B,{isSyncForced:n});else if(t===De.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(x,{isSyncForced:n});else if(t!==De.RESUME_MAIN_CAM&&t!==De.PAUSE_MAIN_CAM||!s){const s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger(k,{mainCam:t,resolutionMainCam:s})}else this._sessionEvents.trigger(H,{isSyncForced:n})},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC"),s=e.getHeader(Ne)===qe.ADMIN_SYNC_FORCED;t===Ue.ADMIN_START_MIC?this._sessionEvents.trigger(L,{isSyncForced:s}):t===Ue.ADMIN_STOP_MIC&&this._sessionEvents.trigger(W,{isSyncForced:s})},this._triggerUseLicense=e=>{const t=e.getHeader("X-WEBRTC-USE-LICENSE");this._sessionEvents.trigger(P,t)},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,n=s.getHeader("content-type");if(n)switch(n){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case Ee:this._triggerShareState(s);break;case Ce:this._triggerMainCamControl(s);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(s);break;case"application/vinteo.webrtc.uselic":this._triggerUseLicense(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;t===Oe&&this._sessionEvents.trigger(q,e),this._restoreSession()},this.JsSIP=e,this._sessionEvents=new r.default(le),this._uaEvents=new r.default(he),this._cancelableConnect=new t.CancelableRequest(this._connect,{moduleName:xe,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new t.CancelableRequest(this._createUa,{moduleName:xe}),this._cancelableDisconnect=new t.CancelableRequest(this._disconnect,{moduleName:xe}),this._cancelableSet=new t.CancelableRequest(this._set,{moduleName:xe}),this._cancelableCall=new t.CancelableRequest(this._call,{moduleName:xe}),this._cancelableAnswer=new t.CancelableRequest(this._answer,{moduleName:xe}),this._cancelableSendDTMF=new t.CancelableRequest(this._sendDTMF,{moduleName:xe}),this.onSession(b,this._handleShareState),this.onSession(ne,this._handleNewInfo),this.on(R,this._handleSipEvent),this.onSession(te,this._handleEnded),this.onSession(Q,this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on(p,e),this.ua.on(T,t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on(N,e),this.ua.unregister()):t(new Error("ua is not registered"))}))}sendOptions(e,t,s){return this.ua?new Promise(((n,i)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{n()},failed:e=>{i(e)}}})}catch(e){i(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo(Ce,void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:n,degradationPreference:i}={}){const r=this.establishedSession;if(!r)return Promise.reject(new Error("No session established"));if(this._streamPresentationCurrent)return Promise.reject(new Error("Presentation is already started"));const o=Pe(e);this._streamPresentationCurrent=o;const a=s?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"],c=r.sendInfo(Ee,void 0,{extraHeaders:a}).then((()=>r.startPresentation(o,t,i))).then((()=>{const{connection:t}=this;if(!t||void 0===n)return;return((e,t,s)=>{const n=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return n?u(n,{maxBitrate:s}):Promise.resolve()})(t.getSenders(),e,n)})).then((()=>e)).catch((e=>{throw this._sessionEvents.trigger(re,e),e}));return this.promisePendingStartPresentation=c,c.finally((()=>{this.promisePendingStartPresentation=void 0}))}stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation||Promise.resolve();const n=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],i=this.establishedSession;return i&&t&&(s=s.then((()=>i.sendInfo(Ee,void 0,{extraHeaders:n}))).then((()=>i.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger(re,e),e}))),!i&&t&&this._sessionEvents.trigger(ie,t),this.promisePendingStopPresentation=s,s.finally((()=>{this._resetPresentation()}))}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}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)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,n,i,r;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(n=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===n?void 0:n.uri.host,incomingNumber:null===(r=null===(i=null==this?void 0:this.incomingSession)||void 0===i?void 0:i.remote_identity)||void 0===r?void 0:r.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.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}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,n=this._remoteStreams[s]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[s]=n,n}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,n)=>{if("audio"===s.kind)return;const i=s,r=e[n-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(i,o);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession(D)}waitSyncMediaState(){return this.waitSession(H)}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}sendMediaState({cam:e,mic:t},s={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const n=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},s),{extraHeaders:n}))}_sendRefusalToTurnOn(e,t={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const s=[`X-Vinteo-Media-Type: ${"mic"==e?0:1}`];return this.session.sendInfo("application/vinteo.webrtc.refusal",void 0,Object.assign(Object.assign({},t),{extraHeaders:s}))}sendRefusalToTurnOnMic(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",e)}sendRefusalToTurnOnCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",e)}},e.eventNames=ue,e.getCodecFromSender=a,e.hasCanceledCallError=(e=new Error)=>{const{originator:s,cause:n}=e;return!!t.isCanceledError(e)||"string"==typeof n&&(n===ge||n===_e||s===ye&&(n===Se||n===me))},e.resolveVideoSendingBalancer=(e,{ignoreForCodec:t,onSetParameters:s}={})=>{let n=()=>{};const i=i=>{n=()=>{const{mainCam:n,resolutionMainCam:r}=i,{connection:o}=e;o&&void 0!==n&&(({mainCam:e,resolutionMainCam:t,connection:s,onSetParameters:n,ignoreForCodec:i})=>{c(void 0,void 0,void 0,(function*(){const r=s.getSenders().find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)}));if(r&&r.track){if(i){const e=yield a(r);if(c=i,(o=e)&&c&&o.toLowerCase().includes(c.toLowerCase()))return}var o,c;Xe({mainCam:e,resolutionMainCam:t,sender:r,track:r.track},n)}}))})({mainCam:n,resolutionMainCam:r,connection:o,onSetParameters:s,ignoreForCodec:t})},n()};return{subscribe:()=>{e.onSession("main-cam-control",i)},unsubscribe:()=>{e.offSession("main-cam-control",i)},reBalance:n}},Object.defineProperty(e,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=index.umd.js.map