sip-connector 14.0.0 → 14.1.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.
@@ -0,0 +1 @@
1
+ "use strict";var Dt=Object.defineProperty;var Mt=(s,e,t)=>e in s?Dt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var r=(s,e,t)=>Mt(s,typeof e!="symbol"?e+"":e,t);const N=require("@krivega/cancelable-promise"),Ue=require("events-constructor"),J=require("repeated-calls"),X=require("debug"),pt="Connection Error",Be="Request Timeout",vt="SIP Failure Code",yt="Internal Error",bt="Busy",Q="Rejected",wt="Redirected",Ut="Unavailable",Fe="Not Found",Lt="Address Incomplete",Ht="Incompatible SDP",Wt="Missing SDP",qt="Authentication Error",xe="Terminated",kt="WebRTC Error",Ve="Canceled",Bt="No Answer",Ft="Expires",xt="No ACK",Vt="Dialog Error",Yt="User Denied Media Access",Ye="Bad Media Description",$t="RTP Timeout",Gt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Lt,AUTHENTICATION_ERROR:qt,BAD_MEDIA_DESCRIPTION:Ye,BUSY:bt,BYE:xe,CANCELED:Ve,CONNECTION_ERROR:pt,DIALOG_ERROR:Vt,EXPIRES:Ft,INCOMPATIBLE_SDP:Ht,INTERNAL_ERROR:yt,MISSING_SDP:Wt,NOT_FOUND:Fe,NO_ACK:xt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:Q,REQUEST_TIMEOUT:Be,RTP_TIMEOUT:$t,SIP_FAILURE_CODE:vt,UNAVAILABLE:Ut,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),z="incomingCall",j="declinedIncomingCall",K="failedIncomingCall",Z="terminatedIncomingCall",x="connecting",m="connected",C="disconnected",w="newRTCSession",D="registered",ee="unregistered",M="registrationFailed",$e="newMessage",te="sipEvent",ne="availableSecondRemoteStream",se="notAvailableSecondRemoteStream",ie="mustStopPresentation",U="shareState",re="enterRoom",oe="useLicense",ae="peerconnection:confirmed",ce="peerconnection:ontrack",L="channels",Ee="channels:notify",_e="ended:fromserver",le="main-cam-control",de="admin-stop-main-cam",he="admin-start-main-cam",Se="admin-stop-mic",Te="admin-start-mic",H="admin-force-sync-media-state",ue="participant:added-to-list-moderators",Ce="participant:removed-from-list-moderators",Ne="participant:move-request-to-stream",V="participant:move-request-to-spectators",Y="participant:move-request-to-participants",ge="participation:accepting-word-request",Ae="participation:cancelling-word-request",Re="webcast:started",Ie="webcast:stopped",fe="account:changed",Pe="account:deleted",Oe="conference:participant-token-issued",p="ended",Ge="sending",Je="reinvite",Xe="replaces",Qe="refer",ze="progress",je="accepted",W="confirmed",q="peerconnection",I="failed",Ke="muted",Ze="unmuted",me="newDTMF",De="newInfo",et="hold",tt="unhold",nt="update",st="sdp",it="icecandidate",rt="getusermediafailed",ot="peerconnection:createofferfailed",at="peerconnection:createanswerfailed",ct="peerconnection:setlocaldescriptionfailed",Et="peerconnection:setremotedescriptionfailed",_t="presentation:start",lt="presentation:started",dt="presentation:end",Me="presentation:ended",k="presentation:failed",ht="SPECTATOR",St="PARTICIPANT",Tt=1e6;var R=(s=>(s.LOCAL="local",s.REMOTE="remote",s.SYSTEM="system",s))(R||{});const Jt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:je,ACCOUNT_CHANGED:fe,ACCOUNT_DELETED:Pe,ADMIN_FORCE_SYNC_MEDIA_STATE:H,ADMIN_START_MAIN_CAM:he,ADMIN_START_MIC:Te,ADMIN_STOP_MAIN_CAM:de,ADMIN_STOP_MIC:Se,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,CHANNELS:L,CHANNELS_NOTIFY:Ee,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Oe,CONFIRMED:W,CONNECTED:m,CONNECTING:x,DECLINED_INCOMING_CALL:j,DISCONNECTED:C,ENDED:p,ENDED_FROM_SERVER:_e,ENTER_ROOM:re,FAILED:I,FAILED_INCOMING_CALL:K,GET_USER_MEDIA_FAILED:rt,HOLD:et,ICE_CANDIDATE:it,INCOMING_CALL:z,MAIN_CAM_CONTROL:le,MUST_STOP_PRESENTATION_EVENT:ie,MUTED:Ke,NEW_DTMF:me,NEW_INFO:De,NEW_MESSAGE:$e,NEW_RTC_SESSION:w,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:se,ONE_MEGABIT_IN_BITS:Tt,Originator:R,PARTICIPANT:St,PARTICIPANT_ADDED_TO_LIST_MODERATORS:ue,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:Y,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:V,PARTICIPANT_MOVE_REQUEST_TO_STREAM:Ne,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Ce,PARTICIPATION_ACCEPTING_WORD_REQUEST:ge,PARTICIPATION_CANCELLING_WORD_REQUEST:Ae,PEER_CONNECTION:q,PEER_CONNECTION_CONFIRMED:ae,PEER_CONNECTION_CREATE_ANSWER_FAILED:at,PEER_CONNECTION_CREATE_OFFER_FAILED:ot,PEER_CONNECTION_ONTRACK:ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ct,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:Et,PRESENTATION_END:dt,PRESENTATION_ENDED:Me,PRESENTATION_FAILED:k,PRESENTATION_START:_t,PRESENTATION_STARTED:lt,PROGRESS:ze,REFER:Qe,REGISTERED:D,REGISTRATION_FAILED:M,REINVITE:Je,REPLACES:Xe,SDP:st,SENDING:Ge,SHARE_STATE:U,SIP_EVENT:te,SPECTATOR:ht,TERMINATED_INCOMING_CALL:Z,UNHOLD:tt,UNMUTED:Ze,UNREGISTERED:ee,UPDATE:nt,USE_LICENSE:oe,WEBCAST_STARTED:Re,WEBCAST_STOPPED:Ie},Symbol.toStringTag,{value:"Module"})),ut=[z,j,Z,K,ge,Ae,Ne,Ee,Oe,fe,Pe,Re,Ie,ue,Ce],pe=[x,m,C,w,D,ee,M,$e,te],Ct=[ne,se,ie,U,re,oe,ae,ce,L,_e,le,he,de,Se,Te,H,V,Y],ve=[p,x,Ge,Je,Xe,Qe,ze,je,W,q,I,Ke,Ze,me,De,et,tt,nt,st,it,rt,ot,at,ct,Et,_t,lt,dt,Me,k],ye=[...pe,...ut],be=[...ve,...Ct],Xt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:be,SESSION_JSSIP_EVENT_NAMES:ve,SESSION_SYNTHETICS_EVENT_NAMES:Ct,UA_EVENT_NAMES:ye,UA_JSSIP_EVENT_NAMES:pe,UA_SYNTHETICS_EVENT_NAMES:ut},Symbol.toStringTag,{value:"Module"})),we="sip-connector",b=X(we),Qt=()=>{X.enable(we)},zt=()=>{X.enable(`-${we}`)},jt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),Kt=(s,e)=>{s.encodings===void 0&&(s.encodings=[]);for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},Nt=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,Zt=Nt(),en=(s,e)=>{if(Zt(s,e))return s},tn=(s,e)=>{const t=s.maxBitrate,n=en(e,t);return n!==void 0&&(s.maxBitrate=n),s},gt=1,nn=Nt(gt),sn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,gt);if(t!==void 0&&nn(t,e))return t},rn=(s,e)=>{const t=s.scaleResolutionDownBy,n=sn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},on=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return Kt(s,t),s.encodings.forEach((i,o)=>{const a=((e==null?void 0:e.encodings)??[])[o],c=a==null?void 0:a.maxBitrate,E=a==null?void 0:a.scaleResolutionDownBy;tn(i,c),rn(i,E)}),s},an=(s,e)=>{var t,n,i,o,a,c,E,_,h,S,l,T;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let d=0;d<(((i=s.codecs)==null?void 0:i.length)??0);d++)if(JSON.stringify(s.codecs[d])!==JSON.stringify(e.codecs[d]))return!0;if(((o=s.headerExtensions)==null?void 0:o.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let d=0;d<(((c=s.headerExtensions)==null?void 0:c.length)??0);d++)if(JSON.stringify(s.headerExtensions[d])!==JSON.stringify(e.headerExtensions[d]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((_=e.encodings)==null?void 0:_.length))return!0;for(let d=0;d<(s.encodings.length??0);d++)if(JSON.stringify(s.encodings[d])!==JSON.stringify(e.encodings[d]))return!0;return((h=s.rtcp)==null?void 0:h.cname)!==((S=e.rtcp)==null?void 0:S.cname)||((l=s.rtcp)==null?void 0:l.reducedSize)!==((T=e.rtcp)==null?void 0:T.reducedSize)||s.degradationPreference!==e.degradationPreference},At=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));on(t,e),jt(t,e);const i=an(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var f=(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))(f||{}),B=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(B||{}),F=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(F||{}),Rt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Rt||{}),It=(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))(It||{});const ft=async(s,e,t)=>{const{isChanged:n,parameters:i}=await At(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}},cn=s=>{const e=[];return s&&e.push(`X-Vinteo-Remote: ${s}`),e},En="content-type",_n="x-webrtc-enter-room",v="application/vinteo.webrtc.sharedesktop",ln="application/vinteo.webrtc.roomname",dn="application/vinteo.webrtc.channels",hn="application/vinteo.webrtc.mediastate",Sn="application/vinteo.webrtc.refusal",Le="application/vinteo.webrtc.maincam",Tn="application/vinteo.webrtc.mic",un="application/vinteo.webrtc.uselic",Cn="X-WEBRTC-USE-LICENSE",Nn="X-WEBRTC-PARTICIPANT-NAME",He="X-WEBRTC-INPUT-CHANNELS",We="X-WEBRTC-OUTPUT-CHANNELS",gn="X-WEBRTC-MAINCAM",An="X-WEBRTC-MIC",qe="X-WEBRTC-SYNC",Rn="X-WEBRTC-MAINCAM-RESOLUTION",In="X-WEBRTC-MEDIA-STATE",fn="X-Vinteo-Media-Type",Pn="X-Vinteo-MainCam-State",On="X-Vinteo-Mic-State",mn="application/vinteo.webrtc.partstate",Dn="X-WEBRTC-PARTSTATE",Mn="application/vinteo.webrtc.notify",pn="X-VINTEO-NOTIFY",P="x-webrtc-share-state",vn=`${P}: LETMESTARTPRESENTATION`,yn=`${P}: STOPPRESENTATION`,Pt="YOUCANRECEIVECONTENT",Ot="CONTENTEND",mt="YOUMUSTSTOPSENDCONTENT",bn=`${P}: ${mt}`,wn=`${P}: ${Pt}`,Un=`${P}: ${Ot}`,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)})},y=(s,{directionVideo:e,directionAudio: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"&&Wn(c,n),c};function qn(s){return e=>`sip:${e}@${s}`}const kn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,ke=s=>s.trim().replaceAll(" ","_"),Bn=kn(1e5,99999999),Fn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),xn="Error decline with 603",Vn=1006,Yn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Vn,$n=s=>s.message===xn,Gn=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Jn=async(s,e,t)=>{const n=Gn(s,e);if(n)return ft(n,{maxBitrate:t})},Xn=486,Qn=487,zn=3,jn=1,Kn=s=>s instanceof Object&&("originator"in s||"cause"in s),Zn=s=>{if(N.isCanceledError(s))return!0;if(!Kn(s))return!1;const{originator:e,cause:t}=s;return typeof t=="string"?t===Be||t===Q||e===R.LOCAL&&(t===Ve||t===xe):!1},es=s=>J.hasCanceledError(s),A="SipConnector",ts="channels",ns="WebcastStarted",ss="WebcastStopped",is="accountChanged",rs="accountDeleted",os="addedToListModerators",as="removedFromListModerators",cs="ParticipationRequestAccepted",Es="ParticipationRequestRejected",_s="ParticipantMovedToWebcast",ls="ConferenceParticipantTokenIssued";class ds{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,"rtcSession");r(this,"incomingRTCSession");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(x,void 0);try{await this.unregister()}catch(e){b("tryRegister",e)}return this.register()});r(this,"declineToIncomingCall",async({statusCode:e=Qn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingRTCSession"));return}const i=this.incomingRTCSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(j,o),t(i.terminate({status_code:e}))}));r(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Xn}));r(this,"removeIncomingSession",()=>{delete this.incomingRTCSession});r(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=zn}={})=>{const n=async()=>this._cancelableConnect.request(e),i=o=>{var _;const c=!!((_=this.ua)!=null&&_.isConnected())&&this.hasEqualConnectionConfiguration(e),E=!!o&&!Yn(o);return c||E};return this._cancelableConnectWithRepeatedCalls=J.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===R.REMOTE){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(I,i=>{this.removeIncomingSession(),i.originator===R.LOCAL?this._uaEvents.trigger(Z,n):this._uaEvents.trigger(K,n)}),this._uaEvents.trigger(z,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:_,userAgent:h,displayName:S="",register:l=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(l&&!e)throw new Error("user is required for authorized connection");if(l&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:S,register:l,user:e,password:t};const{configuration:d,helpers:u}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:S,register:l,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:_,userAgent:h});return this.getSipServerUrl=u.getSipServerUrl,this.socket=u.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!l,this.ua=this._createUa({...d,remoteAddress:o,extraHeaders:T}),this._uaEvents.eachTriggers((g,$)=>{const O=pe.find(G=>G===$);O&&this.ua&&this.ua.on(O,g)}),this.ua});r(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e?cn(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(D,i),this.on(M,o)):this.on(m,i),this.on(C,o)},c=()=>{this.off(D,i),this.off(M,o),this.off(m,i),this.off(C,o)};a(),this.on(w,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",ke(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(_=>{i(_)}):E?n(E):i(new Error("nothing changed"))}));r(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());r(this,"_disconnect",async()=>{this.off(w,this.handleNewRTCSession);const e=new Promise(t=>{this.once(C,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(C,void 0)):this._uaEvents.trigger(C,void 0),e});r(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:o,directionVideo:a,directionAudio:c,contentHint:E,offerToReceiveAudio:_=!0,offerToReceiveVideo:h=!0,sendEncodings:S,onAddedTransceiver:l})=>new Promise((T,d)=>{const{ua:u}=this;if(!u){d(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(T).catch(g=>{d(g)}),this.rtcSession=u.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:y(t,{directionVideo:a,directionAudio:c,contentHint:E}),eventHandlers:this._sessionEvents.triggers,directionVideo:a,directionAudio:c,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:_,offerToReceiveVideo:h},sendEncodings:S,onAddedTransceiver:l})}));r(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:o,directionAudio:a,offerToReceiveAudio:c,offerToReceiveVideo:E,contentHint:_,sendEncodings:h,onAddedTransceiver:S})=>new Promise((l,T)=>{if(!this.isAvailableIncomingCall){T(new Error("no incomingRTCSession"));return}this.rtcSession=this.incomingRTCSession,this.removeIncomingSession();const{rtcSession:d}=this;if(!d){T(new Error("No rtcSession established"));return}this._sessionEvents.eachTriggers((g,$)=>{const O=ve.find(G=>G===$);O&&d.on(O,g)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(l).catch(g=>{T(g)});const u=y(e,{directionVideo:o,directionAudio:a,contentHint:_});d.answer({extraHeaders:n,directionVideo:o,directionAudio:a,mediaStream:u,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:E},sendEncodings:h,onAddedTransceiver:S})}));r(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(q,h),this.onSession(W,S)},o=()=>{this.offSession(q,h),this.offSession(W,S)},a=()=>{this.onSession(I,E),this.onSession(p,E)},c=()=>{this.offSession(I,E),this.offSession(p,E)},E=l=>{o(),c(),n(l)};let _;const h=({peerconnection:l})=>{_=l,_.ontrack=T=>{this._sessionEvents.trigger(ce,_),e&&e(T)}},S=()=>{_&&this._sessionEvents.trigger(ae,_),o(),c(),t(_)};i(),a()}));r(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.rtcSession,this._remoteStreams={}});r(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{rtcSession:i}=this;if(!i){n(new Error("No rtcSession established"));return}this.onceSession(me,({originator:o})=>{o===R.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));r(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){b("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});r(this,"_handleShareState",e=>{switch(e){case Pt:{this._sessionEvents.trigger(ne,void 0);break}case Ot:{this._sessionEvents.trigger(se,void 0);break}case mt:{this._sessionEvents.trigger(ie,void 0);break}}});r(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(He),n=e.getHeader(We);if(t&&n){const i={inputChannels:t,outputChannels:n};this._sessionEvents.trigger(L,i)}});r(this,"_handleNotify",e=>{switch(e.cmd){case ts:{const t=e;this._triggerChannelsNotify(t);break}case ns:{const t=e;this._triggerWebcastStartedNotify(t);break}case ss:{const t=e;this._triggerWebcastStoppedNotify(t);break}case os:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case as:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case cs:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case Es:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case _s:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case is:{this._triggerAccountChangedNotify();break}case rs:{this._triggerAccountDeletedNotify();break}case ls:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:b("unknown cmd",e.cmd)}});r(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Ce,t)});r(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});r(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Re,n)});r(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ie,n)});r(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(fe,void 0)});r(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(Pe,void 0)});r(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Oe,i)});r(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this._uaEvents.trigger(Ee,i)});r(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ge,t)});r(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Ae,t)});r(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Ne,t)});r(this,"_triggerEnterRoom",e=>{const t=e.getHeader(_n),n=e.getHeader(Nn);this._sessionEvents.trigger(re,{room:t,participantName:n})});r(this,"_triggerShareState",e=>{const t=e.getHeader(P);this._sessionEvents.trigger(U,t)});r(this,"_maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(Dn);t===ht&&this._sessionEvents.trigger(V,void 0),t===St&&this._sessionEvents.trigger(Y,void 0)});r(this,"_triggerMainCamControl",e=>{const t=e.getHeader(gn),n=e.getHeader(qe),i=n===F.ADMIN_SYNC_FORCED;if(t===f.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(he,{isSyncForced:i});return}if(t===f.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(de,{isSyncForced:i});return}(t===f.RESUME_MAIN_CAM||t===f.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(H,{isSyncForced:i});const o=e.getHeader(Rn);this._sessionEvents.trigger(le,{mainCam:t,resolutionMainCam:o})});r(this,"_triggerMicControl",e=>{const t=e.getHeader(An),i=e.getHeader(qe)===F.ADMIN_SYNC_FORCED;t===B.ADMIN_START_MIC?this._sessionEvents.trigger(Te,{isSyncForced:i}):t===B.ADMIN_STOP_MIC&&this._sessionEvents.trigger(Se,{isSyncForced:i})});r(this,"_triggerUseLicense",e=>{const t=e.getHeader(Cn);this._sessionEvents.trigger(oe,t)});r(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,i=n.getHeader(En);if(i)switch(i){case ln:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case Mn:{this._maybeHandleNotify(n);break}case v:{this._triggerShareState(n);break}case Le:{this._triggerMainCamControl(n);break}case Tn:{this._triggerMicControl(n);break}case un:{this._triggerUseLicense(n);break}case mn:{this._maybeTriggerParticipantMoveRequest(n);break}}});r(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});r(this,"_maybeHandleNotify",e=>{const t=e.getHeader(pn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});r(this,"_handleEnded",e=>{const{originator:t}=e;t===R.REMOTE&&this._sessionEvents.trigger(_e,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new Ue(be),this._uaEvents=new Ue(ye),this._cancelableConnect=new N.CancelableRequest(this._connect,{moduleName:A,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new N.CancelableRequest(this._initUa,{moduleName:A}),this._cancelableDisconnect=new N.CancelableRequest(this._disconnect,{moduleName:A}),this._cancelableSet=new N.CancelableRequest(this._set,{moduleName:A}),this._cancelableCall=new N.CancelableRequest(this._call,{moduleName:A}),this._cancelableAnswer=new N.CancelableRequest(this._answer,{moduleName:A}),this._cancelableSendDTMF=new N.CancelableRequest(this._sendDTMF,{moduleName:A}),this.onSession(U,this._handleShareState),this.onSession(De,this._handleNewInfo),this.on(te,this._handleSipEvent),this.onSession(I,this._handleEnded),this.onSession(p,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(D,e),this.ua.on(M,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(ee,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:_}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),h=this._createUa({..._,remoteAddress:o,extraHeaders:a}),S=()=>{const T=new Error("Telephony is not available");E(T)};h.once(C,S);const l=()=>{h.removeAllListeners(),h.once(C,c),h.stop()};h.once(m,l),h.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=y(e,{contentHint:n});return this.rtcSession.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Hn];return this.rtcSession.sendInfo(Le,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if($n(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:jn}}){const o=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=J.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:_=2,connectionRecoveryMaxInterval:h=6,userAgent:S}){if(a&&!t)throw new Error("password is required for authorized connection");const l=a&&e?e.trim():`${Bn()}`,T=qn(o),d=T(l),u=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:d,display_name:ke(i),user_agent:S,sdp_semantics:"unified-plan",sockets:[u],session_timers:c,register_expires:E,connection_recovery_min_interval:_,connection_recovery_max_interval:h},helpers:{socket:u,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=Tt,isNeedReinvite:i=!0,isP2P:o=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:E}){const _=y(t,{contentHint:a});this._streamPresentationCurrent=_;const h=o?[wn]:[vn],S=e.sendInfo(v,void 0,{extraHeaders:h}).then(async()=>e.startPresentation(_,i,{sendEncodings:c,onAddedTransceiver:E})).then(async()=>{const{connection:l}=this;if(!l||n===void 0)return;const T=l.getSenders();await Jn(T,t,n)}).then(()=>t).catch(l=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(k,l),l});return this.promisePendingStartPresentation=S,S.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c}={},E){const _=this.establishedRTCSession;if(!_)throw new Error("No rtcSession established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(_),this._sendPresentationWithDuplicatedCalls({rtcSession:_,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c},options:E})}async sendMustStopPresentation(e){await e.sendInfo(v,void 0,{extraHeaders:[bn]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const i=e?[Un]:[yn],o=this.establishedRTCSession;return o&&t&&(n=n.then(async()=>o.sendInfo(v,void 0,{extraHeaders:i})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(k,a),a})),!o&&t&&this._sessionEvents.trigger(Me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:o,onAddedTransceiver:a}={}){const c=this.establishedRTCSession;if(!c)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(c,e,{isP2P:t,maxBitrate:n,contentHint:i,isNeedReinvite:!1,sendEncodings:o,onAddedTransceiver:a})}_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 Fn(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.rtcSession)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,i,o,a;return{displayName:(t=(e=this.incomingRTCSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(i=(n=this.incomingRTCSession)==null?void 0:n.remote_identity)==null?void 0:i.uri.host,incomingNumber:(a=(o=this.incomingRTCSession)==null?void 0:o.remote_identity)==null?void 0:a.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedRTCSession(){var e;return(e=this.rtcSession)!=null&&e.isEstablished()?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}_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(L)}async waitSyncMediaState(){return this.waitSession(H)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${He}: ${e}`,i=`${We}: ${t}`,o=[n,i];return this.rtcSession.sendInfo(dn,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${In}: currentstate`,o=`${Pn}: ${Number(e)}`,a=`${On}: ${Number(t)}`,c=[i,o,a];return this.rtcSession.sendInfo(hn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const c=[`${fn}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(Sn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}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})}}exports.BAD_MEDIA_DESCRIPTION=Ye;exports.EEventsMainCAM=f;exports.EEventsMic=B;exports.EEventsSyncMediaState=F;exports.EMimeTypesVideoCodecs=It;exports.EUseLicense=Rt;exports.NOT_FOUND=Fe;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=Y;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=V;exports.REJECTED=Q;exports.SESSION_EVENT_NAMES=be;exports.SipConnector=ds;exports.UA_EVENT_NAMES=ye;exports.causes=Gt;exports.constants=Jt;exports.disableDebug=zt;exports.enableDebug=Qt;exports.eventNames=Xt;exports.hasCanceledCallError=Zn;exports.hasCanceledStartPresentationError=es;exports.logger=b;exports.setEncodingsToSender=ft;exports.setParametersToSender=At;
@@ -1,7 +1,8 @@
1
1
  import { IncomingInfoEvent, IncomingRTCSessionEvent, IncomingRequest, OutgoingInfoEvent, RTCSession, RegisteredEvent, UA, UAConfigurationParams, URI, UnRegisteredEvent, WebSocketInterface } from '@krivega/jssip';
2
2
  import { TEventSession, TEventUA } from './eventNames';
3
3
  import { TContentHint, TCustomError, TJsSIP, TOnAddedTransceiver } from './types';
4
- export declare const hasCanceledCallError: (error?: TCustomError) => boolean;
4
+ export declare const hasCanceledCallError: (error: unknown) => boolean;
5
+ export declare const hasCanceledStartPresentationError: (error: unknown) => error is import('repeated-calls/utils').TCanceledError<unknown>;
5
6
  type TChannels = {
6
7
  inputChannels: string;
7
8
  outputChannels: string;
@@ -72,3 +72,8 @@ export declare const PRESENTATION_FAILED = "presentation:failed";
72
72
  export declare const SPECTATOR = "SPECTATOR";
73
73
  export declare const PARTICIPANT = "PARTICIPANT";
74
74
  export declare const ONE_MEGABIT_IN_BITS = 1000000;
75
+ export declare enum Originator {
76
+ LOCAL = "local",
77
+ REMOTE = "remote",
78
+ SYSTEM = "system"
79
+ }
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var k=(o,t,e)=>t in o?b(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>k(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./SipConnector-K7IHfEEm.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),F=require("node:events"),V=require("@krivega/jssip/lib/SIPMessage"),I=require("webrtc-mock"),C=require("events-constructor"),T=require("@krivega/jssip");class y extends V.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class z{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new C(g.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get remote_identity(){return this._remote_identity}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class x{constructor({track:t}={}){r(this,"dtmf",null);r(this,"track",null);r(this,"transport",null);r(this,"transform",null);r(this,"_parameters",{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}});r(this,"_parametersGets");this.track=t??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(t){this.track=t??null}async setParameters(t){if(t!==this._parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:e}=this._parameters;this._parameters={...this._parameters,...t,transactionId:`${Number(e)+1}`}}getParameters(){return this._parametersGets={...this._parameters},this._parametersGets}setStreams(){throw new Error("Method not implemented.")}}class U{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e=new x({track:t});return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function q(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const w=400,N="777",H=o=>o.getVideoTracks().length>0,a=class a extends z{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"answer",jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},w)}));this.url=e,this.initPeerconnection(n)}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(e){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(e)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=I.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(H(e)){const m=I.createVideoMediaStreamTrackMock();m.id="mainvideo1",i.push(m)}this._connection=new U(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},w)}connect(e){const n=q(e);setTimeout(()=>{this.url.includes(N)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:g.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},w)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let l=a;class Y{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const c="PASSWORD_CORRECT",f="PASSWORD_CORRECT_2",P="NAME_INCORRECT",u=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new l({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new C(g.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,d]=n.split("@"),m={...t,uri:new T.URI(e,i,d)};this.configuration=m,this._registrator=new Y}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},u):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(P)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},u)):!this._isRegistered&&e&&(t===c||t===f)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},u)):e&&t!==c&&t!==f&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},u)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let S=s;class j{constructor(t){r(this,"url");this.url=t}}class B extends F.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const M="remote",G=(o,t)=>{const e=new y(t),n={originator:M,request:e,info:new B("","")};o.newInfo(n)},K=(o,t)=>{const n={request:new y(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new l({originator:M}),d=new L("sip",t,n);i._remote_identity=new D(d,e),o.trigger("newRTCSession",{originator:M,session:i})},J=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:G,triggerNewSipEvent:K,triggerIncomingSession:$,triggerFailIncomingSession:J,WebSocketInterface:j,UA:S,C:{INVITE:"INVITE"}},_="user",h="displayName",p="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",X=new A.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:p,sipWebSocketServerURL:R},Q={...v},O={...v,user:_,password:c,register:!0},Z={...O,displayName:h},ee={...v,displayName:h,register:!1},E={session_timers:!1,sockets:[X],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},te={...E,password:c,uri:new T.URI("sip",_,p),display_name:"",register:!0},re={...E,password:c,uri:new T.URI("sip",_,p),display_name:h,register:!0},ne={...E,display_name:h,register:!1},oe={...E,display_name:"",register:!1},W="10.10.10.10",ie=[`X-Vinteo-Remote: ${W}`],se=()=>new g.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=N;exports.NAME_INCORRECT=P;exports.PASSWORD_CORRECT=c;exports.PASSWORD_CORRECT_2=f;exports.SIP_SERVER_URL=p;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=Z;exports.dataForConnectionWithoutAuthorization=ee;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Q;exports.displayName=h;exports.doMockSipConnector=se;exports.extraHeadersRemoteAddress=ie;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=te;exports.uaConfigurationWithAuthorizationWithDisplayName=re;exports.uaConfigurationWithoutAuthorization=ne;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=oe;exports.user=_;
1
+ "use strict";var b=Object.defineProperty;var k=(o,t,e)=>t in o?b(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>k(o,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./SipConnector-BUbfMgHs.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),F=require("node:events"),V=require("@krivega/jssip/lib/SIPMessage"),I=require("webrtc-mock"),C=require("events-constructor"),T=require("@krivega/jssip");class y extends V.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class z{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new C(g.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get remote_identity(){return this._remote_identity}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class x{constructor({track:t}={}){r(this,"dtmf",null);r(this,"track",null);r(this,"transport",null);r(this,"transform",null);r(this,"_parameters",{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}});r(this,"_parametersGets");this.track=t??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(t){this.track=t??null}async setParameters(t){if(t!==this._parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:e}=this._parameters;this._parameters={...this._parameters,...t,transactionId:`${Number(e)+1}`}}getParameters(){return this._parametersGets={...this._parameters},this._parametersGets}setStreams(){throw new Error("Method not implemented.")}}class U{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e=new x({track:t});return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function q(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const w=400,N="777",H=o=>o.getVideoTracks().length>0,a=class a extends z{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"answer",jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},w)}));this.url=e,this.initPeerconnection(n)}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(e){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(e)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=I.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(H(e)){const m=I.createVideoMediaStreamTrackMock();m.id="mainvideo1",i.push(m)}this._connection=new U(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},w)}connect(e){const n=q(e);setTimeout(()=>{this.url.includes(N)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:g.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},w)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let l=a;class Y{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const c="PASSWORD_CORRECT",f="PASSWORD_CORRECT_2",P="NAME_INCORRECT",u=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new l({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new C(g.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,d]=n.split("@"),m={...t,uri:new T.URI(e,i,d)};this.configuration=m,this._registrator=new Y}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},u):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(P)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},u)):!this._isRegistered&&e&&(t===c||t===f)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},u)):e&&t!==c&&t!==f&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},u)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let S=s;class j{constructor(t){r(this,"url");this.url=t}}class B extends F.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const M="remote",G=(o,t)=>{const e=new y(t),n={originator:M,request:e,info:new B("","")};o.newInfo(n)},K=(o,t)=>{const n={request:new y(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new l({originator:M}),d=new L("sip",t,n);i._remote_identity=new D(d,e),o.trigger("newRTCSession",{originator:M,session:i})},J=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:G,triggerNewSipEvent:K,triggerIncomingSession:$,triggerFailIncomingSession:J,WebSocketInterface:j,UA:S,C:{INVITE:"INVITE"}},_="user",h="displayName",p="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",X=new A.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:p,sipWebSocketServerURL:R},Q={...v},O={...v,user:_,password:c,register:!0},Z={...O,displayName:h},ee={...v,displayName:h,register:!1},E={session_timers:!1,sockets:[X],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},te={...E,password:c,uri:new T.URI("sip",_,p),display_name:"",register:!0},re={...E,password:c,uri:new T.URI("sip",_,p),display_name:h,register:!0},ne={...E,display_name:h,register:!1},oe={...E,display_name:"",register:!1},W="10.10.10.10",ie=[`X-Vinteo-Remote: ${W}`],se=()=>new g.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=N;exports.NAME_INCORRECT=P;exports.PASSWORD_CORRECT=c;exports.PASSWORD_CORRECT_2=f;exports.SIP_SERVER_URL=p;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=Z;exports.dataForConnectionWithoutAuthorization=ee;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Q;exports.displayName=h;exports.doMockSipConnector=se;exports.extraHeadersRemoteAddress=ie;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=te;exports.uaConfigurationWithAuthorizationWithDisplayName=re;exports.uaConfigurationWithoutAuthorization=ne;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=oe;exports.user=_;
package/dist/doMock.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var y = Object.defineProperty;
2
2
  var N = (o, t, e) => t in o ? y(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
3
  var r = (o, t, e) => N(o, typeof t != "symbol" ? t + "" : t, e);
4
- import { n as P, R as O, U as A, S as b } from "./SipConnector-Cc1z-VjV.js";
4
+ import { o as P, R as O, U as A, S as b } from "./SipConnector-BPIL3yLc.js";
5
5
  import k from "@krivega/jssip/lib/NameAddrHeader";
6
6
  import D from "@krivega/jssip/lib/URI";
7
7
  import { EventEmitter as L } from "node:events";
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var ne=Object.defineProperty;var te=(n,e,t)=>e in n?ne(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>te(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./SipConnector-K7IHfEEm.cjs"),se=require("sequent-promises"),oe=require("stack-promises"),re=require("@krivega/cancelable-promise"),ie=require("repeated-calls"),ce=require("ts-debounce"),ae=require("debug"),$=n=>{const{url:e,cause:t}=n;let s=e;return(t===o.BAD_MEDIA_DESCRIPTION||t===o.NOT_FOUND)&&(s=`${n.message.to.uri.user}@${n.message.to.uri.host}`),s};var j=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))(j||{});const ue=(n=new Error)=>{var r;const{cause:e,socket:t}=n;let s="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case o.BAD_MEDIA_DESCRIPTION:{s="BAD_MEDIA_ERROR";break}case o.NOT_FOUND:{s="NOT_FOUND_ERROR";break}default:t&&((r=t==null?void 0:t._ws)==null?void 0:r.readyState)===3?s="WS_CONNECTION_FAILED":$(n)&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},le=n=>{let e="";try{e=JSON.stringify(n)}catch(t){o.logger("failed to stringify message",t)}return e},de=(n=new Error)=>{const{code:e,cause:t,message:s}=n,r=$(n),i={code:"",cause:"",message:""};return typeof s=="object"&&s!==null?i.message=le(s):s&&(i.message=String(s)),r&&(i.link=r),e&&(i.code=e),t&&(i.cause=t),i},ge=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:j,getLinkError:$,getTypeFromError:ue,getValuesFromError:de},Symbol.toStringTag,{value:"Module"})),Se=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:s,isRegistered:r,isPresentationCall:i})=>{const c=[],u=t?"0":"1",l=s?"0":"1";return c.push(`X-Vinteo-Mic-State: ${u}`,`X-Vinteo-MainCam-State: ${l}`),r||c.push("X-Vinteo-Purgatory-Call: yes"),n&&c.push(`X-Vinteo-Session: ${n}`),i&&c.push("X-Vinteo-Presentation-Call: yes"),e&&c.push(`X-Vinteo-Remote: ${e}`),c},Ce="[@*!|]",fe="_",me=n=>{let e=n;return e=e.replaceAll(new RegExp(Ce,"g"),fe),e},he=({appName:n,appVersion:e,browserName:t,browserVersion:s})=>{const i=`${me(n)} ${e}`;return`ChromeNew - ${t?`${t} ${s}, ${i}`:i}`},Re=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:s,appName:r})=>n?he({appVersion:e,browserName:t,browserVersion:s,appName:r}):"Chrome",W="purgatory",w=n=>n===W,pe=n=>e=>[...e].map(s=>async()=>n(s)),Ee=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=pe(e)(n);return se.sequentPromises(r,t)},ye=n=>t=>(o.logger("onStartMainCam"),n.onSession("admin-start-main-cam",t)),Te=n=>t=>(o.logger("onStartMic"),n.onSession("admin-start-mic",t)),Me=n=>t=>(o.logger("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),be=n=>t=>(o.logger("onStopMic"),n.onSession("admin-stop-mic",t)),Ae=({sipConnector:n})=>{const e=(f,p)=>({isSyncForced:m=!1})=>{if(m){f();return}p()},t=ye(n),s=Me(n),r=Te(n),i=be(n);let c=()=>{},u=()=>{},l=()=>{},g=()=>{};const C=({onStartMainCamForced:f,onStartMainCamNotForced:p,onStopMainCamForced:m,onStopMainCamNotForced:h,onStartMicForced:E,onStartMicNotForced:y,onStopMicForced:T,onStopMicNotForced:M})=>{const _=e(f,p);c=t(_);const v=e(m,h);u=s(v);const O=e(E,y);l=r(O);const N=e(T,M);g=i(N)},S=()=>{c(),u(),l(),g()};return{start:f=>{C(f)},stop:()=>{S()}}},_e=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:W,createSyncMediaState:Ae,error:ge,getExtraHeaders:Se,getUserAgent:Re,hasPurgatory:w,sendDTMFAccumulated:Ee},Symbol.toStringTag,{value:"Module"})),ve=n=>[...n.keys()].map(e=>n.get(e)),Oe=(n,e)=>ve(n).find(t=>t.type===e),G=async n=>n.getStats().then(e=>{const t=Oe(e,"codec");return t==null?void 0:t.mimeType}),Ne=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),K=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Pe=1e6,R=n=>n*Pe,Y=R(.06),Be=R(4),De=n=>n<=64?Y:n<=128?R(.12):n<=256?R(.25):n<=384?R(.32):n<=426?R(.38):n<=640?R(.5):n<=848?R(.7):n<=1280?R(1):n<=1920?R(2):Be,we="av1",Ie=n=>K(n,we),Fe=.6,z=(n,e)=>Ie(e)?n*Fe:n,ke=n=>z(Y,n),Q=(n,e)=>{const t=De(n);return z(t,e)},Ue=1,J=({videoTrack:n,targetSize:e,codec:t})=>{const s=n.getSettings(),r=s.width,i=s.height,c=r/e.width,u=i/e.height,l=Math.max(c,u,Ue),g=Q(e.width,t);return{scaleResolutionDownBy:l,maxBitrate:g}},Z=oe.createStackPromises(),Ve=async()=>Z().catch(n=>{o.logger("videoSendingBalancer: error",n)}),Le=async n=>(Z.add(n),Ve()),H=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:s})=>Le(async()=>o.setEncodingsToSender(n,{scaleResolutionDownBy:e,maxBitrate:t},s)),xe=async({sender:n,codec:e},t)=>{const r=ke(e);return H({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},L=async({sender:n,videoTrack:e,codec:t},s)=>{const c=e.getSettings().width,u=Q(c,t);return H({sender:n,maxBitrate:u,onSetParameters:s,scaleResolutionDownBy:1})},$e=async({sender:n,videoTrack:e,resolution:t,codec:s},r)=>{const[i,c]=t.split("x"),{maxBitrate:u,scaleResolutionDownBy:l}=J({videoTrack:e,codec:s,targetSize:{width:Number(i),height:Number(c)}});return H({sender:n,maxBitrate:u,onSetParameters:r,scaleResolutionDownBy:l})},He=async({mainCam:n,resolutionMainCam:e,sender:t,videoTrack:s,codec:r},i)=>{switch(n){case o.EEventsMainCAM.PAUSE_MAIN_CAM:return xe({sender:t,codec:r},i);case o.EEventsMainCAM.RESUME_MAIN_CAM:return L({sender:t,videoTrack:s,codec:r},i);case o.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?$e({sender:t,videoTrack:s,codec:r,resolution:e},i):L({sender:t,videoTrack:s,codec:r},i);default:return L({sender:t,videoTrack:s,codec:r},i)}},q={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},X=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:s,ignoreForCodec:r})=>{const i=t.getSenders(),c=Ne(i);if(!(c!=null&&c.track))return q;const u=await G(c);return K(u,r)?q:He({mainCam:n,resolutionMainCam:e,sender:c,codec:u,videoTrack:c.track},s)},qe=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const s=async()=>{const{connection:l}=n;if(!l)throw new Error("connection is not exist");return X({connection:l,onSetParameters:t,ignoreForCodec:e})};let r=s;const i=async l=>(r=async()=>{const{mainCam:g,resolutionMainCam:C}=l,{connection:S}=n;if(!S)throw new Error("connection is not exist");return X({mainCam:g,resolutionMainCam:C,connection:S,onSetParameters:t,ignoreForCodec:e})},r());return{subscribe:()=>{n.onSession("main-cam-control",i)},unsubscribe:()=>{n.offSession("main-cam-control",i)},balanceByTrack:s,resetMainCamControl(){r=s},async reBalance(){return r()}}},Xe=n=>n.getVideoTracks()[0],B=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const s=t??[],r=Xe(n);return e.forEach((i,c)=>{const u=s[c]??{};u.active=!0,i.rid!==void 0&&(u.rid=i.rid),i.scalabilityMode!==void 0&&(u.scalabilityMode=i.scalabilityMode);const{maxBitrate:l,scaleResolutionDownBy:g}=J({videoTrack:r,targetSize:{width:i.width,height:i.height}});u.maxBitrate=l,u.scaleResolutionDownBy=g,s[c]=u}),s}return t},je=(n,e)=>n.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),We=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return je(s,r)},Ge=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const r=e.indexOf(t.mimeType),i=e.indexOf(s.mimeType),c=r===-1?Number.MAX_VALUE:r,u=i===-1?Number.MAX_VALUE:i;return c-u}),Ke=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),D=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async s=>{var r;try{if(typeof s.setCodecPreferences=="function"&&((r=s.sender.track)==null?void 0:r.kind)==="video"&&(e!==void 0&&(e==null?void 0:e.length)>0||t!==void 0&&(t==null?void 0:t.length)>0)){const i=We("video"),c=Ke(i,t),u=Ge(c,e);s.setCodecPreferences(u)}Object.keys(n).length>0&&await o.setParametersToSender(s.sender,n)}catch(i){o.logger("updateTransceiver error",i)}},x=n=>{if(!re.isCanceledError(n)&&!ie.hasCanceledError(n))throw n;return{isSuccessful:!1}},Ye=({kind:n,readyState:e})=>n==="video"&&e==="live",ze=new Set(["on","once","onceRace","wait","off","onSession","onceSession","onceRaceSession","waitSession","offSession","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class Qe{constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s}={}){a(this,"sipConnector");a(this,"preferredMimeTypesVideoCodecs");a(this,"excludeMimeTypesVideoCodecs");a(this,"on");a(this,"once");a(this,"onceRace");a(this,"wait");a(this,"off");a(this,"onSession");a(this,"onceSession");a(this,"onceRaceSession");a(this,"waitSession");a(this,"offSession");a(this,"sendDTMF");a(this,"hangUp");a(this,"declineToIncomingCall");a(this,"sendChannels");a(this,"checkTelephony");a(this,"waitChannels");a(this,"ping");a(this,"connection");a(this,"isConfigured");a(this,"isRegistered");a(this,"connectToServer",async e=>{const{userAgent:t,sipWebSocketServerURL:s,sipServerUrl:r,remoteAddress:i,displayName:c,name:u,password:l,isRegisteredUser:g,isDisconnectOnFail:C}=e;return o.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:s,sipServerUrl:r,remoteAddress:i,displayName:c,password:l,user:u,register:g}).then(S=>(o.logger("connectToServer then"),{ua:S,isSuccessful:!0})).catch(async S=>(o.logger("connectToServer catch: error",S),C===!0?this.sipConnector.disconnect().then(()=>x(S)).catch(()=>x(S)):x(S)))});a(this,"callToServer",async e=>{const{conference:t,mediaStream:s,extraHeaders:r,iceServers:i,contentHint:c,simulcastEncodings:u,degradationPreference:l,sendEncodings:g,offerToReceiveAudio:C,offerToReceiveVideo:S,directionVideo:I,directionAudio:F,setRemoteStreams:f,onBeforeProgressCall:p,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:E,onFailProgressCall:y,onFinishProgressCall:T,onEndedCall:M}=e,_=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:f}),v=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:_}),O=D({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("callToServer",e);const N=async()=>(o.logger("startCall"),this.sipConnector.call({mediaStream:s,extraHeaders:r,iceServers:i,contentHint:c,offerToReceiveAudio:C,offerToReceiveVideo:S,directionVideo:I,directionAudio:F,sendEncodings:B({mediaStream:s,simulcastEncodings:u,sendEncodings:g}),number:t,onAddedTransceiver:O,ontrack:v}));let b=!1,A;const P=(o.logger("subscribeEnterConference: onEnterConference",E),h??E?this.sipConnector.onSession("enterRoom",({room:d})=>{o.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),A=d,w(A)?h&&h():E&&E({isSuccessProgressCall:b})}):()=>{}),k=d=>(o.logger("onSuccess"),b=!0,_(),m&&m({isPurgatory:w(A)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),M&&M()}),d),U=d=>{throw o.logger("onFail"),y&&y(),P(),d},V=()=>{o.logger("onFinish"),T&&T()};return o.logger("onBeforeProgressCall"),p&&p(t),N().then(k).catch(d=>U(d)).finally(V)});a(this,"disconnectFromServer",async()=>this.sipConnector.disconnect().then(()=>(o.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(o.logger("disconnectFromServer: catch",e),{isSuccessful:!1})));a(this,"answerIncomingCall",async e=>{const{mediaStream:t,extraHeaders:s,iceServers:r,contentHint:i,simulcastEncodings:c,degradationPreference:u,sendEncodings:l,offerToReceiveAudio:g,offerToReceiveVideo:C,directionVideo:S,directionAudio:I,setRemoteStreams:F,onBeforeProgressCall:f,onSuccessProgressCall:p,onEnterPurgatory:m,onEnterConference:h,onFailProgressCall:E,onFinishProgressCall:y,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:F}),_=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:M}),v=D({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("answerIncomingCall",e);const O=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:s,iceServers:r,contentHint:i,offerToReceiveAudio:g,offerToReceiveVideo:C,directionVideo:S,directionAudio:I,sendEncodings:B({mediaStream:t,simulcastEncodings:c,sendEncodings:l}),onAddedTransceiver:v,ontrack:_}),N=()=>{const{remoteCallerData:d}=this.sipConnector;return d.incomingNumber};let b=!1,A;const P=(o.logger("subscribeEnterConference: onEnterConference",h),m??h?this.sipConnector.onSession("enterRoom",d=>{o.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),A=d,w(A)?m&&m():h&&h({isSuccessProgressCall:b})}):()=>{}),k=d=>(o.logger("onSuccess"),b=!0,M(),p&&p({isPurgatory:w(A)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),T&&T()}),d),U=d=>{throw o.logger("onFail"),E&&E(),P(),d},V=()=>{o.logger("onFinish"),y&&y()};if(o.logger("onBeforeProgressCall"),f){const d=N();f(d)}return O().then(k).catch(d=>U(d)).finally(V)});a(this,"updatePresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:u,preferredMimeTypesVideoCodecs:l,excludeMimeTypesVideoCodecs:g})=>{const C=D({degradationPreference:c},{preferredMimeTypesVideoCodecs:l,excludeMimeTypesVideoCodecs:g});return o.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:s,contentHint:r,sendEncodings:B({mediaStream:e,simulcastEncodings:i,sendEncodings:u}),onAddedTransceiver:C})});a(this,"startPresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:u,preferredMimeTypesVideoCodecs:l,excludeMimeTypesVideoCodecs:g},C)=>{const S=D({degradationPreference:c},{preferredMimeTypesVideoCodecs:l,excludeMimeTypesVideoCodecs:g});return o.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:s,contentHint:r,sendEncodings:B({mediaStream:e,simulcastEncodings:i,sendEncodings:u}),onAddedTransceiver:S},C)});a(this,"stopShareSipConnector",async({isP2P:e=!1}={})=>(o.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{o.logger(t)})));a(this,"sendRefusalToTurnOnMic",async()=>{if(this.sipConnector.isCallActive)return o.logger("sendRefusalToTurnOnMic"),this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{o.logger("sendRefusalToTurnOnMic: error",e)})});a(this,"sendRefusalToTurnOnCam",async()=>{if(this.sipConnector.isCallActive)return o.logger("sendRefusalToTurnOnCam"),this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{o.logger("sendRefusalToTurnOnCam: error",e)})});a(this,"sendMediaState",async({isEnabledCam:e,isEnabledMic:t})=>{if(this.sipConnector.isCallActive)return o.logger("sendMediaState"),this.sipConnector.sendMediaState({cam:e,mic:t})});a(this,"replaceMediaStream",async(e,{deleteExisting:t,addMissing:s,forceRenegotiation:r,contentHint:i,simulcastEncodings:c,degradationPreference:u,sendEncodings:l}={})=>{const g=D({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return o.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:s,forceRenegotiation:r,contentHint:i,sendEncodings:B({mediaStream:e,simulcastEncodings:c,sendEncodings:l}),onAddedTransceiver:g})});a(this,"askPermissionToEnableCam",async()=>{if(this.sipConnector.isCallActive)return o.logger("askPermissionToEnableCam"),this.sipConnector.askPermissionToEnableCam()});a(this,"resolveHandleReadyRemoteStreamsDebounced",({onReadyRemoteStreams:e})=>ce.debounce(()=>{const t=this.sipConnector.getRemoteStreams();o.logger("remoteStreams",t),t&&e(t)},200));a(this,"resolveHandleReadyRemoteStreams",({onReadyRemoteStreams:e})=>({track:t})=>{Ye(t)&&e()});a(this,"getRemoteStreams",()=>(o.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams()));a(this,"onUseLicense",e=>(o.logger("onUseLicense"),this.sipConnector.onSession("useLicense",e)));a(this,"onMustStopPresentation",e=>(o.logger("onMustStopPresentation"),this.sipConnector.onSession("mustStopPresentation",e)));a(this,"onMoveToSpectators",e=>(o.logger("onMoveToSpectators"),this.sipConnector.onSession(o.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,e)));a(this,"onMoveToParticipants",e=>(o.logger("onMoveToParticipants"),this.sipConnector.onSession(o.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,e)));return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.sipConnector=e,new Proxy(this,{get:(r,i,c)=>{if(typeof i=="string"&&ze.has(i)&&i in this.sipConnector){const l=Reflect.get(this.sipConnector,i,this.sipConnector);return typeof l=="function"?l.bind(this.sipConnector):l}const u=Reflect.get(r,i,c);return typeof u=="function"?u.bind(r):u}})}}exports.EEventsMainCAM=o.EEventsMainCAM;exports.EEventsMic=o.EEventsMic;exports.EEventsSyncMediaState=o.EEventsSyncMediaState;exports.EMimeTypesVideoCodecs=o.EMimeTypesVideoCodecs;exports.EUseLicense=o.EUseLicense;exports.SipConnector=o.SipConnector;exports.causes=o.causes;exports.constants=o.constants;exports.disableDebug=o.disableDebug;exports.enableDebug=o.enableDebug;exports.eventNames=o.eventNames;exports.hasCanceledCallError=o.hasCanceledCallError;exports.setParametersToSender=o.setParametersToSender;exports.debug=ae;exports.SipConnectorFacade=Qe;exports.getCodecFromSender=G;exports.resolveVideoSendingBalancer=qe;exports.tools=_e;
1
+ "use strict";var ne=Object.defineProperty;var te=(n,e,t)=>e in n?ne(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>te(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./SipConnector-BUbfMgHs.cjs"),se=require("sequent-promises"),re=require("stack-promises"),oe=require("@krivega/cancelable-promise"),ie=require("repeated-calls"),ce=require("ts-debounce"),ae=require("debug"),$=n=>{const{url:e,cause:t}=n;let s=e;return(t===r.BAD_MEDIA_DESCRIPTION||t===r.NOT_FOUND)&&(s=`${n.message.to.uri.user}@${n.message.to.uri.host}`),s};var j=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))(j||{});const le=(n=new Error)=>{var o;const{cause:e,socket:t}=n;let s="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case r.BAD_MEDIA_DESCRIPTION:{s="BAD_MEDIA_ERROR";break}case r.NOT_FOUND:{s="NOT_FOUND_ERROR";break}default:t&&((o=t==null?void 0:t._ws)==null?void 0:o.readyState)===3?s="WS_CONNECTION_FAILED":$(n)&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},ue=n=>{let e="";try{e=JSON.stringify(n)}catch(t){r.logger("failed to stringify message",t)}return e},de=(n=new Error)=>{const{code:e,cause:t,message:s}=n,o=$(n),i={code:"",cause:"",message:""};return typeof s=="object"&&s!==null?i.message=ue(s):s&&(i.message=String(s)),o&&(i.link=o),e&&(i.code=e),t&&(i.cause=t),i},ge=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:j,getLinkError:$,getTypeFromError:le,getValuesFromError:de},Symbol.toStringTag,{value:"Module"})),Se=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:s,isRegistered:o,isPresentationCall:i})=>{const c=[],l=t?"0":"1",u=s?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),o||c.push("X-Vinteo-Purgatory-Call: yes"),n&&c.push(`X-Vinteo-Session: ${n}`),i&&c.push("X-Vinteo-Presentation-Call: yes"),e&&c.push(`X-Vinteo-Remote: ${e}`),c},Ce="[@*!|]",fe="_",me=n=>{let e=n;return e=e.replaceAll(new RegExp(Ce,"g"),fe),e},he=({appName:n,appVersion:e,browserName:t,browserVersion:s})=>{const i=`${me(n)} ${e}`;return`ChromeNew - ${t?`${t} ${s}, ${i}`:i}`},Re=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:s,appName:o})=>n?he({appVersion:e,browserName:t,browserVersion:s,appName:o}):"Chrome",W="purgatory",w=n=>n===W,pe=n=>e=>[...e].map(s=>async()=>n(s)),Ee=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const o=pe(e)(n);return se.sequentPromises(o,t)},ye=n=>t=>(r.logger("onStartMainCam"),n.onSession("admin-start-main-cam",t)),Te=n=>t=>(r.logger("onStartMic"),n.onSession("admin-start-mic",t)),Me=n=>t=>(r.logger("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),be=n=>t=>(r.logger("onStopMic"),n.onSession("admin-stop-mic",t)),Ae=({sipConnector:n})=>{const e=(f,p)=>({isSyncForced:m=!1})=>{if(m){f();return}p()},t=ye(n),s=Me(n),o=Te(n),i=be(n);let c=()=>{},l=()=>{},u=()=>{},g=()=>{};const C=({onStartMainCamForced:f,onStartMainCamNotForced:p,onStopMainCamForced:m,onStopMainCamNotForced:h,onStartMicForced:E,onStartMicNotForced:y,onStopMicForced:T,onStopMicNotForced:M})=>{const _=e(f,p);c=t(_);const v=e(m,h);l=s(v);const O=e(E,y);u=o(O);const N=e(T,M);g=i(N)},S=()=>{c(),l(),u(),g()};return{start:f=>{C(f)},stop:()=>{S()}}},_e=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:W,createSyncMediaState:Ae,error:ge,getExtraHeaders:Se,getUserAgent:Re,hasPurgatory:w,sendDTMFAccumulated:Ee},Symbol.toStringTag,{value:"Module"})),ve=n=>[...n.keys()].map(e=>n.get(e)),Oe=(n,e)=>ve(n).find(t=>t.type===e),G=async n=>n.getStats().then(e=>{const t=Oe(e,"codec");return t==null?void 0:t.mimeType}),Ne=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),K=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Pe=1e6,R=n=>n*Pe,Y=R(.06),Be=R(4),De=n=>n<=64?Y:n<=128?R(.12):n<=256?R(.25):n<=384?R(.32):n<=426?R(.38):n<=640?R(.5):n<=848?R(.7):n<=1280?R(1):n<=1920?R(2):Be,we="av1",Ie=n=>K(n,we),Fe=.6,z=(n,e)=>Ie(e)?n*Fe:n,ke=n=>z(Y,n),Q=(n,e)=>{const t=De(n);return z(t,e)},Ue=1,J=({videoTrack:n,targetSize:e,codec:t})=>{const s=n.getSettings(),o=s.width,i=s.height,c=o/e.width,l=i/e.height,u=Math.max(c,l,Ue),g=Q(e.width,t);return{scaleResolutionDownBy:u,maxBitrate:g}},Z=re.createStackPromises(),Ve=async()=>Z().catch(n=>{r.logger("videoSendingBalancer: error",n)}),Le=async n=>(Z.add(n),Ve()),H=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:s})=>Le(async()=>r.setEncodingsToSender(n,{scaleResolutionDownBy:e,maxBitrate:t},s)),xe=async({sender:n,codec:e},t)=>{const o=ke(e);return H({sender:n,maxBitrate:o,onSetParameters:t,scaleResolutionDownBy:200})},L=async({sender:n,videoTrack:e,codec:t},s)=>{const c=e.getSettings().width,l=Q(c,t);return H({sender:n,maxBitrate:l,onSetParameters:s,scaleResolutionDownBy:1})},$e=async({sender:n,videoTrack:e,resolution:t,codec:s},o)=>{const[i,c]=t.split("x"),{maxBitrate:l,scaleResolutionDownBy:u}=J({videoTrack:e,codec:s,targetSize:{width:Number(i),height:Number(c)}});return H({sender:n,maxBitrate:l,onSetParameters:o,scaleResolutionDownBy:u})},He=async({mainCam:n,resolutionMainCam:e,sender:t,videoTrack:s,codec:o},i)=>{switch(n){case r.EEventsMainCAM.PAUSE_MAIN_CAM:return xe({sender:t,codec:o},i);case r.EEventsMainCAM.RESUME_MAIN_CAM:return L({sender:t,videoTrack:s,codec:o},i);case r.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?$e({sender:t,videoTrack:s,codec:o,resolution:e},i):L({sender:t,videoTrack:s,codec:o},i);default:return L({sender:t,videoTrack:s,codec:o},i)}},q={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},X=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:s,ignoreForCodec:o})=>{const i=t.getSenders(),c=Ne(i);if(!(c!=null&&c.track))return q;const l=await G(c);return K(l,o)?q:He({mainCam:n,resolutionMainCam:e,sender:c,codec:l,videoTrack:c.track},s)},qe=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const s=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return X({connection:u,onSetParameters:t,ignoreForCodec:e})};let o=s;const i=async u=>(o=async()=>{const{mainCam:g,resolutionMainCam:C}=u,{connection:S}=n;if(!S)throw new Error("connection is not exist");return X({mainCam:g,resolutionMainCam:C,connection:S,onSetParameters:t,ignoreForCodec:e})},o());return{subscribe:()=>{n.onSession("main-cam-control",i)},unsubscribe:()=>{n.offSession("main-cam-control",i)},balanceByTrack:s,resetMainCamControl(){o=s},async reBalance(){return o()}}},Xe=n=>n.getVideoTracks()[0],B=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const s=t??[],o=Xe(n);return e.forEach((i,c)=>{const l=s[c]??{};l.active=!0,i.rid!==void 0&&(l.rid=i.rid),i.scalabilityMode!==void 0&&(l.scalabilityMode=i.scalabilityMode);const{maxBitrate:u,scaleResolutionDownBy:g}=J({videoTrack:o,targetSize:{width:i.width,height:i.height}});l.maxBitrate=u,l.scaleResolutionDownBy=g,s[c]=l}),s}return t},je=(n,e)=>n.filter(s=>e.some(o=>o.clockRate===s.clockRate&&o.mimeType===s.mimeType&&o.channels===s.channels&&o.sdpFmtpLine===s.sdpFmtpLine)),We=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,o=t===null?[]:t.codecs;return je(s,o)},Ge=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const o=e.indexOf(t.mimeType),i=e.indexOf(s.mimeType),c=o===-1?Number.MAX_VALUE:o,l=i===-1?Number.MAX_VALUE:i;return c-l}),Ke=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),D=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async s=>{var o;try{if(typeof s.setCodecPreferences=="function"&&((o=s.sender.track)==null?void 0:o.kind)==="video"&&(e!==void 0&&(e==null?void 0:e.length)>0||t!==void 0&&(t==null?void 0:t.length)>0)){const i=We("video"),c=Ke(i,t),l=Ge(c,e);s.setCodecPreferences(l)}Object.keys(n).length>0&&await r.setParametersToSender(s.sender,n)}catch(i){r.logger("updateTransceiver error",i)}},x=n=>{if(!oe.isCanceledError(n)&&!ie.hasCanceledError(n))throw n;return{isSuccessful:!1}},Ye=({kind:n,readyState:e})=>n==="video"&&e==="live",ze=new Set(["on","once","onceRace","wait","off","onSession","onceSession","onceRaceSession","waitSession","offSession","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class Qe{constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s}={}){a(this,"sipConnector");a(this,"preferredMimeTypesVideoCodecs");a(this,"excludeMimeTypesVideoCodecs");a(this,"on");a(this,"once");a(this,"onceRace");a(this,"wait");a(this,"off");a(this,"onSession");a(this,"onceSession");a(this,"onceRaceSession");a(this,"waitSession");a(this,"offSession");a(this,"sendDTMF");a(this,"hangUp");a(this,"declineToIncomingCall");a(this,"sendChannels");a(this,"checkTelephony");a(this,"waitChannels");a(this,"ping");a(this,"connection");a(this,"isConfigured");a(this,"isRegistered");a(this,"connectToServer",async e=>{const{userAgent:t,sipWebSocketServerURL:s,sipServerUrl:o,remoteAddress:i,displayName:c,name:l,password:u,isRegisteredUser:g,isDisconnectOnFail:C}=e;return r.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:s,sipServerUrl:o,remoteAddress:i,displayName:c,password:u,user:l,register:g}).then(S=>(r.logger("connectToServer then"),{ua:S,isSuccessful:!0})).catch(async S=>(r.logger("connectToServer catch: error",S),C===!0?this.sipConnector.disconnect().then(()=>x(S)).catch(()=>x(S)):x(S)))});a(this,"callToServer",async e=>{const{conference:t,mediaStream:s,extraHeaders:o,iceServers:i,contentHint:c,simulcastEncodings:l,degradationPreference:u,sendEncodings:g,offerToReceiveAudio:C,offerToReceiveVideo:S,directionVideo:I,directionAudio:F,setRemoteStreams:f,onBeforeProgressCall:p,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:E,onFailProgressCall:y,onFinishProgressCall:T,onEndedCall:M}=e,_=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:f}),v=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:_}),O=D({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});r.logger("callToServer",e);const N=async()=>(r.logger("startCall"),this.sipConnector.call({mediaStream:s,extraHeaders:o,iceServers:i,contentHint:c,offerToReceiveAudio:C,offerToReceiveVideo:S,directionVideo:I,directionAudio:F,sendEncodings:B({mediaStream:s,simulcastEncodings:l,sendEncodings:g}),number:t,onAddedTransceiver:O,ontrack:v}));let b=!1,A;const P=(r.logger("subscribeEnterConference: onEnterConference",E),h??E?this.sipConnector.onSession("enterRoom",({room:d})=>{r.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),A=d,w(A)?h&&h():E&&E({isSuccessProgressCall:b})}):()=>{}),k=d=>(r.logger("onSuccess"),b=!0,_(),m&&m({isPurgatory:w(A)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),M&&M()}),d),U=d=>{throw r.logger("onFail"),y&&y(),P(),d},V=()=>{r.logger("onFinish"),T&&T()};return r.logger("onBeforeProgressCall"),p&&p(t),N().then(k).catch(d=>U(d)).finally(V)});a(this,"disconnectFromServer",async()=>this.sipConnector.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(r.logger("disconnectFromServer: catch",e),{isSuccessful:!1})));a(this,"answerIncomingCall",async e=>{const{mediaStream:t,extraHeaders:s,iceServers:o,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:g,offerToReceiveVideo:C,directionVideo:S,directionAudio:I,setRemoteStreams:F,onBeforeProgressCall:f,onSuccessProgressCall:p,onEnterPurgatory:m,onEnterConference:h,onFailProgressCall:E,onFinishProgressCall:y,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:F}),_=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:M}),v=D({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});r.logger("answerIncomingCall",e);const O=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:s,iceServers:o,contentHint:i,offerToReceiveAudio:g,offerToReceiveVideo:C,directionVideo:S,directionAudio:I,sendEncodings:B({mediaStream:t,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:v,ontrack:_}),N=()=>{const{remoteCallerData:d}=this.sipConnector;return d.incomingNumber};let b=!1,A;const P=(r.logger("subscribeEnterConference: onEnterConference",h),m??h?this.sipConnector.onSession("enterRoom",d=>{r.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),A=d,w(A)?m&&m():h&&h({isSuccessProgressCall:b})}):()=>{}),k=d=>(r.logger("onSuccess"),b=!0,M(),p&&p({isPurgatory:w(A)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),T&&T()}),d),U=d=>{throw r.logger("onFail"),E&&E(),P(),d},V=()=>{r.logger("onFinish"),y&&y()};if(r.logger("onBeforeProgressCall"),f){const d=N();f(d)}return O().then(k).catch(d=>U(d)).finally(V)});a(this,"updatePresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:o,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g})=>{const C=D({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return r.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:s,contentHint:o,sendEncodings:B({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:C})});a(this,"startPresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:o,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g},C)=>{const S=D({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return r.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:s,contentHint:o,sendEncodings:B({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:S},C)});a(this,"stopShareSipConnector",async({isP2P:e=!1}={})=>(r.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{r.logger(t)})));a(this,"sendRefusalToTurnOnMic",async()=>{if(this.sipConnector.isCallActive)return r.logger("sendRefusalToTurnOnMic"),this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{r.logger("sendRefusalToTurnOnMic: error",e)})});a(this,"sendRefusalToTurnOnCam",async()=>{if(this.sipConnector.isCallActive)return r.logger("sendRefusalToTurnOnCam"),this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{r.logger("sendRefusalToTurnOnCam: error",e)})});a(this,"sendMediaState",async({isEnabledCam:e,isEnabledMic:t})=>{if(this.sipConnector.isCallActive)return r.logger("sendMediaState"),this.sipConnector.sendMediaState({cam:e,mic:t})});a(this,"replaceMediaStream",async(e,{deleteExisting:t,addMissing:s,forceRenegotiation:o,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u}={})=>{const g=D({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return r.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:s,forceRenegotiation:o,contentHint:i,sendEncodings:B({mediaStream:e,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:g})});a(this,"askPermissionToEnableCam",async()=>{if(this.sipConnector.isCallActive)return r.logger("askPermissionToEnableCam"),this.sipConnector.askPermissionToEnableCam()});a(this,"resolveHandleReadyRemoteStreamsDebounced",({onReadyRemoteStreams:e})=>ce.debounce(()=>{const t=this.sipConnector.getRemoteStreams();r.logger("remoteStreams",t),t&&e(t)},200));a(this,"resolveHandleReadyRemoteStreams",({onReadyRemoteStreams:e})=>({track:t})=>{Ye(t)&&e()});a(this,"getRemoteStreams",()=>(r.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams()));a(this,"onUseLicense",e=>(r.logger("onUseLicense"),this.sipConnector.onSession("useLicense",e)));a(this,"onMustStopPresentation",e=>(r.logger("onMustStopPresentation"),this.sipConnector.onSession("mustStopPresentation",e)));a(this,"onMoveToSpectators",e=>(r.logger("onMoveToSpectators"),this.sipConnector.onSession(r.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,e)));a(this,"onMoveToParticipants",e=>(r.logger("onMoveToParticipants"),this.sipConnector.onSession(r.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,e)));return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.sipConnector=e,new Proxy(this,{get:(o,i,c)=>{if(typeof i=="string"&&ze.has(i)&&i in this.sipConnector){const u=Reflect.get(this.sipConnector,i,this.sipConnector);return typeof u=="function"?u.bind(this.sipConnector):u}const l=Reflect.get(o,i,c);return typeof l=="function"?l.bind(o):l}})}}exports.EEventsMainCAM=r.EEventsMainCAM;exports.EEventsMic=r.EEventsMic;exports.EEventsSyncMediaState=r.EEventsSyncMediaState;exports.EMimeTypesVideoCodecs=r.EMimeTypesVideoCodecs;exports.EUseLicense=r.EUseLicense;exports.SipConnector=r.SipConnector;exports.causes=r.causes;exports.constants=r.constants;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.eventNames=r.eventNames;exports.hasCanceledCallError=r.hasCanceledCallError;exports.hasCanceledStartPresentationError=r.hasCanceledStartPresentationError;exports.setParametersToSender=r.setParametersToSender;exports.debug=ae;exports.SipConnectorFacade=Qe;exports.getCodecFromSender=G;exports.resolveVideoSendingBalancer=qe;exports.tools=_e;
package/dist/index.d.ts CHANGED
@@ -7,5 +7,5 @@ export * as tools from './tools';
7
7
  export * from './types';
8
8
  export { default as getCodecFromSender } from './utils/getCodecFromSender';
9
9
  export { default as resolveVideoSendingBalancer } from './videoSendingBalancer';
10
- export { hasCanceledCallError, default as SipConnector } from './SipConnector';
10
+ export { hasCanceledCallError, hasCanceledStartPresentationError, default as SipConnector, } from './SipConnector';
11
11
  export { SipConnectorFacade } from './SipConnectorFacade';
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  var se = Object.defineProperty;
2
2
  var oe = (n, e, t) => e in n ? se(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
3
  var a = (n, e, t) => oe(n, typeof e != "symbol" ? e + "" : e, t);
4
- import { B as G, N as K, l as c, E as x, s as re, a as ie, P as ce, b as ae } from "./SipConnector-Cc1z-VjV.js";
5
- import { i as Cn, j as mn, m as hn, k as Rn, S as gn, c as pn, d as yn, f as En, g as Tn, e as bn, h as Mn } from "./SipConnector-Cc1z-VjV.js";
4
+ import { B as G, N as K, l as c, E as x, s as re, a as ie, P as ce, b as ae } from "./SipConnector-BPIL3yLc.js";
5
+ import { j as Cn, k as mn, n as hn, m as Rn, S as gn, c as pn, d as yn, f as En, g as Tn, e as bn, h as Mn, i as _n } from "./SipConnector-BPIL3yLc.js";
6
6
  import { sequentPromises as ue } from "sequent-promises";
7
7
  import { createStackPromises as le } from "stack-promises";
8
8
  import { isCanceledError as de } from "@krivega/cancelable-promise";
9
9
  import { hasCanceledError as Se } from "repeated-calls";
10
10
  import { debounce as fe } from "ts-debounce";
11
- import { default as An } from "debug";
11
+ import { default as vn } from "debug";
12
12
  const H = (n) => {
13
13
  const { url: e, cause: t } = n;
14
14
  let s = e;
@@ -742,12 +742,13 @@ export {
742
742
  dn as SipConnectorFacade,
743
743
  pn as causes,
744
744
  yn as constants,
745
- An as debug,
745
+ vn as debug,
746
746
  En as disableDebug,
747
747
  Tn as enableDebug,
748
748
  bn as eventNames,
749
749
  De as getCodecFromSender,
750
750
  Mn as hasCanceledCallError,
751
+ _n as hasCanceledStartPresentationError,
751
752
  ln as resolveVideoSendingBalancer,
752
753
  ie as setParametersToSender,
753
754
  un as tools
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "14.0.0",
3
+ "version": "14.1.0",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -62,15 +62,15 @@
62
62
  "test:coverage": "yarn test:ci --coverage --reporters=default --reporters=jest-junit"
63
63
  },
64
64
  "dependencies": {
65
- "@krivega/cancelable-promise": "^1.1.3",
65
+ "@krivega/cancelable-promise": "^1.1.4",
66
66
  "@krivega/jssip": "^5.1.2",
67
- "debug": "^4.4.0",
67
+ "debug": "^4.4.1",
68
68
  "events-constructor": "^1.3.0",
69
- "repeated-calls": "^2.3.0",
69
+ "repeated-calls": "^2.3.3",
70
70
  "sequent-promises": "^2.0.1",
71
71
  "stack-promises": "^2.0.3",
72
72
  "ts-debounce": "^4.0.0",
73
- "webrtc-mock": "^1.1.6"
73
+ "webrtc-mock": "^1.1.7"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@babel/preset-typescript": "^7.26.0",
@@ -110,15 +110,15 @@
110
110
  "vite-tsconfig-paths": "^5.1.4"
111
111
  },
112
112
  "peerDependencies": {
113
- "@krivega/cancelable-promise": "^1.1.3",
113
+ "@krivega/cancelable-promise": "^1.1.4",
114
114
  "@krivega/jssip": "^5.1.2",
115
- "debug": "^4.4.0",
115
+ "debug": "^4.4.1",
116
116
  "events-constructor": "^1.3.0",
117
- "repeated-calls": "^2.2.1",
117
+ "repeated-calls": "^2.3.3",
118
118
  "sequent-promises": "^2.0.1",
119
119
  "stack-promises": "^2.0.3",
120
120
  "ts-debounce": "^4.0.0",
121
- "webrtc-mock": "^1.0.4"
121
+ "webrtc-mock": "^1.0.7"
122
122
  },
123
123
  "packageManager": "yarn@1.22.22",
124
124
  "main:src": "src/index.ts"
@@ -1 +0,0 @@
1
- "use strict";var Mt=Object.defineProperty;var pt=(s,e,t)=>e in s?Mt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var r=(s,e,t)=>pt(s,typeof e!="symbol"?e+"":e,t);const N=require("@krivega/cancelable-promise"),we=require("events-constructor"),Ue=require("repeated-calls"),J=require("debug"),vt="Connection Error",Fe="Request Timeout",yt="SIP Failure Code",bt="Internal Error",wt="Busy",X="Rejected",Ut="Redirected",Lt="Unavailable",xe="Not Found",Ht="Address Incomplete",Wt="Incompatible SDP",qt="Missing SDP",kt="Authentication Error",Ve="Terminated",Bt="WebRTC Error",Ye="Canceled",Ft="No Answer",xt="Expires",Vt="No ACK",Yt="Dialog Error",Gt="User Denied Media Access",Ge="Bad Media Description",$t="RTP Timeout",Jt=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Ht,AUTHENTICATION_ERROR:kt,BAD_MEDIA_DESCRIPTION:Ge,BUSY:wt,BYE:Ve,CANCELED:Ye,CONNECTION_ERROR:vt,DIALOG_ERROR:Yt,EXPIRES:xt,INCOMPATIBLE_SDP:Wt,INTERNAL_ERROR:bt,MISSING_SDP:qt,NOT_FOUND:xe,NO_ACK:Vt,NO_ANSWER:Ft,REDIRECTED:Ut,REJECTED:X,REQUEST_TIMEOUT:Fe,RTP_TIMEOUT:$t,SIP_FAILURE_CODE:yt,UNAVAILABLE:Lt,USER_DENIED_MEDIA_ACCESS:Gt,WEBRTC_ERROR:Bt},Symbol.toStringTag,{value:"Module"})),Q="incomingCall",z="declinedIncomingCall",j="failedIncomingCall",K="terminatedIncomingCall",F="connecting",O="connected",C="disconnected",b="newRTCSession",m="registered",Z="unregistered",D="registrationFailed",$e="newMessage",ee="sipEvent",te="availableSecondRemoteStream",ne="notAvailableSecondRemoteStream",se="mustStopPresentation",w="shareState",ie="enterRoom",re="useLicense",oe="peerconnection:confirmed",ae="peerconnection:ontrack",U="channels",ce="channels:notify",Ee="ended:fromserver",_e="main-cam-control",le="admin-stop-main-cam",de="admin-start-main-cam",he="admin-stop-mic",Se="admin-start-mic",L="admin-force-sync-media-state",Te="participant:added-to-list-moderators",ue="participant:removed-from-list-moderators",Ce="participant:move-request-to-stream",x="participant:move-request-to-spectators",V="participant:move-request-to-participants",Ne="participation:accepting-word-request",ge="participation:cancelling-word-request",Re="webcast:started",Ae="webcast:stopped",Ie="account:changed",fe="account:deleted",Pe="conference:participant-token-issued",M="ended",Je="sending",Xe="reinvite",Qe="replaces",ze="refer",je="progress",Ke="accepted",H="confirmed",W="peerconnection",A="failed",Ze="muted",et="unmuted",Oe="newDTMF",me="newInfo",tt="hold",nt="unhold",st="update",it="sdp",rt="icecandidate",ot="getusermediafailed",at="peerconnection:createofferfailed",ct="peerconnection:createanswerfailed",Et="peerconnection:setlocaldescriptionfailed",_t="peerconnection:setremotedescriptionfailed",lt="presentation:start",dt="presentation:started",ht="presentation:end",De="presentation:ended",q="presentation:failed",St="SPECTATOR",Tt="PARTICIPANT",ut=1e6,Xt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Ke,ACCOUNT_CHANGED:Ie,ACCOUNT_DELETED:fe,ADMIN_FORCE_SYNC_MEDIA_STATE:L,ADMIN_START_MAIN_CAM:de,ADMIN_START_MIC:Se,ADMIN_STOP_MAIN_CAM:le,ADMIN_STOP_MIC:he,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:te,CHANNELS:U,CHANNELS_NOTIFY:ce,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Pe,CONFIRMED:H,CONNECTED:O,CONNECTING:F,DECLINED_INCOMING_CALL:z,DISCONNECTED:C,ENDED:M,ENDED_FROM_SERVER:Ee,ENTER_ROOM:ie,FAILED:A,FAILED_INCOMING_CALL:j,GET_USER_MEDIA_FAILED:ot,HOLD:tt,ICE_CANDIDATE:rt,INCOMING_CALL:Q,MAIN_CAM_CONTROL:_e,MUST_STOP_PRESENTATION_EVENT:se,MUTED:Ze,NEW_DTMF:Oe,NEW_INFO:me,NEW_MESSAGE:$e,NEW_RTC_SESSION:b,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,ONE_MEGABIT_IN_BITS:ut,PARTICIPANT:Tt,PARTICIPANT_ADDED_TO_LIST_MODERATORS:Te,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:x,PARTICIPANT_MOVE_REQUEST_TO_STREAM:Ce,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:ue,PARTICIPATION_ACCEPTING_WORD_REQUEST:Ne,PARTICIPATION_CANCELLING_WORD_REQUEST:ge,PEER_CONNECTION:W,PEER_CONNECTION_CONFIRMED:oe,PEER_CONNECTION_CREATE_ANSWER_FAILED:ct,PEER_CONNECTION_CREATE_OFFER_FAILED:at,PEER_CONNECTION_ONTRACK:ae,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:Et,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:_t,PRESENTATION_END:ht,PRESENTATION_ENDED:De,PRESENTATION_FAILED:q,PRESENTATION_START:lt,PRESENTATION_STARTED:dt,PROGRESS:je,REFER:ze,REGISTERED:m,REGISTRATION_FAILED:D,REINVITE:Xe,REPLACES:Qe,SDP:it,SENDING:Je,SHARE_STATE:w,SIP_EVENT:ee,SPECTATOR:St,TERMINATED_INCOMING_CALL:K,UNHOLD:nt,UNMUTED:et,UNREGISTERED:Z,UPDATE:st,USE_LICENSE:re,WEBCAST_STARTED:Re,WEBCAST_STOPPED:Ae},Symbol.toStringTag,{value:"Module"})),Ct=[Q,z,K,j,Ne,ge,Ce,ce,Pe,Ie,fe,Re,Ae,Te,ue],Me=[F,O,C,b,m,Z,D,$e,ee],Nt=[te,ne,se,w,ie,re,oe,ae,U,Ee,_e,de,le,he,Se,L,x,V],pe=[M,F,Je,Xe,Qe,ze,je,Ke,H,W,A,Ze,et,Oe,me,tt,nt,st,it,rt,ot,at,ct,Et,_t,lt,dt,ht,De,q],ve=[...Me,...Ct],ye=[...pe,...Nt],Qt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:ye,SESSION_JSSIP_EVENT_NAMES:pe,SESSION_SYNTHETICS_EVENT_NAMES:Nt,UA_EVENT_NAMES:ve,UA_JSSIP_EVENT_NAMES:Me,UA_SYNTHETICS_EVENT_NAMES:Ct},Symbol.toStringTag,{value:"Module"})),be="sip-connector",y=J(be),zt=()=>{J.enable(be)},jt=()=>{J.enable(`-${be}`)},Kt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),Zt=(s,e)=>{s.encodings===void 0&&(s.encodings=[]);for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},gt=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,en=gt(),tn=(s,e)=>{if(en(s,e))return s},nn=(s,e)=>{const t=s.maxBitrate,n=tn(e,t);return n!==void 0&&(s.maxBitrate=n),s},Rt=1,sn=gt(Rt),rn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,Rt);if(t!==void 0&&sn(t,e))return t},on=(s,e)=>{const t=s.scaleResolutionDownBy,n=rn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},an=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return Zt(s,t),s.encodings.forEach((i,o)=>{const a=((e==null?void 0:e.encodings)??[])[o],c=a==null?void 0:a.maxBitrate,E=a==null?void 0:a.scaleResolutionDownBy;nn(i,c),on(i,E)}),s},cn=(s,e)=>{var t,n,i,o,a,c,E,_,h,S,l,T;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let d=0;d<(((i=s.codecs)==null?void 0:i.length)??0);d++)if(JSON.stringify(s.codecs[d])!==JSON.stringify(e.codecs[d]))return!0;if(((o=s.headerExtensions)==null?void 0:o.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let d=0;d<(((c=s.headerExtensions)==null?void 0:c.length)??0);d++)if(JSON.stringify(s.headerExtensions[d])!==JSON.stringify(e.headerExtensions[d]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((_=e.encodings)==null?void 0:_.length))return!0;for(let d=0;d<(s.encodings.length??0);d++)if(JSON.stringify(s.encodings[d])!==JSON.stringify(e.encodings[d]))return!0;return((h=s.rtcp)==null?void 0:h.cname)!==((S=e.rtcp)==null?void 0:S.cname)||((l=s.rtcp)==null?void 0:l.reducedSize)!==((T=e.rtcp)==null?void 0:T.reducedSize)||s.degradationPreference!==e.degradationPreference},At=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));an(t,e),Kt(t,e);const i=cn(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var I=(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))(I||{}),k=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(k||{}),B=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(B||{}),It=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(It||{}),ft=(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))(ft||{});const Pt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await At(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}},En=s=>{const e=[];return s&&e.push(`X-Vinteo-Remote: ${s}`),e},_n="content-type",ln="x-webrtc-enter-room",p="application/vinteo.webrtc.sharedesktop",dn="application/vinteo.webrtc.roomname",hn="application/vinteo.webrtc.channels",Sn="application/vinteo.webrtc.mediastate",Tn="application/vinteo.webrtc.refusal",Le="application/vinteo.webrtc.maincam",un="application/vinteo.webrtc.mic",Cn="application/vinteo.webrtc.uselic",Nn="X-WEBRTC-USE-LICENSE",gn="X-WEBRTC-PARTICIPANT-NAME",He="X-WEBRTC-INPUT-CHANNELS",We="X-WEBRTC-OUTPUT-CHANNELS",Rn="X-WEBRTC-MAINCAM",An="X-WEBRTC-MIC",qe="X-WEBRTC-SYNC",In="X-WEBRTC-MAINCAM-RESOLUTION",fn="X-WEBRTC-MEDIA-STATE",Pn="X-Vinteo-Media-Type",On="X-Vinteo-MainCam-State",mn="X-Vinteo-Mic-State",Dn="application/vinteo.webrtc.partstate",Mn="X-WEBRTC-PARTSTATE",pn="application/vinteo.webrtc.notify",vn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",yn=`${f}: LETMESTARTPRESENTATION`,bn=`${f}: STOPPRESENTATION`,Ot="YOUCANRECEIVECONTENT",mt="CONTENTEND",Dt="YOUMUSTSTOPSENDCONTENT",wn=`${f}: ${Dt}`,Un=`${f}: ${Ot}`,Ln=`${f}: ${mt}`,Hn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Wn=`${Hn}: LETMESTARTMAINCAM`,qn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},v=(s,{directionVideo:e,directionAudio: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"&&qn(c,n),c};function kn(s){return e=>`sip:${e}@${s}`}const Bn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,ke=s=>s.trim().replaceAll(" ","_"),Fn=Bn(1e5,99999999),xn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),Vn="Error decline with 603",Yn=1006,Gn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Yn,$n=s=>s.message===Vn,Jn=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Xn=async(s,e,t)=>{const n=Jn(s,e);if(n)return Pt(n,{maxBitrate:t})},Qn=486,zn=487,$="local",Be="remote",jn=3,Kn=1,Zn=(s=new Error)=>{const{originator:e,cause:t}=s;return N.isCanceledError(s)?!0:typeof t=="string"?t===Fe||t===X||e===$&&(t===Ye||t===Ve):!1},R="SipConnector",es="channels",ts="WebcastStarted",ns="WebcastStopped",ss="accountChanged",is="accountDeleted",rs="addedToListModerators",os="removedFromListModerators",as="ParticipationRequestAccepted",cs="ParticipationRequestRejected",Es="ParticipantMovedToWebcast",_s="ConferenceParticipantTokenIssued";class ls{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,"rtcSession");r(this,"incomingRTCSession");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(F,void 0);try{await this.unregister()}catch(e){y("tryRegister",e)}return this.register()});r(this,"declineToIncomingCall",async({statusCode:e=zn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingRTCSession"));return}const i=this.incomingRTCSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(z,o),t(i.terminate({status_code:e}))}));r(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Qn}));r(this,"removeIncomingSession",()=>{delete this.incomingRTCSession});r(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=jn}={})=>{const n=async()=>this._cancelableConnect.request(e),i=o=>{var _;const c=!!((_=this.ua)!=null&&_.isConnected())&&this.hasEqualConnectionConfiguration(e),E=!!o&&!Gn(o);return c||E};return this._cancelableConnectWithRepeatedCalls=Ue.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===Be){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(A,i=>{this.removeIncomingSession(),i.originator===$?this._uaEvents.trigger(K,n):this._uaEvents.trigger(j,n)}),this._uaEvents.trigger(Q,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:_,userAgent:h,displayName:S="",register:l=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(l&&!e)throw new Error("user is required for authorized connection");if(l&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:S,register:l,user:e,password:t};const{configuration:d,helpers:u}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:S,register:l,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:_,userAgent:h});return this.getSipServerUrl=u.getSipServerUrl,this.socket=u.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!l,this.ua=this._createUa({...d,remoteAddress:o,extraHeaders:T}),this._uaEvents.eachTriggers((g,Y)=>{const P=Me.find(G=>G===Y);P&&this.ua&&this.ua.on(P,g)}),this.ua});r(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e?En(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(D,o)):this.on(O,i),this.on(C,o)},c=()=>{this.off(m,i),this.off(D,o),this.off(O,i),this.off(C,o)};a(),this.on(b,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",ke(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(_=>{i(_)}):E?n(E):i(new Error("nothing changed"))}));r(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());r(this,"_disconnect",async()=>{this.off(b,this.handleNewRTCSession);const e=new Promise(t=>{this.once(C,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(C,void 0)):this._uaEvents.trigger(C,void 0),e});r(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:o,directionVideo:a,directionAudio:c,contentHint:E,offerToReceiveAudio:_=!0,offerToReceiveVideo:h=!0,sendEncodings:S,onAddedTransceiver:l})=>new Promise((T,d)=>{const{ua:u}=this;if(!u){d(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(T).catch(g=>{d(g)}),this.rtcSession=u.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:v(t,{directionVideo:a,directionAudio:c,contentHint:E}),eventHandlers:this._sessionEvents.triggers,directionVideo:a,directionAudio:c,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:_,offerToReceiveVideo:h},sendEncodings:S,onAddedTransceiver:l})}));r(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:o,directionAudio:a,offerToReceiveAudio:c,offerToReceiveVideo:E,contentHint:_,sendEncodings:h,onAddedTransceiver:S})=>new Promise((l,T)=>{if(!this.isAvailableIncomingCall){T(new Error("no incomingRTCSession"));return}this.rtcSession=this.incomingRTCSession,this.removeIncomingSession();const{rtcSession:d}=this;if(!d){T(new Error("No rtcSession established"));return}this._sessionEvents.eachTriggers((g,Y)=>{const P=pe.find(G=>G===Y);P&&d.on(P,g)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(l).catch(g=>{T(g)});const u=v(e,{directionVideo:o,directionAudio:a,contentHint:_});d.answer({extraHeaders:n,directionVideo:o,directionAudio:a,mediaStream:u,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:E},sendEncodings:h,onAddedTransceiver:S})}));r(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(W,h),this.onSession(H,S)},o=()=>{this.offSession(W,h),this.offSession(H,S)},a=()=>{this.onSession(A,E),this.onSession(M,E)},c=()=>{this.offSession(A,E),this.offSession(M,E)},E=l=>{o(),c(),n(l)};let _;const h=({peerconnection:l})=>{_=l,_.ontrack=T=>{this._sessionEvents.trigger(ae,_),e&&e(T)}},S=()=>{_&&this._sessionEvents.trigger(oe,_),o(),c(),t(_)};i(),a()}));r(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.rtcSession,this._remoteStreams={}});r(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{rtcSession:i}=this;if(!i){n(new Error("No rtcSession established"));return}this.onceSession(Oe,({originator:o})=>{o===$&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));r(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){y("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});r(this,"_handleShareState",e=>{switch(e){case Ot:{this._sessionEvents.trigger(te,void 0);break}case mt:{this._sessionEvents.trigger(ne,void 0);break}case Dt:{this._sessionEvents.trigger(se,void 0);break}}});r(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(He),n=e.getHeader(We);if(t&&n){const i={inputChannels:t,outputChannels:n};this._sessionEvents.trigger(U,i)}});r(this,"_handleNotify",e=>{switch(e.cmd){case es:{const t=e;this._triggerChannelsNotify(t);break}case ts:{const t=e;this._triggerWebcastStartedNotify(t);break}case ns:{const t=e;this._triggerWebcastStoppedNotify(t);break}case rs:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case os:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case as:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case cs:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case Es:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case ss:{this._triggerAccountChangedNotify();break}case is:{this._triggerAccountDeletedNotify();break}case _s:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:y("unknown cmd",e.cmd)}});r(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});r(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Te,t)});r(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Re,n)});r(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ae,n)});r(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ie,void 0)});r(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(fe,void 0)});r(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Pe,i)});r(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this._uaEvents.trigger(ce,i)});r(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Ne,t)});r(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ge,t)});r(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Ce,t)});r(this,"_triggerEnterRoom",e=>{const t=e.getHeader(ln),n=e.getHeader(gn);this._sessionEvents.trigger(ie,{room:t,participantName:n})});r(this,"_triggerShareState",e=>{const t=e.getHeader(f);this._sessionEvents.trigger(w,t)});r(this,"_maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(Mn);t===St&&this._sessionEvents.trigger(x,void 0),t===Tt&&this._sessionEvents.trigger(V,void 0)});r(this,"_triggerMainCamControl",e=>{const t=e.getHeader(Rn),n=e.getHeader(qe),i=n===B.ADMIN_SYNC_FORCED;if(t===I.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(de,{isSyncForced:i});return}if(t===I.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(le,{isSyncForced:i});return}(t===I.RESUME_MAIN_CAM||t===I.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(L,{isSyncForced:i});const o=e.getHeader(In);this._sessionEvents.trigger(_e,{mainCam:t,resolutionMainCam:o})});r(this,"_triggerMicControl",e=>{const t=e.getHeader(An),i=e.getHeader(qe)===B.ADMIN_SYNC_FORCED;t===k.ADMIN_START_MIC?this._sessionEvents.trigger(Se,{isSyncForced:i}):t===k.ADMIN_STOP_MIC&&this._sessionEvents.trigger(he,{isSyncForced:i})});r(this,"_triggerUseLicense",e=>{const t=e.getHeader(Nn);this._sessionEvents.trigger(re,t)});r(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,i=n.getHeader(_n);if(i)switch(i){case dn:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case pn:{this._maybeHandleNotify(n);break}case p:{this._triggerShareState(n);break}case Le:{this._triggerMainCamControl(n);break}case un:{this._triggerMicControl(n);break}case Cn:{this._triggerUseLicense(n);break}case Dn:{this._maybeTriggerParticipantMoveRequest(n);break}}});r(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});r(this,"_maybeHandleNotify",e=>{const t=e.getHeader(vn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});r(this,"_handleEnded",e=>{const{originator:t}=e;t===Be&&this._sessionEvents.trigger(Ee,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new we(ye),this._uaEvents=new we(ve),this._cancelableConnect=new N.CancelableRequest(this._connect,{moduleName:R,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new N.CancelableRequest(this._initUa,{moduleName:R}),this._cancelableDisconnect=new N.CancelableRequest(this._disconnect,{moduleName:R}),this._cancelableSet=new N.CancelableRequest(this._set,{moduleName:R}),this._cancelableCall=new N.CancelableRequest(this._call,{moduleName:R}),this._cancelableAnswer=new N.CancelableRequest(this._answer,{moduleName:R}),this._cancelableSendDTMF=new N.CancelableRequest(this._sendDTMF,{moduleName:R}),this.onSession(w,this._handleShareState),this.onSession(me,this._handleNewInfo),this.on(ee,this._handleSipEvent),this.onSession(A,this._handleEnded),this.onSession(M,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(m,e),this.ua.on(D,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"))})}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:_}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),h=this._createUa({..._,remoteAddress:o,extraHeaders:a}),S=()=>{const T=new Error("Telephony is not available");E(T)};h.once(C,S);const l=()=>{h.removeAllListeners(),h.once(C,c),h.stop()};h.once(O,l),h.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=v(e,{contentHint:n});return this.rtcSession.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Wn];return this.rtcSession.sendInfo(Le,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if($n(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:Kn}}){const o=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=Ue.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:_=2,connectionRecoveryMaxInterval:h=6,userAgent:S}){if(a&&!t)throw new Error("password is required for authorized connection");const l=a&&e?e.trim():`${Fn()}`,T=kn(o),d=T(l),u=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:d,display_name:ke(i),user_agent:S,sdp_semantics:"unified-plan",sockets:[u],session_timers:c,register_expires:E,connection_recovery_min_interval:_,connection_recovery_max_interval:h},helpers:{socket:u,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=ut,isNeedReinvite:i=!0,isP2P:o=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:E}){const _=v(t,{contentHint:a});this._streamPresentationCurrent=_;const h=o?[Un]:[yn],S=e.sendInfo(p,void 0,{extraHeaders:h}).then(async()=>e.startPresentation(_,i,{sendEncodings:c,onAddedTransceiver:E})).then(async()=>{const{connection:l}=this;if(!l||n===void 0)return;const T=l.getSenders();await Xn(T,t,n)}).then(()=>t).catch(l=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(q,l),l});return this.promisePendingStartPresentation=S,S.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c}={},E){const _=this.establishedRTCSession;if(!_)throw new Error("No rtcSession established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(_),this._sendPresentationWithDuplicatedCalls({rtcSession:_,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c},options:E})}async sendMustStopPresentation(e){await e.sendInfo(p,void 0,{extraHeaders:[wn]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const i=e?[Ln]:[bn],o=this.establishedRTCSession;return o&&t&&(n=n.then(async()=>o.sendInfo(p,void 0,{extraHeaders:i})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(q,a),a})),!o&&t&&this._sessionEvents.trigger(De,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:o,onAddedTransceiver:a}={}){const c=this.establishedRTCSession;if(!c)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(c,e,{isP2P:t,maxBitrate:n,contentHint:i,isNeedReinvite:!1,sendEncodings:o,onAddedTransceiver:a})}_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 xn(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.rtcSession)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,i,o,a;return{displayName:(t=(e=this.incomingRTCSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(i=(n=this.incomingRTCSession)==null?void 0:n.remote_identity)==null?void 0:i.uri.host,incomingNumber:(a=(o=this.incomingRTCSession)==null?void 0:o.remote_identity)==null?void 0:a.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedRTCSession(){var e;return(e=this.rtcSession)!=null&&e.isEstablished()?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}_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(U)}async waitSyncMediaState(){return this.waitSession(L)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${He}: ${e}`,i=`${We}: ${t}`,o=[n,i];return this.rtcSession.sendInfo(hn,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${fn}: currentstate`,o=`${On}: ${Number(e)}`,a=`${mn}: ${Number(t)}`,c=[i,o,a];return this.rtcSession.sendInfo(Sn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const c=[`${Pn}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(Tn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}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})}}exports.BAD_MEDIA_DESCRIPTION=Ge;exports.EEventsMainCAM=I;exports.EEventsMic=k;exports.EEventsSyncMediaState=B;exports.EMimeTypesVideoCodecs=ft;exports.EUseLicense=It;exports.NOT_FOUND=xe;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=x;exports.REJECTED=X;exports.SESSION_EVENT_NAMES=ye;exports.SipConnector=ls;exports.UA_EVENT_NAMES=ve;exports.causes=Jt;exports.constants=Xt;exports.disableDebug=jt;exports.enableDebug=zt;exports.eventNames=Qt;exports.hasCanceledCallError=Zn;exports.logger=y;exports.setEncodingsToSender=Pt;exports.setParametersToSender=At;