sip-connector 14.1.2-3 → 14.1.2-5

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.
@@ -201,7 +201,7 @@ const hs = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
201
201
  }, ls = () => {
202
202
  Y.enable(`-${De}`);
203
203
  }, Vt = (s, e) => (s.degradationPreference = e.degradationPreference, s), Yt = (s, e) => {
204
- s.encodings === void 0 && (s.encodings = []);
204
+ s.encodings ?? (s.encodings = []);
205
205
  for (let t = s.encodings.length; t < e; t += 1)
206
206
  s.encodings.push({});
207
207
  return s;
@@ -0,0 +1 @@
1
+ "use strict";var Ot=Object.defineProperty;var mt=(s,e,t)=>e in s?Ot(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 Mt=require("@krivega/cancelable-promise"),we=require("events-constructor"),G=require("repeated-calls"),J=require("debug"),Dt="Connection Error",ke="Request Timeout",pt="SIP Failure Code",vt="Internal Error",yt="Busy",X="Rejected",wt="Redirected",bt="Unavailable",Be="Not Found",Ut="Address Incomplete",Lt="Incompatible SDP",Ht="Missing SDP",Wt="Authentication Error",Fe="Terminated",kt="WebRTC Error",Q="Canceled",Bt="No Answer",Ft="Expires",xt="No ACK",Vt="Dialog Error",Yt="User Denied Media Access",xe="Bad Media Description",qt="RTP Timeout",$t=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Ut,AUTHENTICATION_ERROR:Wt,BAD_MEDIA_DESCRIPTION:xe,BUSY:yt,BYE:Fe,CANCELED:Q,CONNECTION_ERROR:Dt,DIALOG_ERROR:Vt,EXPIRES:Ft,INCOMPATIBLE_SDP:Lt,INTERNAL_ERROR:vt,MISSING_SDP:Ht,NOT_FOUND:Be,NO_ACK:xt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:X,REQUEST_TIMEOUT:ke,RTP_TIMEOUT:qt,SIP_FAILURE_CODE:pt,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),z="incomingCall",j="declinedIncomingCall",K="failedIncomingCall",Z="terminatedIncomingCall",F="connecting",P="connected",C="disconnected",y="newRTCSession",O="registered",ee="unregistered",m="registrationFailed",Ve="newMessage",te="sipEvent",ne="availableSecondRemoteStream",se="notAvailableSecondRemoteStream",ie="mustStopPresentation",w="shareState",oe="enterRoom",re="useLicense",ae="peerconnection:confirmed",ce="peerconnection:ontrack",b="channels",Ee="channels:notify",de="ended:fromserver",he="main-cam-control",Se="admin-stop-main-cam",Te="admin-start-main-cam",le="admin-stop-mic",ue="admin-start-mic",U="admin-force-sync-media-state",ge="participant:added-to-list-moderators",Ce="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",x="participant:move-request-to-spectators",V="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ae="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ie="account:changed",Pe="account:deleted",Oe="conference:participant-token-issued",M="ended",Ye="sending",qe="reinvite",$e="replaces",Ge="refer",Je="progress",Xe="accepted",L="confirmed",H="peerconnection",A="failed",Qe="muted",ze="unmuted",me="newDTMF",Me="newInfo",je="hold",Ke="unhold",Ze="update",et="sdp",tt="icecandidate",nt="getusermediafailed",st="peerconnection:createofferfailed",it="peerconnection:createanswerfailed",ot="peerconnection:setlocaldescriptionfailed",rt="peerconnection:setremotedescriptionfailed",at="presentation:start",ct="presentation:started",Et="presentation:end",De="presentation:ended",W="presentation:failed",dt="SPECTATOR",ht="PARTICIPANT",St=1e6;var _=(s=>(s.LOCAL="local",s.REMOTE="remote",s.SYSTEM="system",s))(_||{});const Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Xe,ACCOUNT_CHANGED:Ie,ACCOUNT_DELETED:Pe,ADMIN_FORCE_SYNC_MEDIA_STATE:U,ADMIN_START_MAIN_CAM:Te,ADMIN_START_MIC:ue,ADMIN_STOP_MAIN_CAM:Se,ADMIN_STOP_MIC:le,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,CHANNELS:b,CHANNELS_NOTIFY:Ee,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Oe,CONFIRMED:L,CONNECTED:P,CONNECTING:F,DECLINED_INCOMING_CALL:j,DISCONNECTED:C,ENDED:M,ENDED_FROM_SERVER:de,ENTER_ROOM:oe,FAILED:A,FAILED_INCOMING_CALL:K,GET_USER_MEDIA_FAILED:nt,HOLD:je,ICE_CANDIDATE:tt,INCOMING_CALL:z,MAIN_CAM_CONTROL:he,MUST_STOP_PRESENTATION_EVENT:ie,MUTED:Qe,NEW_DTMF:me,NEW_INFO:Me,NEW_MESSAGE:Ve,NEW_RTC_SESSION:y,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:se,ONE_MEGABIT_IN_BITS:St,Originator:_,PARTICIPANT:ht,PARTICIPANT_ADDED_TO_LIST_MODERATORS:ge,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:x,PARTICIPANT_MOVE_REQUEST_TO_STREAM:_e,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Ce,PARTICIPATION_ACCEPTING_WORD_REQUEST:Ne,PARTICIPATION_CANCELLING_WORD_REQUEST:Ae,PEER_CONNECTION:H,PEER_CONNECTION_CONFIRMED:ae,PEER_CONNECTION_CREATE_ANSWER_FAILED:it,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ot,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:rt,PRESENTATION_END:Et,PRESENTATION_ENDED:De,PRESENTATION_FAILED:W,PRESENTATION_START:at,PRESENTATION_STARTED:ct,PROGRESS:Je,REFER:Ge,REGISTERED:O,REGISTRATION_FAILED:m,REINVITE:qe,REPLACES:$e,SDP:et,SENDING:Ye,SHARE_STATE:w,SIP_EVENT:te,SPECTATOR:dt,TERMINATED_INCOMING_CALL:Z,UNHOLD:Ke,UNMUTED:ze,UNREGISTERED:ee,UPDATE:Ze,USE_LICENSE:re,WEBCAST_STARTED:Re,WEBCAST_STOPPED:fe},Symbol.toStringTag,{value:"Module"})),Tt=[z,j,Z,K,Ne,Ae,_e,Ee,Oe,Ie,Pe,Re,fe,ge,Ce],Y=[F,P,C,y,O,ee,m,Ve,te],lt=[ne,se,ie,w,oe,re,ae,ce,b,de,he,Te,Se,le,ue,U,x,V],pe=[M,F,Ye,qe,$e,Ge,Je,Xe,L,H,A,Qe,ze,me,Me,je,Ke,Ze,et,tt,nt,st,it,ot,rt,at,ct,Et,De,W],ut=[...Y,...Tt],ve=[...pe,...lt],Jt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:ve,SESSION_JSSIP_EVENT_NAMES:pe,SESSION_SYNTHETICS_EVENT_NAMES:lt,UA_EVENT_NAMES:ut,UA_JSSIP_EVENT_NAMES:Y,UA_SYNTHETICS_EVENT_NAMES:Tt},Symbol.toStringTag,{value:"Module"})),ye="sip-connector",v=J(ye),Xt=()=>{J.enable(ye)},Qt=()=>{J.enable(`-${ye}`)},zt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),jt=(s,e)=>{s.encodings??(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,Kt=gt(),Zt=(s,e)=>{if(Kt(s,e))return s},en=(s,e)=>{const t=s.maxBitrate,n=Zt(e,t);return n!==void 0&&(s.maxBitrate=n),s},Ct=1,tn=gt(Ct),nn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,Ct);if(t!==void 0&&tn(t,e))return t},sn=(s,e)=>{const t=s.scaleResolutionDownBy,n=nn(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 jt(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;en(i,c),sn(i,E)}),s},rn=(s,e)=>{var t,n,i,o,a,c,E,d,T,l,S,u;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let h=0;h<(((i=s.codecs)==null?void 0:i.length)??0);h++)if(JSON.stringify(s.codecs[h])!==JSON.stringify(e.codecs[h]))return!0;if(((o=s.headerExtensions)==null?void 0:o.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let h=0;h<(((c=s.headerExtensions)==null?void 0:c.length)??0);h++)if(JSON.stringify(s.headerExtensions[h])!==JSON.stringify(e.headerExtensions[h]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((d=e.encodings)==null?void 0:d.length))return!0;for(let h=0;h<(s.encodings.length??0);h++)if(JSON.stringify(s.encodings[h])!==JSON.stringify(e.encodings[h]))return!0;return((T=s.rtcp)==null?void 0:T.cname)!==((l=e.rtcp)==null?void 0:l.cname)||((S=s.rtcp)==null?void 0:S.reducedSize)!==((u=e.rtcp)==null?void 0:u.reducedSize)||s.degradationPreference!==e.degradationPreference},_t=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));on(t,e),zt(t,e);const i=rn(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var R=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(R||{}),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||{}),Nt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Nt||{}),At=(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))(At||{});const Rt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await _t(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}};function an(s){return e=>`sip:${e}@${s}`}const cn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,be=s=>s.trim().replaceAll(" ","_"),En=cn(1e5,99999999),dn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),hn=s=>{const e=[];return s!==void 0&&s!==""&&e.push(`X-Vinteo-Remote: ${s}`),e},Sn="content-type",Tn="x-webrtc-enter-room",D="application/vinteo.webrtc.sharedesktop",ln="application/vinteo.webrtc.roomname",un="application/vinteo.webrtc.channels",gn="application/vinteo.webrtc.mediastate",Cn="application/vinteo.webrtc.refusal",Ue="application/vinteo.webrtc.maincam",_n="application/vinteo.webrtc.mic",Nn="application/vinteo.webrtc.uselic",An="X-WEBRTC-USE-LICENSE",Rn="X-WEBRTC-PARTICIPANT-NAME",Le="X-WEBRTC-INPUT-CHANNELS",He="X-WEBRTC-OUTPUT-CHANNELS",fn="X-WEBRTC-MAINCAM",In="X-WEBRTC-MIC",We="X-WEBRTC-SYNC",Pn="X-WEBRTC-MAINCAM-RESOLUTION",On="X-WEBRTC-MEDIA-STATE",mn="X-Vinteo-Media-Type",Mn="X-Vinteo-MainCam-State",Dn="X-Vinteo-Mic-State",pn="application/vinteo.webrtc.partstate",vn="X-WEBRTC-PARTSTATE",yn="application/vinteo.webrtc.notify",wn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",bn=`${f}: LETMESTARTPRESENTATION`,Un=`${f}: STOPPRESENTATION`,ft="YOUCANRECEIVECONTENT",It="CONTENTEND",Pt="YOUMUSTSTOPSENDCONTENT",Ln=`${f}: ${Pt}`,Hn=`${f}: ${ft}`,Wn=`${f}: ${It}`,kn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Bn=`${kn}: LETMESTARTMAINCAM`,Fn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(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"&&Fn(c,n),c},xn="Error decline with 603",Vn=1006,Yn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Vn,qn=s=>s.message===xn,$n=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Gn=async(s,e,t)=>{const n=$n(s,e);if(n)return Rt(n,{maxBitrate:t})},Jn=486,Xn=487,Qn=3,zn=1,jn=s=>s instanceof Object&&("originator"in s||"cause"in s),Kn=s=>{if(Mt.isCanceledError(s))return!0;if(!jn(s))return!1;const{originator:e,cause:t}=s;return typeof t=="string"?t===ke||t===X||e===_.LOCAL&&(t===Q||t===Fe):!1},Zn=s=>G.hasCanceledError(s),es="channels",ts="WebcastStarted",ns="WebcastStopped",ss="accountChanged",is="accountDeleted",os="addedToListModerators",rs="removedFromListModerators",as="ParticipationRequestAccepted",cs="ParticipationRequestRejected",Es="ParticipantMovedToWebcast",ds="ConferenceParticipantTokenIssued";class hs{constructor({JsSIP:e}){r(this,"promisePendingStartPresentation");r(this,"promisePendingStopPresentation");r(this,"ua");r(this,"rtcSession");r(this,"incomingRTCSession");r(this,"streamPresentationCurrent");r(this,"socket");r(this,"isRegisterConfigInner",!1);r(this,"connectionConfiguration",{});r(this,"remoteStreams",{});r(this,"JsSIP");r(this,"sessionEvents");r(this,"uaEvents");r(this,"cancelableConnectWithRepeatedCalls");r(this,"cancelableSendPresentationWithRepeatedCalls");r(this,"isPendingConnect",!1);r(this,"isPendingInitUa",!1);r(this,"isPendingCall",!1);r(this,"isPendingAnswer",!1);r(this,"connect",async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t)));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){v("tryRegister",e)}return this.register()});r(this,"declineToIncomingCall",async({statusCode:e=Xn}={})=>new Promise((t,n)=>{try{const i=this.getIncomingRTCSession(),o=this.remoteCallerData;this.removeIncomingSession(),this.uaEvents.trigger(j,o),i.terminate({status_code:e}),t()}catch(i){n(i)}}));r(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Jn}));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",be(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(d=>{i(d)}):E?n(E):i(new Error("nothing changed"))}));r(this,"disconnect",async()=>{this.off(y,this.handleNewRTCSession);const e=new Promise(n=>{this.once(C,()=>{n()})}),{ua:t}=this;return t?(await this.hangUpWithoutCancelRequests(),t.stop()):this.uaEvents.trigger(C,void 0),e.finally(()=>{delete this.ua})});r(this,"call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:o,directionVideo:a,directionAudio:c,contentHint:E,offerToReceiveAudio:d=!0,offerToReceiveVideo:T=!0,sendEncodings:l,onAddedTransceiver:S})=>(this.isPendingCall=!0,new Promise((u,h)=>{const{ua:g}=this;if(!g){h(new Error("this.ua is not initialized"));return}this.connectionConfiguration.number=e,this.connectionConfiguration.answer=!1,this.handleCall({ontrack:i}).then(u).catch(N=>{h(N)}),this.rtcSession=g.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{directionVideo:a,directionAudio:c,contentHint:E}),eventHandlers:this.sessionEvents.triggers,directionVideo:a,directionAudio:c,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:d,offerToReceiveVideo:T},sendEncodings:l,onAddedTransceiver:S})}).finally(()=>{this.isPendingCall=!1})));r(this,"answerToIncomingCall",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:o,directionAudio:a,offerToReceiveAudio:c,offerToReceiveVideo:E,contentHint:d,sendEncodings:T,onAddedTransceiver:l})=>(this.isPendingAnswer=!0,new Promise((S,u)=>{try{const h=this.getIncomingRTCSession();this.rtcSession=h,this.removeIncomingSession(),this.sessionEvents.eachTriggers((N,q)=>{const I=pe.find($=>$===q);I&&h.on(I,N)}),this.connectionConfiguration.answer=!0,this.connectionConfiguration.number=h.remote_identity.uri.user,this.handleCall({ontrack:t}).then(S).catch(N=>{u(N)});const g=p(e,{directionVideo:o,directionAudio:a,contentHint:d});h.answer({extraHeaders:n,directionVideo:o,directionAudio:a,mediaStream:g,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:E},sendEncodings:T,onAddedTransceiver:l})}catch(h){u(h)}}).finally(()=>{this.isPendingAnswer=!1})));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===_.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));r(this,"removeIncomingSession",()=>{delete this.incomingRTCSession});r(this,"getSipServerUrl",e=>e);r(this,"connectWithDuplicatedCalls",async(e,{callLimit:t=Qn}={})=>{const n=async()=>this.connectInner(e),i=o=>{var d;const c=((d=this.ua)==null?void 0:d.isConnected())===!0&&this.hasEqualConnectionConfiguration(e),E=o!=null&&!Yn(o);return c||E};return this.isPendingConnect=!0,this.cancelableConnectWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(o=>{if(o instanceof this.JsSIP.UA)return o;throw o}).finally(()=>{this.isPendingConnect=!1})});r(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===_.REMOTE){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(A,i=>{this.removeIncomingSession(),i.originator===_.LOCAL?this.uaEvents.trigger(Z,n):this.uaEvents.trigger(K,n)}),this.uaEvents.trigger(z,n)}});r(this,"connectInner",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:d,userAgent:T,displayName:l="",register:S=!1,extraHeaders:u=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(S&&(e===void 0||e===""))throw new Error("user is required for authorized connection");if(S&&(t===void 0||t===""))throw new Error("password is required for authorized connection");this.isPendingInitUa=!0;try{this.connectionConfiguration={sipServerUrl:n,displayName:l,register:S,user:e,password:t};const{configuration:h,helpers:g}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:l,register:S,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T});return this.getSipServerUrl=g.getSipServerUrl,this.socket=g.socket,this.ua&&await this.disconnect(),this.isRegisterConfigInner=!!S,this.ua=this.createUa({...h,remoteAddress:o,extraHeaders:u}),this.uaEvents.eachTriggers((N,q)=>{const I=Y.find($=>$===q);I&&this.ua&&this.ua.on(I,N)}),this.ua}finally{this.isPendingInitUa=!1}});r(this,"createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e!==void 0&&e!==""?hn(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(O,i),this.on(m,o)):this.on(P,i),this.on(C,o)},c=()=>{this.off(O,i),this.off(m,o),this.off(P,i),this.off(C,o)};a(),this.on(y,this.handleNewRTCSession),n.start()}));r(this,"handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(H,T),this.onSession(L,l)},o=()=>{this.offSession(H,T),this.offSession(L,l)},a=()=>{this.onSession(A,E),this.onSession(M,E)},c=()=>{this.offSession(A,E),this.offSession(M,E)},E=S=>{o(),c(),n(S)};let d;const T=({peerconnection:S})=>{d=S,d.ontrack=u=>{this.sessionEvents.trigger(ce,d),e&&e(u)}},l=()=>{d!==void 0&&this.sessionEvents.trigger(ae,d),o(),c(),t(d)};i(),a()}));r(this,"restoreSession",()=>{this.cancelRequestsAndResetPresentation(),delete this.connectionConfiguration.number,delete this.rtcSession,this.remoteStreams={}});r(this,"hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this.streamPresentationCurrent)try{await this.stopPresentation()}catch(t){v("error stop presentation: ",t)}if(this.restoreSession(),!e.isEnded())return e.terminateAsync({cause:Q})}});r(this,"handleShareState",e=>{switch(e){case ft:{this.sessionEvents.trigger(ne,void 0);break}case It:{this.sessionEvents.trigger(se,void 0);break}case Pt:{this.sessionEvents.trigger(ie,void 0);break}}});r(this,"maybeTriggerChannels",e=>{const t=e.getHeader(Le),n=e.getHeader(He);if(t&&n){const i={inputChannels:t,outputChannels:n};this.sessionEvents.trigger(b,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 os:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case rs:{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 ds:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:v("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(ge,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(fe,n)});r(this,"triggerAccountChangedNotify",()=>{this.uaEvents.trigger(Ie,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(Ne,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(_e,t)});r(this,"triggerEnterRoom",e=>{const t=e.getHeader(Tn),n=e.getHeader(Rn);this.sessionEvents.trigger(oe,{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(vn);t===dt&&this.sessionEvents.trigger(x,void 0),t===ht&&this.sessionEvents.trigger(V,void 0)});r(this,"triggerMainCamControl",e=>{const t=e.getHeader(fn),n=e.getHeader(We),i=n===B.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this.sessionEvents.trigger(Te,{isSyncForced:i});return}if(t===R.ADMIN_STOP_MAIN_CAM){this.sessionEvents.trigger(Se,{isSyncForced:i});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n!==void 0&&this.sessionEvents.trigger(U,{isSyncForced:i});const o=e.getHeader(Pn);this.sessionEvents.trigger(he,{mainCam:t,resolutionMainCam:o})});r(this,"triggerMicControl",e=>{const t=e.getHeader(In),i=e.getHeader(We)===B.ADMIN_SYNC_FORCED;t===k.ADMIN_START_MIC?this.sessionEvents.trigger(ue,{isSyncForced:i}):t===k.ADMIN_STOP_MIC&&this.sessionEvents.trigger(le,{isSyncForced:i})});r(this,"triggerUseLicense",e=>{const t=e.getHeader(An);this.sessionEvents.trigger(re,t)});r(this,"handleNewInfo",e=>{const{originator:t}=e;if(t!==_.REMOTE)return;const{request:n}=e,i=n.getHeader(Sn);if(i)switch(i){case ln:{this.triggerEnterRoom(n),this.maybeTriggerChannels(n);break}case yn:{this.maybeHandleNotify(n);break}case D:{this.triggerShareState(n);break}case Ue:{this.triggerMainCamControl(n);break}case _n:{this.triggerMicControl(n);break}case Nn:{this.triggerUseLicense(n);break}case pn:{this.maybeTriggerParticipantMoveRequest(n);break}}});r(this,"handleSipEvent",({request:e})=>{this.maybeHandleNotify(e)});r(this,"maybeHandleNotify",e=>{const t=e.getHeader(wn);if(t){const n=JSON.parse(t);this.handleNotify(n)}});r(this,"handleEnded",e=>{const{originator:t}=e;t===_.REMOTE&&this.sessionEvents.trigger(de,e),this.restoreSession()});this.JsSIP=e,this.sessionEvents=new we(ve),this.uaEvents=new we(ut),this.onSession(w,this.handleShareState),this.onSession(Me,this.handleNewInfo),this.on(te,this.handleSipEvent),this.onSession(A,this.handleEnded),this.onSession(M,this.handleEnded)}get connection(){var t;return(t=this.rtcSession)==null?void 0:t.connection}get remoteCallerData(){var e,t,n;return{displayName:(e=this.incomingRTCSession)==null?void 0:e.remote_identity.display_name,host:(t=this.incomingRTCSession)==null?void 0:t.remote_identity.uri.host,incomingNumber:(n=this.incomingRTCSession)==null?void 0:n.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this.isPendingInitUa||this.isPendingConnect||this.isPendingCall||this.isPendingAnswer}get establishedRTCSession(){var e;return((e=this.rtcSession)==null?void 0:e.isEstablished())===!0?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this.isRegisterConfigInner}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(O,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:d}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),T=this.createUa({...d,remoteAddress:o,extraHeaders:a}),l=()=>{const u=new Error("Telephony is not available");E(u)};T.once(C,l);const S=()=>{T.removeAllListeners(),T.once(C,c),T.stop()};T.once(P,S),T.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=p(e,{contentHint:n});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Bn];return this.rtcSession.sendInfo(Ue,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(qn(n))throw n})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c}={},E){const d=this.establishedRTCSession;if(!d)throw new Error("No rtcSession established");if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return n===!0&&await this.sendMustStopPresentation(),this.sendPresentationWithDuplicatedCalls({rtcSession:d,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:o,sendEncodings:a,onAddedTransceiver:c},options:E})}async stopPresentation({isP2P:e=!1}={}){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=e?[Wn]:[Un],o=this.establishedRTCSession;return o&&t&&(n=n.then(async()=>o.sendInfo(D,void 0,{extraHeaders:i})).then(async()=>o.stopPresentation(t)).catch(a=>{throw this.sessionEvents.trigger(W,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})}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 dn(t)?this.generateStreams(t):this.generateAudioStreams(t)}getIncomingRTCSession(){const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e}cancelSendPresentationWithRepeatedCalls(){var e;(e=this.cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}async waitChannels(){return this.waitSession(b)}async waitSyncMediaState(){return this.waitSession(U)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${Le}: ${e}`,i=`${He}: ${t}`,o=[n,i];return this.rtcSession.sendInfo(un,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${On}: currentstate`,o=`${Mn}: ${Number(e)}`,a=`${Dn}: ${Number(t)}`,c=[i,o,a];return this.rtcSession.sendInfo(gn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const c=[`${mn}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(Cn,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})}async sendMustStopPresentation(){const e=this.establishedRTCSession;if(!e)throw new Error("No rtcSession established");await e.sendInfo(D,void 0,{extraHeaders:[Ln]})}async sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:zn}}){const o=async()=>this.sendPresentation(e,t,n),a=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=G.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.uri.toString()===t.uri&&n.display_name===t.display_name&&n.user_agent===t.user_agent&&n.sockets===t.sockets&&n.session_timers===t.session_timers&&n.register_expires===t.register_expires&&n.connection_recovery_min_interval===t.connection_recovery_min_interval&&n.connection_recovery_max_interval===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:o,register:a=!1,sessionTimers:c=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:d=2,connectionRecoveryMaxInterval:T=6,userAgent:l}){if(a&&(t===void 0||t===""))throw new Error("password is required for authorized connection");const S=a&&e!==void 0&&e.trim()!==""?e.trim():`${En()}`,u=an(o),h=u(S),g=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:h,display_name:be(i),user_agent:l,sdp_semantics:"unified-plan",sockets:[g],session_timers:c,register_expires:E,connection_recovery_min_interval:d,connection_recovery_max_interval:T},helpers:{socket:g,getSipServerUrl:u}}}async sendPresentation(e,t,{maxBitrate:n=St,isNeedReinvite:i=!0,isP2P:o=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:E}){const d=p(t,{contentHint:a});if(d===void 0)throw new Error("No streamPresentationCurrent");this.streamPresentationCurrent=d;const T=o?[Hn]:[bn],l=e.sendInfo(D,void 0,{extraHeaders:T}).then(async()=>e.startPresentation(d,i,{sendEncodings:c,onAddedTransceiver:E})).then(async()=>{const{connection:S}=this;if(!S)return;const u=S.getSenders();await Gn(u,t,n)}).then(()=>t).catch(S=>{throw this.removeStreamPresentationCurrent(),this.sessionEvents.trigger(W,S),S});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}cancelRequestsAndResetPresentation(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}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==null?void 0: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.cancelConnectWithRepeatedCalls()}cancelConnectWithRepeatedCalls(){var e;(e=this.cancelableConnectWithRepeatedCalls)==null||e.cancel()}}exports.BAD_MEDIA_DESCRIPTION=xe;exports.EEventsMainCAM=R;exports.EEventsMic=k;exports.EEventsSyncMediaState=B;exports.EMimeTypesVideoCodecs=At;exports.EUseLicense=Nt;exports.NOT_FOUND=Be;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=x;exports.REJECTED=X;exports.SESSION_EVENT_NAMES=ve;exports.SipConnector=hs;exports.UA_JSSIP_EVENT_NAMES=Y;exports.causes=$t;exports.constants=Gt;exports.disableDebug=Qt;exports.enableDebug=Xt;exports.eventNames=Jt;exports.hasCanceledCallError=Kn;exports.hasCanceledStartPresentationError=Zn;exports.logger=v;exports.setEncodingsToSender=Rt;exports.setParametersToSender=_t;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var F=Object.defineProperty;var L=(o,e,t)=>e in o?F(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var r=(o,e,t)=>L(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./SipConnector-DGYQOyHy.cjs"),V=require("@krivega/jssip/lib/NameAddrHeader"),U=require("@krivega/jssip/lib/URI"),z=require("node:events"),x=require("@krivega/jssip/lib/SIPMessage"),y=require("webrtc-mock"),A=require("events-constructor"),u=require("@krivega/jssip");class v extends x.IncomingRequest{constructor(t){super();r(this,"headers");this.headers=new Headers(t)}getHeader(t){return this.headers.get(t)??""}}class q{constructor({originator:e="local",eventHandlers:t}){r(this,"originator");r(this,"connection");r(this,"events");r(this,"remote_identity");r(this,"mutedOptions",{audio:!1,video:!1});this.originator=e,this.events=new A(p.SESSION_EVENT_NAMES),this.initEvents(t)}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 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.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){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(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,n){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){throw new Error("Method not implemented.")}removeAllListeners(e){throw new Error("Method not implemented.")}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){Object.entries(e).forEach(([t,n])=>this.on(t,n))}on(e,t){return this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return e}async updatePresentation(e){return e}async stopPresentation(e){return e}isEstablished(){return!0}}class H{constructor({track:e}={}){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=e??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class Y{constructor(e,t){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",e=>{const t=new H({track:e});return this.senders.push(t),t});this.receivers=t.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,n){throw new Error("Method not implemented.")}removeEventListener(e,t,n){throw new Error("Method not implemented.")}dispatchEvent(e){throw new Error("Method not implemented.")}}function j(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const S=400,O="777",B=o=>o.getVideoTracks().length>0,a=class a extends q{constructor({url:t="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"answer",jest.fn(({mediaStream:t})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(t),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},S)}));r(this,"isEndedInner",!1);this.url=t,this.initPeerconnection(n)}static setStartPresentationError(t,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=t,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(t){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(t)}initPeerconnection(t){return t?(this.createPeerconnection(t),!0):!1}createPeerconnection(t){const n=y.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(B(t)){const c=y.createVideoMediaStreamTrackMock();c.id="mainvideo1",i.push(c)}this.connection=new Y(void 0,i),this.addStream(t),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},S)}connect(t){const n=j(t);setTimeout(()=>{this.url.includes(O)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:p.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},S)}terminate({status_code:t,cause:n}={}){return this.status_code=t,this.trigger("ended",{status_code:t,cause:n,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:t,cause:n}={}){this.terminate({status_code:t,cause:n})}terminateRemote({status_code:t}={}){return this.status_code=t,this.trigger("ended",{status_code:t,originator:"remote"}),this}addStream(t,n="getTracks"){t[n]().forEach(i=>this.connection.addTrack(i))}forEachSenders(t){const n=this.connection.getSenders();for(const i of n)t(i);return n}toggleMuteAudio(t){this.forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!t)})}toggleMuteVideo(t){this.forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!t)})}mute(t){t.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),t.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(t)}unmute(t){t.audio&&(this.mutedOptions.audio=!1),t.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",t)}isMuted(){return this.mutedOptions}async replaceMediaStream(t){}onmute({audio:t,video:n}){this.trigger("muted",{audio:t,video:n})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(t){this.trigger("newInfo",t)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let g=a;class G{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const h="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",k="NAME_INCORRECT",l=400,f={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},N={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"},s=class s{constructor(e){r(this,"events");r(this,"registratorInner");r(this,"call",jest.fn((e,t)=>{const{mediaStream:n,eventHandlers:i}=t;return this.session=new g({url:e,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(e),this.session}));r(this,"startedTimeout");r(this,"stopedTimeout");r(this,"session");r(this,"isRegisteredInner");r(this,"isConnectedInner");r(this,"configuration");this.events=new A(p.UA_JSSIP_EVENT_NAMES);const[t,n]=e.uri.split(":"),[i,d]=n.split("@"),c={...e,uri:new u.URI(t,i,d)};this.configuration=c,this.registratorInner=new G}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startError=e,this.countStartError=t}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}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:!0,socket:f})},l):this.trigger("disconnected",{error:!0,socket:f})}on(e,t){return this.events.on(e,t),this}once(e,t){return this.events.once(e,t),this}off(e,t){return this.events.off(e,t),this}removeAllListeners(){return this.events.removeEventHandlers(),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){var e;(e=this.session)==null||e.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:n}=this.configuration;t===!0&&n.user.includes(k)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)):!this.isRegistered()&&t===!0&&(e===h||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:N})},l)):t===!0&&e!==h&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)),s.isAvailableTelephony?(this.trigger("connected",{socket:f}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:N})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class J{constructor(e){r(this,"url");this.url=e}}class K extends z.EventEmitter{constructor(t,n){super();r(this,"contentType");r(this,"body");this.contentType=t,this.body=n}}const T="remote",$=(o,e)=>{const t=new v(e),n={originator:T,request:t,info:new K("","")};o.newInfo(n)},X=(o,e)=>{const n={event:"sipEvent",request:new v(e)};o.newSipEvent(n)},Q=(o,{incomingNumber:e="1234",displayName:t,host:n})=>{const i=new g({originator:T,eventHandlers:{}}),d=new U("sip",e,n);i.remote_identity=new V(d,t);const c=new v([]);o.trigger("newRTCSession",{originator:T,session:i,request:c})},Z=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},W={triggerNewInfo:$,triggerNewSipEvent:X,triggerIncomingSession:Q,triggerFailIncomingSession:Z,WebSocketInterface:J,UA:M,C:{INVITE:"INVITE"}},E="user",m="displayName",w="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",ee=new W.WebSocketInterface(R),C={userAgent:"Chrome",sipServerUrl:w,sipWebSocketServerURL:R},te={...C},b={...C,user:E,password:h,register:!0},re={...b,displayName:m},ne={...C,displayName:m,register:!1},_={session_timers:!1,sockets:[ee],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},oe={..._,password:h,uri:new u.URI("sip",E,w),display_name:"",register:!0},ie={..._,password:h,uri:new u.URI("sip",E,w),display_name:m,register:!0},se={..._,display_name:m,register:!1},ae={..._,display_name:"",register:!1},D="10.10.10.10",de=[`X-Vinteo-Remote: ${D}`],ce=()=>new p.SipConnector({JsSIP:W});exports.FAILED_CONFERENCE_NUMBER=O;exports.NAME_INCORRECT=k;exports.PASSWORD_CORRECT=h;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=w;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=re;exports.dataForConnectionWithoutAuthorization=ne;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=te;exports.displayName=m;exports.doMockSipConnector=ce;exports.extraHeadersRemoteAddress=de;exports.remoteAddress=D;exports.uaConfigurationWithAuthorization=oe;exports.uaConfigurationWithAuthorizationWithDisplayName=ie;exports.uaConfigurationWithoutAuthorization=se;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ae;exports.user=E;
1
+ "use strict";var F=Object.defineProperty;var L=(o,e,t)=>e in o?F(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var r=(o,e,t)=>L(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./SipConnector-J07EhbbA.cjs"),V=require("@krivega/jssip/lib/NameAddrHeader"),U=require("@krivega/jssip/lib/URI"),z=require("node:events"),x=require("@krivega/jssip/lib/SIPMessage"),y=require("webrtc-mock"),A=require("events-constructor"),u=require("@krivega/jssip");class v extends x.IncomingRequest{constructor(t){super();r(this,"headers");this.headers=new Headers(t)}getHeader(t){return this.headers.get(t)??""}}class q{constructor({originator:e="local",eventHandlers:t}){r(this,"originator");r(this,"connection");r(this,"events");r(this,"remote_identity");r(this,"mutedOptions",{audio:!1,video:!1});this.originator=e,this.events=new A(p.SESSION_EVENT_NAMES),this.initEvents(t)}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 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.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){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(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,n){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){throw new Error("Method not implemented.")}removeAllListeners(e){throw new Error("Method not implemented.")}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){Object.entries(e).forEach(([t,n])=>this.on(t,n))}on(e,t){return this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return e}async updatePresentation(e){return e}async stopPresentation(e){return e}isEstablished(){return!0}}class H{constructor({track:e}={}){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=e??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class Y{constructor(e,t){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",e=>{const t=new H({track:e});return this.senders.push(t),t});this.receivers=t.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,n){throw new Error("Method not implemented.")}removeEventListener(e,t,n){throw new Error("Method not implemented.")}dispatchEvent(e){throw new Error("Method not implemented.")}}function j(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const S=400,O="777",B=o=>o.getVideoTracks().length>0,a=class a extends q{constructor({url:t="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"answer",jest.fn(({mediaStream:t})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(t),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},S)}));r(this,"isEndedInner",!1);this.url=t,this.initPeerconnection(n)}static setStartPresentationError(t,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=t,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(t){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(t)}initPeerconnection(t){return t?(this.createPeerconnection(t),!0):!1}createPeerconnection(t){const n=y.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(B(t)){const c=y.createVideoMediaStreamTrackMock();c.id="mainvideo1",i.push(c)}this.connection=new Y(void 0,i),this.addStream(t),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},S)}connect(t){const n=j(t);setTimeout(()=>{this.url.includes(O)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:p.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},S)}terminate({status_code:t,cause:n}={}){return this.status_code=t,this.trigger("ended",{status_code:t,cause:n,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:t,cause:n}={}){this.terminate({status_code:t,cause:n})}terminateRemote({status_code:t}={}){return this.status_code=t,this.trigger("ended",{status_code:t,originator:"remote"}),this}addStream(t,n="getTracks"){t[n]().forEach(i=>this.connection.addTrack(i))}forEachSenders(t){const n=this.connection.getSenders();for(const i of n)t(i);return n}toggleMuteAudio(t){this.forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!t)})}toggleMuteVideo(t){this.forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!t)})}mute(t){t.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),t.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(t)}unmute(t){t.audio&&(this.mutedOptions.audio=!1),t.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",t)}isMuted(){return this.mutedOptions}async replaceMediaStream(t){}onmute({audio:t,video:n}){this.trigger("muted",{audio:t,video:n})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(t){this.trigger("newInfo",t)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let g=a;class G{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const h="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",k="NAME_INCORRECT",l=400,f={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},N={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"},s=class s{constructor(e){r(this,"events");r(this,"registratorInner");r(this,"call",jest.fn((e,t)=>{const{mediaStream:n,eventHandlers:i}=t;return this.session=new g({url:e,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(e),this.session}));r(this,"startedTimeout");r(this,"stopedTimeout");r(this,"session");r(this,"isRegisteredInner");r(this,"isConnectedInner");r(this,"configuration");this.events=new A(p.UA_JSSIP_EVENT_NAMES);const[t,n]=e.uri.split(":"),[i,d]=n.split("@"),c={...e,uri:new u.URI(t,i,d)};this.configuration=c,this.registratorInner=new G}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startError=e,this.countStartError=t}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}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:!0,socket:f})},l):this.trigger("disconnected",{error:!0,socket:f})}on(e,t){return this.events.on(e,t),this}once(e,t){return this.events.once(e,t),this}off(e,t){return this.events.off(e,t),this}removeAllListeners(){return this.events.removeEventHandlers(),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){var e;(e=this.session)==null||e.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:n}=this.configuration;t===!0&&n.user.includes(k)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)):!this.isRegistered()&&t===!0&&(e===h||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:N})},l)):t===!0&&e!==h&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:u.C.causes.REJECTED})},l)),s.isAvailableTelephony?(this.trigger("connected",{socket:f}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:N})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class J{constructor(e){r(this,"url");this.url=e}}class K extends z.EventEmitter{constructor(t,n){super();r(this,"contentType");r(this,"body");this.contentType=t,this.body=n}}const T="remote",$=(o,e)=>{const t=new v(e),n={originator:T,request:t,info:new K("","")};o.newInfo(n)},X=(o,e)=>{const n={event:"sipEvent",request:new v(e)};o.newSipEvent(n)},Q=(o,{incomingNumber:e="1234",displayName:t,host:n})=>{const i=new g({originator:T,eventHandlers:{}}),d=new U("sip",e,n);i.remote_identity=new V(d,t);const c=new v([]);o.trigger("newRTCSession",{originator:T,session:i,request:c})},Z=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},W={triggerNewInfo:$,triggerNewSipEvent:X,triggerIncomingSession:Q,triggerFailIncomingSession:Z,WebSocketInterface:J,UA:M,C:{INVITE:"INVITE"}},E="user",m="displayName",w="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",ee=new W.WebSocketInterface(R),C={userAgent:"Chrome",sipServerUrl:w,sipWebSocketServerURL:R},te={...C},b={...C,user:E,password:h,register:!0},re={...b,displayName:m},ne={...C,displayName:m,register:!1},_={session_timers:!1,sockets:[ee],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},oe={..._,password:h,uri:new u.URI("sip",E,w),display_name:"",register:!0},ie={..._,password:h,uri:new u.URI("sip",E,w),display_name:m,register:!0},se={..._,display_name:m,register:!1},ae={..._,display_name:"",register:!1},D="10.10.10.10",de=[`X-Vinteo-Remote: ${D}`],ce=()=>new p.SipConnector({JsSIP:W});exports.FAILED_CONFERENCE_NUMBER=O;exports.NAME_INCORRECT=k;exports.PASSWORD_CORRECT=h;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=w;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=re;exports.dataForConnectionWithoutAuthorization=ne;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=te;exports.displayName=m;exports.doMockSipConnector=ce;exports.extraHeadersRemoteAddress=de;exports.remoteAddress=D;exports.uaConfigurationWithAuthorization=oe;exports.uaConfigurationWithAuthorizationWithDisplayName=ie;exports.uaConfigurationWithoutAuthorization=se;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ae;exports.user=E;
package/dist/doMock.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var k = Object.defineProperty;
2
2
  var A = (o, e, t) => e in o ? k(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
3
  var r = (o, e, t) => A(o, typeof e != "symbol" ? e + "" : e, t);
4
- import { o as b, R as D, U as L, S as W } from "./SipConnector-DTNc5BfW.js";
4
+ import { o as b, R as D, U as L, S as W } from "./SipConnector-D9frFCEK.js";
5
5
  import V from "@krivega/jssip/lib/NameAddrHeader";
6
6
  import F from "@krivega/jssip/lib/URI";
7
7
  import { EventEmitter as x } from "node:events";
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var te=Object.defineProperty;var se=(n,e,t)=>e in n?te(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>se(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./SipConnector-DGYQOyHy.cjs"),oe=require("sequent-promises"),re=require("stack-promises"),_=require("debug"),ie=require("@krivega/cancelable-promise"),ce=require("repeated-calls"),ae=require("ts-debounce"),U=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 W=(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))(W||{});const le=new Error("Unknown error"),ue=(n=le)=>{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!==void 0&&((r=t._ws)==null?void 0:r.readyState)===3?s="WS_CONNECTION_FAILED":U(n)!==void 0&&U(n)!==""&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},de=n=>{let e="";try{e=JSON.stringify(n)}catch(t){o.logger("failed to stringify message",t)}return e},ge=new Error("Unknown error"),Ce=(n=ge)=>{const{code:e,cause:t,message:s}=n,r=U(n),i={code:"",cause:"",message:""};return typeof s=="object"&&s!==null?i.message=de(s):s&&(i.message=String(s)),r!==void 0&&r!==""&&(i.link=r),e!==void 0&&e!==""&&(i.code=e),t!==void 0&&t!==""&&(i.cause=t),i},Se=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:W,getLinkError:U,getTypeFromError:ue,getValuesFromError:Ce},Symbol.toStringTag,{value:"Module"})),fe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:s,isRegistered:r,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}`),(r===!1||r===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),i===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},me="[@*!|]",he="_",Re=n=>{let e=n;return e=e.replaceAll(new RegExp(me,"g"),he),e},pe=({appName:n,appVersion:e,browserName:t,browserVersion:s})=>{const i=`${Re(n)} ${e}`;return`ChromeNew - ${t?`${t} ${s}, ${i}`:i}`},Ee=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:s,appName:r})=>n?pe({appVersion:e,browserName:t,browserVersion:s,appName:r}):"Chrome",G="purgatory",I=n=>n===G,ye=n=>e=>[...e].map(s=>async()=>n(s)),Te=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=ye(e)(n);return oe.sequentPromises(r,t)},Me=n=>t=>(o.logger("onStartMainCam"),n.onSession("admin-start-main-cam",t)),be=n=>t=>(o.logger("onStartMic"),n.onSession("admin-start-mic",t)),Ae=n=>t=>(o.logger("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),ve=n=>t=>(o.logger("onStopMic"),n.onSession("admin-stop-mic",t)),_e=({sipConnector:n})=>{const e=(f,p)=>({isSyncForced:m=!1})=>{if(m){f();return}p()},t=Me(n),s=Ae(n),r=be(n),i=ve(n);let c=()=>{},l=()=>{},u=()=>{},g=()=>{};const S=({onStartMainCamForced:f,onStartMainCamNotForced:p,onStopMainCamForced:m,onStopMainCamNotForced:h,onStartMicForced:E,onStartMicNotForced:y,onStopMicForced:T,onStopMicNotForced:M})=>{const v=e(f,p);c=t(v);const O=e(m,h);l=s(O);const N=e(E,y);u=r(N);const w=e(T,M);g=i(w)},C=()=>{c(),l(),u(),g()};return{start:f=>{S(f)},stop:()=>{C()}}},Oe=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:G,createSyncMediaState:_e,error:Se,getExtraHeaders:fe,getUserAgent:Ee,hasPurgatory:I,sendDtmfAccumulated:Te},Symbol.toStringTag,{value:"Module"})),Ne=n=>[...n.keys()].map(e=>n.get(e)),we=(n,e)=>Ne(n).find(t=>t.type===e),K=async n=>n.getStats().then(e=>{const t=we(e,"codec");return t==null?void 0:t.mimeType}),Pe=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),Y=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),De=1e6,R=n=>n*De,z=R(.06),Be=R(4),Ie=n=>n<=64?z: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,Fe="av1",ke=n=>Y(n,Fe),Ve=.6,Q=(n,e)=>ke(e)?n*Ve:n,Ue=n=>Q(z,n),J=(n,e)=>{const t=Ie(n);return Q(t,e)},xe=1,Z=({videoTrack:n,targetSize:e,codec:t})=>{const s=n.getSettings(),r=s.width,i=s.height,c=r/e.width,l=i/e.height,u=Math.max(c,l,xe),g=J(e.width,t);return{scaleResolutionDownBy:u,maxBitrate:g}},ee=re.createStackPromises(),Le=async()=>ee().catch(n=>{o.logger("videoSendingBalancer: error",n)}),$e=async n=>(ee.add(n),Le()),q=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:s})=>$e(async()=>o.setEncodingsToSender(n,{scaleResolutionDownBy:e,maxBitrate:t},s)),He=async({sender:n,codec:e},t)=>{const r=Ue(e);return q({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},V=async({sender:n,videoTrack:e,codec:t},s)=>{const c=e.getSettings().width,l=J(c,t);return q({sender:n,maxBitrate:l,onSetParameters:s,scaleResolutionDownBy:1})},qe=async({sender:n,videoTrack:e,resolution:t,codec:s},r)=>{const[i,c]=t.split("x"),{maxBitrate:l,scaleResolutionDownBy:u}=Z({videoTrack:e,codec:s,targetSize:{width:Number(i),height:Number(c)}});return q({sender:n,maxBitrate:l,onSetParameters:r,scaleResolutionDownBy:u})},Xe=async({mainCam:n,resolutionMainCam:e,sender:t,videoTrack:s,codec:r},i)=>{switch(n){case o.EEventsMainCAM.PAUSE_MAIN_CAM:return He({sender:t,codec:r},i);case o.EEventsMainCAM.RESUME_MAIN_CAM:return V({sender:t,videoTrack:s,codec:r},i);case o.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?qe({sender:t,videoTrack:s,codec:r,resolution:e},i):V({sender:t,videoTrack:s,codec:r},i);case o.EEventsMainCAM.ADMIN_STOP_MAIN_CAM:case o.EEventsMainCAM.ADMIN_START_MAIN_CAM:case void 0:return V({sender:t,videoTrack:s,codec:r},i);default:return V({sender:t,videoTrack:s,codec:r},i)}},X={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},j=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:s,ignoreForCodec:r})=>{const i=t.getSenders(),c=Pe(i);if(!(c!=null&&c.track))return X;const l=await K(c);return Y(l,r)?X:Xe({mainCam:n,resolutionMainCam:e,sender:c,codec:l,videoTrack:c.track},s)},je=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const s=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return j({connection:u,onSetParameters:t,ignoreForCodec:e})};let r=s;const i=u=>{r=async()=>{const{mainCam:g,resolutionMainCam:S}=u,{connection:C}=n;if(!C)throw new Error("connection is not exist");return j({mainCam:g,resolutionMainCam:S,connection:C,onSetParameters:t,ignoreForCodec:e})},r().catch(_)};return{subscribe:()=>{n.onSession("main-cam-control",i)},unsubscribe:()=>{n.offSession("main-cam-control",i)},balanceByTrack:s,resetMainCamControl(){r=s},async reBalance(){return r()}}},We=n=>n.getVideoTracks()[0],D=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const s=t??[],r=We(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}=Z({videoTrack:r,targetSize:{width:i.width,height:i.height}});l.maxBitrate=u,l.scaleResolutionDownBy=g,s[c]=l}),s}return t},Ge=(n,e)=>n.filter(s=>e.some(r=>r.clockRate===s.clockRate&&r.mimeType===s.mimeType&&r.channels===s.channels&&r.sdpFmtpLine===s.sdpFmtpLine)),Ke=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return Ge(s,r)},Ye=(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,l=i===-1?Number.MAX_VALUE:i;return c-l}),ze=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),B=(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.length>0||t!==void 0&&t.length>0)){const i=Ke("video"),c=ze(i,t),l=Ye(c,e);s.setCodecPreferences(l)}Object.keys(n).length>0&&await o.setParametersToSender(s.sender,n)}catch(i){o.logger("updateTransceiver error",i)}},H=n=>{if(!ie.isCanceledError(n)&&!ce.hasCanceledError(n))throw n;return{isSuccessful:!1}},Qe=({kind:n,readyState:e})=>n==="video"&&e==="live",Je=new Set(["on","once","onceRace","wait","off","onSession","onceSession","onceRaceSession","waitSession","offSession","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class Ze{constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s}={}){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,"sipConnector");a(this,"preferredMimeTypesVideoCodecs");a(this,"excludeMimeTypesVideoCodecs");a(this,"connectToServer",async e=>{const{userAgent:t,sipWebSocketServerURL:s,sipServerUrl:r,remoteAddress:i,displayName:c,name:l,password:u,isRegisteredUser:g,isDisconnectOnFail:S}=e;return o.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:s,sipServerUrl:r,remoteAddress:i,displayName:c,password:u,user:l,register:g}).then(C=>(o.logger("connectToServer then"),{ua:C,isSuccessful:!0})).catch(async C=>(o.logger("connectToServer catch: error",C),S===!0?this.sipConnector.disconnect().then(()=>H(C)).catch(()=>H(C)):H(C)))});a(this,"callToServer",async e=>{const{conference:t,mediaStream:s,extraHeaders:r,iceServers:i,contentHint:c,simulcastEncodings:l,degradationPreference:u,sendEncodings:g,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,setRemoteStreams:f,onBeforeProgressCall:p,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:E,onFailProgressCall:y,onFinishProgressCall:T,onEndedCall:M}=e,v=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:f}),O=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{v().catch(_)}}),N=B({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("callToServer",e);const w=async()=>(o.logger("startCall"),this.sipConnector.call({mediaStream:s,extraHeaders:r,iceServers:i,contentHint:c,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,sendEncodings:D({mediaStream:s,simulcastEncodings:l,sendEncodings:g}),number:t,onAddedTransceiver:N,ontrack:O}));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,I(A)?h&&h():E&&E({isSuccessProgressCall:b})}):()=>{}),x=d=>(o.logger("onSuccess"),b=!0,v().catch(_),m&&m({isPurgatory:I(A)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),M&&M()}),d),L=d=>{throw o.logger("onFail"),y&&y(),P(),d},$=()=>{o.logger("onFinish"),T&&T()};return o.logger("onBeforeProgressCall"),p&&p(t),w().then(x).catch(d=>L(d)).finally($)});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:l,sendEncodings:u,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,setRemoteStreams:k,onBeforeProgressCall:f,onSuccessProgressCall:p,onEnterPurgatory:m,onEnterConference:h,onFailProgressCall:E,onFinishProgressCall:y,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:k}),v=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{M().catch(_)}}),O=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});o.logger("answerIncomingCall",e);const N=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:s,iceServers:r,contentHint:i,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,sendEncodings:D({mediaStream:t,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:O,ontrack:v}),w=()=>{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,I(A)?m&&m():h&&h({isSuccessProgressCall:b})}):()=>{}),x=d=>(o.logger("onSuccess"),b=!0,M().catch(_),p&&p({isPurgatory:I(A)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),T&&T()}),d),L=d=>{throw o.logger("onFail"),E&&E(),P(),d},$=()=>{o.logger("onFinish"),y&&y()};if(o.logger("onBeforeProgressCall"),f){const d=w();f(d)}return N().then(x).catch(d=>L(d)).finally($)});a(this,"updatePresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g})=>{const S=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return o.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:s,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:S})});a(this,"startPresentation",async({mediaStream:e,isP2P:t,maxBitrate:s,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g},S)=>{const C=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return o.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:s,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:C},S)});a(this,"stopShareSipConnector",async({isP2P:e=!1}={})=>(o.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{o.logger(t)})));a(this,"sendRefusalToTurnOnMic",async()=>{this.sipConnector.isCallActive&&(o.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{o.logger("sendRefusalToTurnOnMic: error",e)}))});a(this,"sendRefusalToTurnOnCam",async()=>{this.sipConnector.isCallActive&&(o.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{o.logger("sendRefusalToTurnOnCam: error",e)}))});a(this,"sendMediaState",async({isEnabledCam:e,isEnabledMic:t})=>{this.sipConnector.isCallActive&&(o.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t}))});a(this,"replaceMediaStream",async(e,{deleteExisting:t,addMissing:s,forceRenegotiation:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u}={})=>{const g=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return o.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:s,forceRenegotiation:r,contentHint:i,sendEncodings:D({mediaStream:e,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:g})});a(this,"askPermissionToEnableCam",async()=>{this.sipConnector.isCallActive&&(o.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam())});a(this,"resolveHandleReadyRemoteStreamsDebounced",({onReadyRemoteStreams:e})=>ae.debounce(()=>{const t=this.sipConnector.getRemoteStreams();o.logger("remoteStreams",t),t&&e(t)},200));a(this,"resolveHandleReadyRemoteStreams",({onReadyRemoteStreams:e})=>({track:t})=>{Qe(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"&&Je.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(r,i,c);return typeof l=="function"?l.bind(r):l}})}}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.hasCanceledStartPresentationError=o.hasCanceledStartPresentationError;exports.setParametersToSender=o.setParametersToSender;exports.debug=_;exports.SipConnectorFacade=Ze;exports.getCodecFromSender=K;exports.resolveVideoSendingBalancer=je;exports.tools=Oe;
1
+ "use strict";var te=Object.defineProperty;var oe=(n,e,t)=>e in n?te(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./SipConnector-J07EhbbA.cjs"),se=require("sequent-promises"),re=require("stack-promises"),_=require("debug"),ie=require("@krivega/cancelable-promise"),ce=require("repeated-calls"),ae=require("ts-debounce"),U=n=>{const{url:e,cause:t}=n;let o=e;return(t===s.BAD_MEDIA_DESCRIPTION||t===s.NOT_FOUND)&&(o=`${n.message.to.uri.user}@${n.message.to.uri.host}`),o};var W=(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))(W||{});const le=new Error("Unknown error"),ue=(n=le)=>{var r;const{cause:e,socket:t}=n;let o="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case s.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case s.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:t!==void 0&&((r=t._ws)==null?void 0:r.readyState)===3?o="WS_CONNECTION_FAILED":U(n)!==void 0&&U(n)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},de=n=>{let e="";try{e=JSON.stringify(n)}catch(t){s.logger("failed to stringify message",t)}return e},ge=new Error("Unknown error"),Ce=(n=ge)=>{const{code:e,cause:t,message:o}=n,r=U(n),i={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?i.message=de(o):o&&(i.message=String(o)),r!==void 0&&r!==""&&(i.link=r),e!==void 0&&e!==""&&(i.code=e),t!==void 0&&t!==""&&(i.cause=t),i},Se=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:W,getLinkError:U,getTypeFromError:ue,getValuesFromError:Ce},Symbol.toStringTag,{value:"Module"})),fe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:o,isRegistered:r,isPresentationCall:i})=>{const c=[],l=t?"0":"1",u=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(r===!1||r===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),i===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},me="[@*!|]",he="_",Re=n=>{let e=n;return e=e.replaceAll(new RegExp(me,"g"),he),e},pe=({appName:n,appVersion:e,browserName:t,browserVersion:o})=>{const i=`${Re(n)} ${e}`;return`ChromeNew - ${t?`${t} ${o}, ${i}`:i}`},Ee=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:o,appName:r})=>n?pe({appVersion:e,browserName:t,browserVersion:o,appName:r}):"Chrome",G="purgatory",I=n=>n===G,ye=n=>e=>[...e].map(o=>async()=>n(o)),Te=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=ye(e)(n);return se.sequentPromises(r,t)},Me=n=>t=>(s.logger("onStartMainCam"),n.onSession("admin-start-main-cam",t)),be=n=>t=>(s.logger("onStartMic"),n.onSession("admin-start-mic",t)),ve=n=>t=>(s.logger("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),Ae=n=>t=>(s.logger("onStopMic"),n.onSession("admin-stop-mic",t)),_e=({sipConnector:n})=>{const e=(f,p)=>({isSyncForced:m=!1})=>{if(m){f();return}p()},t=Me(n),o=ve(n),r=be(n),i=Ae(n);let c=()=>{},l=()=>{},u=()=>{},g=()=>{};const S=({onStartMainCamForced:f,onStartMainCamNotForced:p,onStopMainCamForced:m,onStopMainCamNotForced:h,onStartMicForced:E,onStartMicNotForced:y,onStopMicForced:T,onStopMicNotForced:M})=>{const A=e(f,p);c=t(A);const O=e(m,h);l=o(O);const N=e(E,y);u=r(N);const w=e(T,M);g=i(w)},C=()=>{c(),l(),u(),g()};return{start:f=>{S(f)},stop:()=>{C()}}},Oe=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:G,createSyncMediaState:_e,error:Se,getExtraHeaders:fe,getUserAgent:Ee,hasPurgatory:I,sendDtmfAccumulated:Te},Symbol.toStringTag,{value:"Module"})),Ne=n=>[...n.keys()].map(e=>n.get(e)),we=(n,e)=>Ne(n).find(t=>t.type===e),K=async n=>n.getStats().then(e=>{const t=we(e,"codec");return t==null?void 0:t.mimeType}),Pe=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),Y=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),De=1e6,R=n=>n*De,z=R(.06),Be=R(4),Ie=n=>n<=64?z: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,Fe="av1",ke=n=>Y(n,Fe),Ve=.6,Q=(n,e)=>ke(e)?n*Ve:n,Ue=n=>Q(z,n),J=(n,e)=>{const t=Ie(n);return Q(t,e)},xe=1,Z=({videoTrack:n,targetSize:e,codec:t})=>{const o=n.getSettings(),r=o.width,i=o.height,c=r/e.width,l=i/e.height,u=Math.max(c,l,xe),g=J(e.width,t);return{scaleResolutionDownBy:u,maxBitrate:g}},ee=re.createStackPromises(),Le=async()=>ee().catch(n=>{s.logger("videoSendingBalancer: error",n)}),$e=async n=>(ee.add(n),Le()),q=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:o})=>$e(async()=>s.setEncodingsToSender(n,{scaleResolutionDownBy:e,maxBitrate:t},o)),He=async({sender:n,codec:e},t)=>{const r=Ue(e);return q({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},V=async({sender:n,videoTrack:e,codec:t},o)=>{const c=e.getSettings().width,l=J(c,t);return q({sender:n,maxBitrate:l,onSetParameters:o,scaleResolutionDownBy:1})},qe=async({sender:n,videoTrack:e,resolution:t,codec:o},r)=>{const[i,c]=t.split("x"),{maxBitrate:l,scaleResolutionDownBy:u}=Z({videoTrack:e,codec:o,targetSize:{width:Number(i),height:Number(c)}});return q({sender:n,maxBitrate:l,onSetParameters:r,scaleResolutionDownBy:u})},Xe=async({mainCam:n,resolutionMainCam:e,sender:t,videoTrack:o,codec:r},i)=>{switch(n){case s.EEventsMainCAM.PAUSE_MAIN_CAM:return He({sender:t,codec:r},i);case s.EEventsMainCAM.RESUME_MAIN_CAM:return V({sender:t,videoTrack:o,codec:r},i);case s.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?qe({sender:t,videoTrack:o,codec:r,resolution:e},i):V({sender:t,videoTrack:o,codec:r},i);case s.EEventsMainCAM.ADMIN_STOP_MAIN_CAM:case s.EEventsMainCAM.ADMIN_START_MAIN_CAM:case void 0:return V({sender:t,videoTrack:o,codec:r},i);default:return V({sender:t,videoTrack:o,codec:r},i)}},X={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},j=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:o,ignoreForCodec:r})=>{const i=t.getSenders(),c=Pe(i);if(!(c!=null&&c.track))return X;const l=await K(c);return Y(l,r)?X:Xe({mainCam:n,resolutionMainCam:e,sender:c,codec:l,videoTrack:c.track},o)},je=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const o=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return j({connection:u,onSetParameters:t,ignoreForCodec:e})};let r=o;const i=u=>{r=async()=>{const{mainCam:g,resolutionMainCam:S}=u,{connection:C}=n;if(!C)throw new Error("connection is not exist");return j({mainCam:g,resolutionMainCam:S,connection:C,onSetParameters:t,ignoreForCodec:e})},r().catch(_)};return{subscribe:()=>{n.onSession("main-cam-control",i)},unsubscribe:()=>{n.offSession("main-cam-control",i)},balanceByTrack:o,resetMainCamControl(){r=o},async reBalance(){return r()}}},We=n=>n.getVideoTracks()[0],D=({mediaStream:n,simulcastEncodings:e,sendEncodings:t})=>{if(e&&e.length>0){const o=t??[],r=We(n);if(r===void 0)throw new Error("No video track");return e.forEach((i,c)=>{const l=o[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}=Z({videoTrack:r,targetSize:{width:i.width,height:i.height}});l.maxBitrate=u,l.scaleResolutionDownBy=g,o[c]=l}),o}return t},Ge=(n,e)=>n.filter(o=>e.some(r=>r.clockRate===o.clockRate&&r.mimeType===o.mimeType&&r.channels===o.channels&&r.sdpFmtpLine===o.sdpFmtpLine)),Ke=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),o=e===null?[]:e.codecs,r=t===null?[]:t.codecs;return Ge(o,r)},Ye=(n,e)=>e===void 0||e.length===0?n:n.sort((t,o)=>{const r=e.indexOf(t.mimeType),i=e.indexOf(o.mimeType),c=r===-1?Number.MAX_VALUE:r,l=i===-1?Number.MAX_VALUE:i;return c-l}),ze=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),B=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>async o=>{var r;try{if(typeof o.setCodecPreferences=="function"&&((r=o.sender.track)==null?void 0:r.kind)==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const i=Ke("video"),c=ze(i,t),l=Ye(c,e);o.setCodecPreferences(l)}Object.keys(n).length>0&&await s.setParametersToSender(o.sender,n)}catch(i){s.logger("updateTransceiver error",i)}},H=n=>{if(!ie.isCanceledError(n)&&!ce.hasCanceledError(n))throw n;return{isSuccessful:!1}},Qe=({kind:n,readyState:e})=>n==="video"&&e==="live",Je=new Set(["on","once","onceRace","wait","off","onSession","onceSession","onceRaceSession","waitSession","offSession","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class Ze{constructor(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:o}={}){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,"sipConnector");a(this,"preferredMimeTypesVideoCodecs");a(this,"excludeMimeTypesVideoCodecs");a(this,"connectToServer",async e=>{const{userAgent:t,sipWebSocketServerURL:o,sipServerUrl:r,remoteAddress:i,displayName:c,name:l,password:u,isRegisteredUser:g,isDisconnectOnFail:S}=e;return s.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:o,sipServerUrl:r,remoteAddress:i,displayName:c,password:u,user:l,register:g}).then(C=>(s.logger("connectToServer then"),{ua:C,isSuccessful:!0})).catch(async C=>(s.logger("connectToServer catch: error",C),S===!0?this.sipConnector.disconnect().then(()=>H(C)).catch(()=>H(C)):H(C)))});a(this,"callToServer",async e=>{const{conference:t,mediaStream:o,extraHeaders:r,iceServers:i,contentHint:c,simulcastEncodings:l,degradationPreference:u,sendEncodings:g,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,setRemoteStreams:f,onBeforeProgressCall:p,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:E,onFailProgressCall:y,onFinishProgressCall:T,onEndedCall:M}=e,A=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:f}),O=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{A().catch(_)}}),N=B({degradationPreference:u},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});s.logger("callToServer",e);const w=async()=>(s.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:r,iceServers:i,contentHint:c,offerToReceiveAudio:S,offerToReceiveVideo:C,directionVideo:F,directionAudio:k,sendEncodings:D({mediaStream:o,simulcastEncodings:l,sendEncodings:g}),number:t,onAddedTransceiver:N,ontrack:O}));let b=!1,v;const P=(s.logger("subscribeEnterConference: onEnterConference",E),h??E?this.sipConnector.onSession("enterRoom",({room:d})=>{s.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),v=d,I(v)?h&&h():E&&E({isSuccessProgressCall:b})}):()=>{}),x=d=>(s.logger("onSuccess"),b=!0,A().catch(_),m&&m({isPurgatory:I(v)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),M&&M()}),d),L=d=>{throw s.logger("onFail"),y&&y(),P(),d},$=()=>{s.logger("onFinish"),T&&T()};return s.logger("onBeforeProgressCall"),p&&p(t),w().then(x).catch(d=>L(d)).finally($)});a(this,"disconnectFromServer",async()=>this.sipConnector.disconnect().then(()=>(s.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(s.logger("disconnectFromServer: catch",e),{isSuccessful:!1})));a(this,"answerIncomingCall",async e=>{const{mediaStream:t,extraHeaders:o,iceServers:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,setRemoteStreams:k,onBeforeProgressCall:f,onSuccessProgressCall:p,onEnterPurgatory:m,onEnterConference:h,onFailProgressCall:E,onFinishProgressCall:y,onEndedCall:T}=e,M=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:k}),A=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{M().catch(_)}}),O=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});s.logger("answerIncomingCall",e);const N=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:o,iceServers:r,contentHint:i,offerToReceiveAudio:g,offerToReceiveVideo:S,directionVideo:C,directionAudio:F,sendEncodings:D({mediaStream:t,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:O,ontrack:A}),w=()=>{const{remoteCallerData:d}=this.sipConnector;return d.incomingNumber};let b=!1,v;const P=(s.logger("subscribeEnterConference: onEnterConference",h),m??h?this.sipConnector.onSession("enterRoom",d=>{s.logger("enterRoom",{_room:d,isSuccessProgressCall:b}),v=d,I(v)?m&&m():h&&h({isSuccessProgressCall:b})}):()=>{}),x=d=>(s.logger("onSuccess"),b=!0,M().catch(_),p&&p({isPurgatory:I(v)}),this.sipConnector.onceRaceSession(["ended","failed"],()=>{P(),T&&T()}),d),L=d=>{throw s.logger("onFail"),E&&E(),P(),d},$=()=>{s.logger("onFinish"),y&&y()};if(s.logger("onBeforeProgressCall"),f){const d=w();f(d)}return N().then(x).catch(d=>L(d)).finally($)});a(this,"updatePresentation",async({mediaStream:e,isP2P:t,maxBitrate:o,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g})=>{const S=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return s.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,maxBitrate:o,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:S})});a(this,"startPresentation",async({mediaStream:e,isP2P:t,maxBitrate:o,contentHint:r,simulcastEncodings:i,degradationPreference:c,sendEncodings:l,preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g},S)=>{const C=B({degradationPreference:c},{preferredMimeTypesVideoCodecs:u,excludeMimeTypesVideoCodecs:g});return s.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,maxBitrate:o,contentHint:r,sendEncodings:D({mediaStream:e,simulcastEncodings:i,sendEncodings:l}),onAddedTransceiver:C},S)});a(this,"stopShareSipConnector",async({isP2P:e=!1}={})=>(s.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{s.logger(t)})));a(this,"sendRefusalToTurnOnMic",async()=>{this.sipConnector.isCallActive&&(s.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{s.logger("sendRefusalToTurnOnMic: error",e)}))});a(this,"sendRefusalToTurnOnCam",async()=>{this.sipConnector.isCallActive&&(s.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{s.logger("sendRefusalToTurnOnCam: error",e)}))});a(this,"sendMediaState",async({isEnabledCam:e,isEnabledMic:t})=>{this.sipConnector.isCallActive&&(s.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t}))});a(this,"replaceMediaStream",async(e,{deleteExisting:t,addMissing:o,forceRenegotiation:r,contentHint:i,simulcastEncodings:c,degradationPreference:l,sendEncodings:u}={})=>{const g=B({degradationPreference:l},{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs});return s.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:o,forceRenegotiation:r,contentHint:i,sendEncodings:D({mediaStream:e,simulcastEncodings:c,sendEncodings:u}),onAddedTransceiver:g})});a(this,"askPermissionToEnableCam",async()=>{this.sipConnector.isCallActive&&(s.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam())});a(this,"resolveHandleReadyRemoteStreamsDebounced",({onReadyRemoteStreams:e})=>ae.debounce(()=>{const t=this.sipConnector.getRemoteStreams();s.logger("remoteStreams",t),t&&e(t)},200));a(this,"resolveHandleReadyRemoteStreams",({onReadyRemoteStreams:e})=>({track:t})=>{Qe(t)&&e()});a(this,"getRemoteStreams",()=>(s.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams()));a(this,"onUseLicense",e=>(s.logger("onUseLicense"),this.sipConnector.onSession("useLicense",e)));a(this,"onMustStopPresentation",e=>(s.logger("onMustStopPresentation"),this.sipConnector.onSession("mustStopPresentation",e)));a(this,"onMoveToSpectators",e=>(s.logger("onMoveToSpectators"),this.sipConnector.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,e)));a(this,"onMoveToParticipants",e=>(s.logger("onMoveToParticipants"),this.sipConnector.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,e)));return this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=o,this.sipConnector=e,new Proxy(this,{get:(r,i,c)=>{if(typeof i=="string"&&Je.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(r,i,c);return typeof l=="function"?l.bind(r):l}})}}exports.EEventsMainCAM=s.EEventsMainCAM;exports.EEventsMic=s.EEventsMic;exports.EEventsSyncMediaState=s.EEventsSyncMediaState;exports.EMimeTypesVideoCodecs=s.EMimeTypesVideoCodecs;exports.EUseLicense=s.EUseLicense;exports.SipConnector=s.SipConnector;exports.causes=s.causes;exports.constants=s.constants;exports.disableDebug=s.disableDebug;exports.enableDebug=s.enableDebug;exports.eventNames=s.eventNames;exports.hasCanceledCallError=s.hasCanceledCallError;exports.hasCanceledStartPresentationError=s.hasCanceledStartPresentationError;exports.setParametersToSender=s.setParametersToSender;exports.debug=_;exports.SipConnectorFacade=Ze;exports.getCodecFromSender=K;exports.resolveVideoSendingBalancer=je;exports.tools=Oe;
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  var oe = Object.defineProperty;
2
2
  var re = (n, e, t) => e in n ? oe(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
3
  var a = (n, e, t) => re(n, typeof e != "symbol" ? e + "" : e, t);
4
- import { B as K, N as Y, l as c, E as B, s as ie, a as ce, P as ae, b as ue } from "./SipConnector-DTNc5BfW.js";
5
- import { j as Rn, k as gn, n as yn, m as Tn, S as En, c as Mn, d as bn, f as _n, g as An, e as vn, h as On, i as Nn } from "./SipConnector-DTNc5BfW.js";
4
+ import { B as K, N as Y, l as c, E as B, s as ie, a as ce, P as ae, b as ue } from "./SipConnector-D9frFCEK.js";
5
+ import { j as Rn, k as gn, n as yn, m as Tn, S as En, c as Mn, d as bn, f as _n, g as An, e as vn, h as On, i as Nn } from "./SipConnector-D9frFCEK.js";
6
6
  import { sequentPromises as de } from "sequent-promises";
7
7
  import { createStackPromises as le } from "stack-promises";
8
8
  import D from "debug";
@@ -81,7 +81,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
81
81
  browserName: t,
82
82
  browserVersion: s,
83
83
  appName: o
84
- }) => n ? _e({ appVersion: e, browserName: t, browserVersion: s, appName: o }) : "Chrome", z = "purgatory", F = (n) => n === z, ve = (n) => (e) => [...e].map((s) => async () => n(s)), Oe = async ({
84
+ }) => n ? _e({ appVersion: e, browserName: t, browserVersion: s, appName: o }) : "Chrome", z = "purgatory", k = (n) => n === z, ve = (n) => (e) => [...e].map((s) => async () => n(s)), Oe = async ({
85
85
  accumulatedKeys: n,
86
86
  sendKey: e,
87
87
  canRunTask: t
@@ -143,10 +143,10 @@ const me = new Error("Unknown error"), he = (n = me) => {
143
143
  error: ye,
144
144
  getExtraHeaders: Te,
145
145
  getUserAgent: Ae,
146
- hasPurgatory: F,
146
+ hasPurgatory: k,
147
147
  sendDtmfAccumulated: Oe
148
- }, Symbol.toStringTag, { value: "Module" })), De = (n) => [...n.keys()].map((e) => n.get(e)), Fe = (n, e) => De(n).find((t) => t.type === e), ke = async (n) => n.getStats().then((e) => {
149
- const t = Fe(e, "codec");
148
+ }, Symbol.toStringTag, { value: "Module" })), De = (n) => [...n.keys()].map((e) => n.get(e)), ke = (n, e) => De(n).find((t) => t.type === e), Fe = async (n) => n.getStats().then((e) => {
149
+ const t = ke(e, "codec");
150
150
  return t == null ? void 0 : t.mimeType;
151
151
  }), Ve = (n) => n.find((e) => {
152
152
  var t;
@@ -251,7 +251,7 @@ const me = new Error("Unknown error"), he = (n = me) => {
251
251
  const r = t.getSenders(), i = Ve(r);
252
252
  if (!(i != null && i.track))
253
253
  return W;
254
- const u = await ke(i);
254
+ const u = await Fe(i);
255
255
  return Q(u, o) ? W : ze(
256
256
  {
257
257
  mainCam: n,
@@ -313,11 +313,12 @@ const me = new Error("Unknown error"), he = (n = me) => {
313
313
  }) => {
314
314
  if (e && e.length > 0) {
315
315
  const s = t ?? [], o = Qe(n);
316
+ if (o === void 0)
317
+ throw new Error("No video track");
316
318
  return e.forEach((r, i) => {
317
319
  const u = s[i] ?? {};
318
320
  u.active = !0, r.rid !== void 0 && (u.rid = r.rid), r.scalabilityMode !== void 0 && (u.scalabilityMode = r.scalabilityMode);
319
321
  const { maxBitrate: d, scaleResolutionDownBy: C } = ne({
320
- // @ts-expect-error
321
322
  videoTrack: o,
322
323
  targetSize: {
323
324
  width: r.width,
@@ -457,7 +458,7 @@ class mn {
457
458
  sendEncodings: C,
458
459
  offerToReceiveAudio: f,
459
460
  offerToReceiveVideo: S,
460
- directionVideo: k,
461
+ directionVideo: F,
461
462
  directionAudio: V,
462
463
  setRemoteStreams: m,
463
464
  onBeforeProgressCall: g,
@@ -490,7 +491,7 @@ class mn {
490
491
  contentHint: i,
491
492
  offerToReceiveAudio: f,
492
493
  offerToReceiveVideo: S,
493
- directionVideo: k,
494
+ directionVideo: F,
494
495
  directionAudio: V,
495
496
  sendEncodings: P({
496
497
  mediaStream: s,
@@ -503,9 +504,9 @@ class mn {
503
504
  }));
504
505
  let b = !1, _;
505
506
  const w = (c("subscribeEnterConference: onEnterConference", y), p ?? y ? this.sipConnector.onSession("enterRoom", ({ room: l }) => {
506
- c("enterRoom", { _room: l, isSuccessProgressCall: b }), _ = l, F(_) ? p && p() : y && y({ isSuccessProgressCall: b });
507
+ c("enterRoom", { _room: l, isSuccessProgressCall: b }), _ = l, k(_) ? p && p() : y && y({ isSuccessProgressCall: b });
507
508
  }) : () => {
508
- }), L = (l) => (c("onSuccess"), b = !0, A().catch(D), h && h({ isPurgatory: F(_) }), this.sipConnector.onceRaceSession(["ended", "failed"], () => {
509
+ }), L = (l) => (c("onSuccess"), b = !0, A().catch(D), h && h({ isPurgatory: k(_) }), this.sipConnector.onceRaceSession(["ended", "failed"], () => {
509
510
  w(), M && M();
510
511
  }), l), $ = (l) => {
511
512
  throw c("onFail"), T && T(), w(), l;
@@ -527,7 +528,7 @@ class mn {
527
528
  offerToReceiveAudio: C,
528
529
  offerToReceiveVideo: f,
529
530
  directionVideo: S,
530
- directionAudio: k,
531
+ directionAudio: F,
531
532
  setRemoteStreams: V,
532
533
  onBeforeProgressCall: m,
533
534
  onSuccessProgressCall: g,
@@ -560,7 +561,7 @@ class mn {
560
561
  offerToReceiveAudio: C,
561
562
  offerToReceiveVideo: f,
562
563
  directionVideo: S,
563
- directionAudio: k,
564
+ directionAudio: F,
564
565
  sendEncodings: P({
565
566
  mediaStream: t,
566
567
  simulcastEncodings: i,
@@ -574,9 +575,9 @@ class mn {
574
575
  };
575
576
  let b = !1, _;
576
577
  const w = (c("subscribeEnterConference: onEnterConference", p), h ?? p ? this.sipConnector.onSession("enterRoom", (l) => {
577
- c("enterRoom", { _room: l, isSuccessProgressCall: b }), _ = l, F(_) ? h && h() : p && p({ isSuccessProgressCall: b });
578
+ c("enterRoom", { _room: l, isSuccessProgressCall: b }), _ = l, k(_) ? h && h() : p && p({ isSuccessProgressCall: b });
578
579
  }) : () => {
579
- }), L = (l) => (c("onSuccess"), b = !0, M().catch(D), g && g({ isPurgatory: F(_) }), this.sipConnector.onceRaceSession(["ended", "failed"], () => {
580
+ }), L = (l) => (c("onSuccess"), b = !0, M().catch(D), g && g({ isPurgatory: k(_) }), this.sipConnector.onceRaceSession(["ended", "failed"], () => {
580
581
  w(), E && E();
581
582
  }), l), $ = (l) => {
582
583
  throw c("onFail"), y && y(), w(), l;
@@ -755,7 +756,7 @@ export {
755
756
  _n as disableDebug,
756
757
  An as enableDebug,
757
758
  vn as eventNames,
758
- ke as getCodecFromSender,
759
+ Fe as getCodecFromSender,
759
760
  On as hasCanceledCallError,
760
761
  Nn as hasCanceledStartPresentationError,
761
762
  fn as resolveVideoSendingBalancer,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "14.1.2-3",
3
+ "version": "14.1.2-5",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -1 +0,0 @@
1
- "use strict";var Ot=Object.defineProperty;var mt=(s,e,t)=>e in s?Ot(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var o=(s,e,t)=>mt(s,typeof e!="symbol"?e+"":e,t);const Mt=require("@krivega/cancelable-promise"),we=require("events-constructor"),G=require("repeated-calls"),J=require("debug"),Dt="Connection Error",ke="Request Timeout",pt="SIP Failure Code",vt="Internal Error",yt="Busy",X="Rejected",wt="Redirected",bt="Unavailable",Be="Not Found",Ut="Address Incomplete",Lt="Incompatible SDP",Ht="Missing SDP",Wt="Authentication Error",Fe="Terminated",kt="WebRTC Error",Q="Canceled",Bt="No Answer",Ft="Expires",xt="No ACK",Vt="Dialog Error",Yt="User Denied Media Access",xe="Bad Media Description",qt="RTP Timeout",$t=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Ut,AUTHENTICATION_ERROR:Wt,BAD_MEDIA_DESCRIPTION:xe,BUSY:yt,BYE:Fe,CANCELED:Q,CONNECTION_ERROR:Dt,DIALOG_ERROR:Vt,EXPIRES:Ft,INCOMPATIBLE_SDP:Lt,INTERNAL_ERROR:vt,MISSING_SDP:Ht,NOT_FOUND:Be,NO_ACK:xt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:X,REQUEST_TIMEOUT:ke,RTP_TIMEOUT:qt,SIP_FAILURE_CODE:pt,UNAVAILABLE:bt,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),z="incomingCall",j="declinedIncomingCall",K="failedIncomingCall",Z="terminatedIncomingCall",F="connecting",P="connected",C="disconnected",y="newRTCSession",O="registered",ee="unregistered",m="registrationFailed",Ve="newMessage",te="sipEvent",ne="availableSecondRemoteStream",se="notAvailableSecondRemoteStream",ie="mustStopPresentation",w="shareState",re="enterRoom",oe="useLicense",ae="peerconnection:confirmed",ce="peerconnection:ontrack",b="channels",Ee="channels:notify",de="ended:fromserver",he="main-cam-control",Se="admin-stop-main-cam",Te="admin-start-main-cam",le="admin-stop-mic",ue="admin-start-mic",U="admin-force-sync-media-state",ge="participant:added-to-list-moderators",Ce="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",x="participant:move-request-to-spectators",V="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ae="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ie="account:changed",Pe="account:deleted",Oe="conference:participant-token-issued",M="ended",Ye="sending",qe="reinvite",$e="replaces",Ge="refer",Je="progress",Xe="accepted",L="confirmed",H="peerconnection",A="failed",Qe="muted",ze="unmuted",me="newDTMF",Me="newInfo",je="hold",Ke="unhold",Ze="update",et="sdp",tt="icecandidate",nt="getusermediafailed",st="peerconnection:createofferfailed",it="peerconnection:createanswerfailed",rt="peerconnection:setlocaldescriptionfailed",ot="peerconnection:setremotedescriptionfailed",at="presentation:start",ct="presentation:started",Et="presentation:end",De="presentation:ended",W="presentation:failed",dt="SPECTATOR",ht="PARTICIPANT",St=1e6;var _=(s=>(s.LOCAL="local",s.REMOTE="remote",s.SYSTEM="system",s))(_||{});const Gt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Xe,ACCOUNT_CHANGED:Ie,ACCOUNT_DELETED:Pe,ADMIN_FORCE_SYNC_MEDIA_STATE:U,ADMIN_START_MAIN_CAM:Te,ADMIN_START_MIC:ue,ADMIN_STOP_MAIN_CAM:Se,ADMIN_STOP_MIC:le,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ne,CHANNELS:b,CHANNELS_NOTIFY:Ee,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Oe,CONFIRMED:L,CONNECTED:P,CONNECTING:F,DECLINED_INCOMING_CALL:j,DISCONNECTED:C,ENDED:M,ENDED_FROM_SERVER:de,ENTER_ROOM:re,FAILED:A,FAILED_INCOMING_CALL:K,GET_USER_MEDIA_FAILED:nt,HOLD:je,ICE_CANDIDATE:tt,INCOMING_CALL:z,MAIN_CAM_CONTROL:he,MUST_STOP_PRESENTATION_EVENT:ie,MUTED:Qe,NEW_DTMF:me,NEW_INFO:Me,NEW_MESSAGE:Ve,NEW_RTC_SESSION:y,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:se,ONE_MEGABIT_IN_BITS:St,Originator:_,PARTICIPANT:ht,PARTICIPANT_ADDED_TO_LIST_MODERATORS:ge,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:x,PARTICIPANT_MOVE_REQUEST_TO_STREAM:_e,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Ce,PARTICIPATION_ACCEPTING_WORD_REQUEST:Ne,PARTICIPATION_CANCELLING_WORD_REQUEST:Ae,PEER_CONNECTION:H,PEER_CONNECTION_CONFIRMED:ae,PEER_CONNECTION_CREATE_ANSWER_FAILED:it,PEER_CONNECTION_CREATE_OFFER_FAILED:st,PEER_CONNECTION_ONTRACK:ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:rt,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:ot,PRESENTATION_END:Et,PRESENTATION_ENDED:De,PRESENTATION_FAILED:W,PRESENTATION_START:at,PRESENTATION_STARTED:ct,PROGRESS:Je,REFER:Ge,REGISTERED:O,REGISTRATION_FAILED:m,REINVITE:qe,REPLACES:$e,SDP:et,SENDING:Ye,SHARE_STATE:w,SIP_EVENT:te,SPECTATOR:dt,TERMINATED_INCOMING_CALL:Z,UNHOLD:Ke,UNMUTED:ze,UNREGISTERED:ee,UPDATE:Ze,USE_LICENSE:oe,WEBCAST_STARTED:Re,WEBCAST_STOPPED:fe},Symbol.toStringTag,{value:"Module"})),Tt=[z,j,Z,K,Ne,Ae,_e,Ee,Oe,Ie,Pe,Re,fe,ge,Ce],Y=[F,P,C,y,O,ee,m,Ve,te],lt=[ne,se,ie,w,re,oe,ae,ce,b,de,he,Te,Se,le,ue,U,x,V],pe=[M,F,Ye,qe,$e,Ge,Je,Xe,L,H,A,Qe,ze,me,Me,je,Ke,Ze,et,tt,nt,st,it,rt,ot,at,ct,Et,De,W],ut=[...Y,...Tt],ve=[...pe,...lt],Jt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:ve,SESSION_JSSIP_EVENT_NAMES:pe,SESSION_SYNTHETICS_EVENT_NAMES:lt,UA_EVENT_NAMES:ut,UA_JSSIP_EVENT_NAMES:Y,UA_SYNTHETICS_EVENT_NAMES:Tt},Symbol.toStringTag,{value:"Module"})),ye="sip-connector",v=J(ye),Xt=()=>{J.enable(ye)},Qt=()=>{J.enable(`-${ye}`)},zt=(s,e)=>(s.degradationPreference=e.degradationPreference,s),jt=(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,Kt=gt(),Zt=(s,e)=>{if(Kt(s,e))return s},en=(s,e)=>{const t=s.maxBitrate,n=Zt(e,t);return n!==void 0&&(s.maxBitrate=n),s},Ct=1,tn=gt(Ct),nn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,Ct);if(t!==void 0&&tn(t,e))return t},sn=(s,e)=>{const t=s.scaleResolutionDownBy,n=nn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},rn=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return jt(s,t),s.encodings.forEach((i,r)=>{const a=((e==null?void 0:e.encodings)??[])[r],c=a==null?void 0:a.maxBitrate,E=a==null?void 0:a.scaleResolutionDownBy;en(i,c),sn(i,E)}),s},on=(s,e)=>{var t,n,i,r,a,c,E,d,T,l,S,u;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let h=0;h<(((i=s.codecs)==null?void 0:i.length)??0);h++)if(JSON.stringify(s.codecs[h])!==JSON.stringify(e.codecs[h]))return!0;if(((r=s.headerExtensions)==null?void 0:r.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let h=0;h<(((c=s.headerExtensions)==null?void 0:c.length)??0);h++)if(JSON.stringify(s.headerExtensions[h])!==JSON.stringify(e.headerExtensions[h]))return!0;if(((E=s.encodings)==null?void 0:E.length)!==((d=e.encodings)==null?void 0:d.length))return!0;for(let h=0;h<(s.encodings.length??0);h++)if(JSON.stringify(s.encodings[h])!==JSON.stringify(e.encodings[h]))return!0;return((T=s.rtcp)==null?void 0:T.cname)!==((l=e.rtcp)==null?void 0:l.cname)||((S=s.rtcp)==null?void 0:S.reducedSize)!==((u=e.rtcp)==null?void 0:u.reducedSize)||s.degradationPreference!==e.degradationPreference},_t=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));rn(t,e),zt(t,e);const i=on(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}};var R=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(R||{}),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||{}),Nt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Nt||{}),At=(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))(At||{});const Rt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await _t(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}};function an(s){return e=>`sip:${e}@${s}`}const cn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,be=s=>s.trim().replaceAll(" ","_"),En=cn(1e5,99999999),dn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),hn=s=>{const e=[];return s!==void 0&&s!==""&&e.push(`X-Vinteo-Remote: ${s}`),e},Sn="content-type",Tn="x-webrtc-enter-room",D="application/vinteo.webrtc.sharedesktop",ln="application/vinteo.webrtc.roomname",un="application/vinteo.webrtc.channels",gn="application/vinteo.webrtc.mediastate",Cn="application/vinteo.webrtc.refusal",Ue="application/vinteo.webrtc.maincam",_n="application/vinteo.webrtc.mic",Nn="application/vinteo.webrtc.uselic",An="X-WEBRTC-USE-LICENSE",Rn="X-WEBRTC-PARTICIPANT-NAME",Le="X-WEBRTC-INPUT-CHANNELS",He="X-WEBRTC-OUTPUT-CHANNELS",fn="X-WEBRTC-MAINCAM",In="X-WEBRTC-MIC",We="X-WEBRTC-SYNC",Pn="X-WEBRTC-MAINCAM-RESOLUTION",On="X-WEBRTC-MEDIA-STATE",mn="X-Vinteo-Media-Type",Mn="X-Vinteo-MainCam-State",Dn="X-Vinteo-Mic-State",pn="application/vinteo.webrtc.partstate",vn="X-WEBRTC-PARTSTATE",yn="application/vinteo.webrtc.notify",wn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",bn=`${f}: LETMESTARTPRESENTATION`,Un=`${f}: STOPPRESENTATION`,ft="YOUCANRECEIVECONTENT",It="CONTENTEND",Pt="YOUMUSTSTOPSENDCONTENT",Ln=`${f}: ${Pt}`,Hn=`${f}: ${ft}`,Wn=`${f}: ${It}`,kn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Bn=`${kn}: LETMESTARTMAINCAM`,Fn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(s,{directionVideo:e,directionAudio:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),r=e==="recvonly"?[]:s.getVideoTracks(),a=[...i,...r],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Fn(c,n),c},xn="Error decline with 603",Vn=1006,Yn=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===Vn,qn=s=>s.message===xn,$n=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Gn=async(s,e,t)=>{const n=$n(s,e);if(n)return Rt(n,{maxBitrate:t})},Jn=486,Xn=487,Qn=3,zn=1,jn=s=>s instanceof Object&&("originator"in s||"cause"in s),Kn=s=>{if(Mt.isCanceledError(s))return!0;if(!jn(s))return!1;const{originator:e,cause:t}=s;return typeof t=="string"?t===ke||t===X||e===_.LOCAL&&(t===Q||t===Fe):!1},Zn=s=>G.hasCanceledError(s),es="channels",ts="WebcastStarted",ns="WebcastStopped",ss="accountChanged",is="accountDeleted",rs="addedToListModerators",os="removedFromListModerators",as="ParticipationRequestAccepted",cs="ParticipationRequestRejected",Es="ParticipantMovedToWebcast",ds="ConferenceParticipantTokenIssued";class hs{constructor({JsSIP:e}){o(this,"promisePendingStartPresentation");o(this,"promisePendingStopPresentation");o(this,"ua");o(this,"rtcSession");o(this,"incomingRTCSession");o(this,"streamPresentationCurrent");o(this,"socket");o(this,"isRegisterConfigInner",!1);o(this,"connectionConfiguration",{});o(this,"remoteStreams",{});o(this,"JsSIP");o(this,"sessionEvents");o(this,"uaEvents");o(this,"cancelableConnectWithRepeatedCalls");o(this,"cancelableSendPresentationWithRepeatedCalls");o(this,"isPendingConnect",!1);o(this,"isPendingInitUa",!1);o(this,"isPendingCall",!1);o(this,"isPendingAnswer",!1);o(this,"connect",async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t)));o(this,"hangUp",async()=>(this.cancelRequests(),this.hangUpWithoutCancelRequests()));o(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){v("tryRegister",e)}return this.register()});o(this,"declineToIncomingCall",async({statusCode:e=Xn}={})=>new Promise((t,n)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.uaEvents.trigger(j,r),i.terminate({status_code:e}),t()}catch(i){n(i)}}));o(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Jn}));o(this,"set",async({displayName:e,password:t})=>new Promise((n,i)=>{const{ua:r}=this;if(!r){i(new Error("this.ua is not initialized"));return}let a=!1,c=!1;e!==void 0&&e!==this.connectionConfiguration.displayName&&(a=r.set("display_name",be(e)),this.connectionConfiguration.displayName=e),t!==void 0&&t!==this.connectionConfiguration.password&&(c=r.set("password",t),this.connectionConfiguration.password=t);const E=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(E)}).catch(d=>{i(d)}):E?n(E):i(new Error("nothing changed"))}));o(this,"disconnect",async()=>{this.off(y,this.handleNewRTCSession);const e=new Promise(n=>{this.once(C,()=>{n()})}),{ua:t}=this;return t?(await this.hangUpWithoutCancelRequests(),t.stop()):this.uaEvents.trigger(C,void 0),e.finally(()=>{delete this.ua})});o(this,"call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:r,directionVideo:a,directionAudio:c,contentHint:E,offerToReceiveAudio:d=!0,offerToReceiveVideo:T=!0,sendEncodings:l,onAddedTransceiver:S})=>(this.isPendingCall=!0,new Promise((u,h)=>{const{ua:g}=this;if(!g){h(new Error("this.ua is not initialized"));return}this.connectionConfiguration.number=e,this.connectionConfiguration.answer=!1,this.handleCall({ontrack:i}).then(u).catch(N=>{h(N)}),this.rtcSession=g.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{directionVideo:a,directionAudio:c,contentHint:E}),eventHandlers:this.sessionEvents.triggers,directionVideo:a,directionAudio:c,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:d,offerToReceiveVideo:T},sendEncodings:l,onAddedTransceiver:S})}).finally(()=>{this.isPendingCall=!1})));o(this,"answerToIncomingCall",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,directionVideo:r,directionAudio:a,offerToReceiveAudio:c,offerToReceiveVideo:E,contentHint:d,sendEncodings:T,onAddedTransceiver:l})=>(this.isPendingAnswer=!0,new Promise((S,u)=>{try{const h=this.getIncomingRTCSession();this.rtcSession=h,this.removeIncomingSession(),this.sessionEvents.eachTriggers((N,q)=>{const I=pe.find($=>$===q);I&&h.on(I,N)}),this.connectionConfiguration.answer=!0,this.connectionConfiguration.number=h.remote_identity.uri.user,this.handleCall({ontrack:t}).then(S).catch(N=>{u(N)});const g=p(e,{directionVideo:r,directionAudio:a,contentHint:d});h.answer({extraHeaders:n,directionVideo:r,directionAudio:a,mediaStream:g,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:E},sendEncodings:T,onAddedTransceiver:l})}catch(h){u(h)}}).finally(()=>{this.isPendingAnswer=!1})));o(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:r})=>{r===_.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));o(this,"removeIncomingSession",()=>{delete this.incomingRTCSession});o(this,"getSipServerUrl",e=>e);o(this,"connectWithDuplicatedCalls",async(e,{callLimit:t=Qn}={})=>{const n=async()=>this.connectInner(e),i=r=>{var d;const c=((d=this.ua)==null?void 0:d.isConnected())===!0&&this.hasEqualConnectionConfiguration(e),E=r!=null&&!Yn(r);return c||E};return this.isPendingConnect=!0,this.cancelableConnectWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r}).finally(()=>{this.isPendingConnect=!1})});o(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===_.REMOTE){this.incomingRTCSession=t;const n=this.remoteCallerData;t.on(A,i=>{this.removeIncomingSession(),i.originator===_.LOCAL?this.uaEvents.trigger(Z,n):this.uaEvents.trigger(K,n)}),this.uaEvents.trigger(z,n)}});o(this,"connectInner",async e=>this.initUa(e).then(async()=>this.start()));o(this,"initUa",async({user:e,password:t,sipServerUrl:n,sipWebSocketServerURL:i,remoteAddress:r,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T,displayName:l="",register:S=!1,extraHeaders:u=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(S&&(e===void 0||e===""))throw new Error("user is required for authorized connection");if(S&&(t===void 0||t===""))throw new Error("password is required for authorized connection");this.isPendingInitUa=!0;try{this.connectionConfiguration={sipServerUrl:n,displayName:l,register:S,user:e,password:t};const{configuration:h,helpers:g}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:l,register:S,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:E,connectionRecoveryMaxInterval:d,userAgent:T});return this.getSipServerUrl=g.getSipServerUrl,this.socket=g.socket,this.ua&&await this.disconnect(),this.isRegisterConfigInner=!!S,this.ua=this.createUa({...h,remoteAddress:r,extraHeaders:u}),this.uaEvents.eachTriggers((N,q)=>{const I=Y.find($=>$===q);I&&this.ua&&this.ua.on(I,N)}),this.ua}finally{this.isPendingInitUa=!1}});o(this,"createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e!==void 0&&e!==""?hn(e):[],...t];return a.length>0&&i.registrator().setExtraHeaders(a),i});o(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)},r=E=>{c(),t(E)},a=()=>{this.isRegisterConfig?(this.on(O,i),this.on(m,r)):this.on(P,i),this.on(C,r)},c=()=>{this.off(O,i),this.off(m,r),this.off(P,i),this.off(C,r)};a(),this.on(y,this.handleNewRTCSession),n.start()}));o(this,"handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(H,T),this.onSession(L,l)},r=()=>{this.offSession(H,T),this.offSession(L,l)},a=()=>{this.onSession(A,E),this.onSession(M,E)},c=()=>{this.offSession(A,E),this.offSession(M,E)},E=S=>{r(),c(),n(S)};let d;const T=({peerconnection:S})=>{d=S,d.ontrack=u=>{this.sessionEvents.trigger(ce,d),e&&e(u)}},l=()=>{d!==void 0&&this.sessionEvents.trigger(ae,d),r(),c(),t(d)};i(),a()}));o(this,"restoreSession",()=>{this.cancelRequestsAndResetPresentation(),delete this.connectionConfiguration.number,delete this.rtcSession,this.remoteStreams={}});o(this,"hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.rtcSession){const{rtcSession:e}=this;if(this.streamPresentationCurrent)try{await this.stopPresentation()}catch(t){v("error stop presentation: ",t)}if(this.restoreSession(),!e.isEnded())return e.terminateAsync({cause:Q})}});o(this,"handleShareState",e=>{switch(e){case ft:{this.sessionEvents.trigger(ne,void 0);break}case It:{this.sessionEvents.trigger(se,void 0);break}case Pt:{this.sessionEvents.trigger(ie,void 0);break}}});o(this,"maybeTriggerChannels",e=>{const t=e.getHeader(Le),n=e.getHeader(He);if(t&&n){const i={inputChannels:t,outputChannels:n};this.sessionEvents.trigger(b,i)}});o(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 ds:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:v("unknown cmd",e.cmd)}});o(this,"triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this.uaEvents.trigger(Ce,t)});o(this,"triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this.uaEvents.trigger(ge,t)});o(this,"triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(Re,n)});o(this,"triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this.uaEvents.trigger(fe,n)});o(this,"triggerAccountChangedNotify",()=>{this.uaEvents.trigger(Ie,void 0)});o(this,"triggerAccountDeletedNotify",()=>{this.uaEvents.trigger(Pe,void 0)});o(this,"triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this.uaEvents.trigger(Oe,i)});o(this,"triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this.uaEvents.trigger(Ee,i)});o(this,"triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ne,t)});o(this,"triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(Ae,t)});o(this,"triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this.uaEvents.trigger(_e,t)});o(this,"triggerEnterRoom",e=>{const t=e.getHeader(Tn),n=e.getHeader(Rn);this.sessionEvents.trigger(re,{room:t,participantName:n})});o(this,"triggerShareState",e=>{const t=e.getHeader(f);this.sessionEvents.trigger(w,t)});o(this,"maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(vn);t===dt&&this.sessionEvents.trigger(x,void 0),t===ht&&this.sessionEvents.trigger(V,void 0)});o(this,"triggerMainCamControl",e=>{const t=e.getHeader(fn),n=e.getHeader(We),i=n===B.ADMIN_SYNC_FORCED;if(t===R.ADMIN_START_MAIN_CAM){this.sessionEvents.trigger(Te,{isSyncForced:i});return}if(t===R.ADMIN_STOP_MAIN_CAM){this.sessionEvents.trigger(Se,{isSyncForced:i});return}(t===R.RESUME_MAIN_CAM||t===R.PAUSE_MAIN_CAM)&&n!==void 0&&this.sessionEvents.trigger(U,{isSyncForced:i});const r=e.getHeader(Pn);this.sessionEvents.trigger(he,{mainCam:t,resolutionMainCam:r})});o(this,"triggerMicControl",e=>{const t=e.getHeader(In),i=e.getHeader(We)===B.ADMIN_SYNC_FORCED;t===k.ADMIN_START_MIC?this.sessionEvents.trigger(ue,{isSyncForced:i}):t===k.ADMIN_STOP_MIC&&this.sessionEvents.trigger(le,{isSyncForced:i})});o(this,"triggerUseLicense",e=>{const t=e.getHeader(An);this.sessionEvents.trigger(oe,t)});o(this,"handleNewInfo",e=>{const{originator:t}=e;if(t!==_.REMOTE)return;const{request:n}=e,i=n.getHeader(Sn);if(i)switch(i){case ln:{this.triggerEnterRoom(n),this.maybeTriggerChannels(n);break}case yn:{this.maybeHandleNotify(n);break}case D:{this.triggerShareState(n);break}case Ue:{this.triggerMainCamControl(n);break}case _n:{this.triggerMicControl(n);break}case Nn:{this.triggerUseLicense(n);break}case pn:{this.maybeTriggerParticipantMoveRequest(n);break}}});o(this,"handleSipEvent",({request:e})=>{this.maybeHandleNotify(e)});o(this,"maybeHandleNotify",e=>{const t=e.getHeader(wn);if(t){const n=JSON.parse(t);this.handleNotify(n)}});o(this,"handleEnded",e=>{const{originator:t}=e;t===_.REMOTE&&this.sessionEvents.trigger(de,e),this.restoreSession()});this.JsSIP=e,this.sessionEvents=new we(ve),this.uaEvents=new we(ut),this.onSession(w,this.handleShareState),this.onSession(Me,this.handleNewInfo),this.on(te,this.handleSipEvent),this.onSession(A,this.handleEnded),this.onSession(M,this.handleEnded)}get connection(){var t;return(t=this.rtcSession)==null?void 0:t.connection}get remoteCallerData(){var e,t,n;return{displayName:(e=this.incomingRTCSession)==null?void 0:e.remote_identity.display_name,host:(t=this.incomingRTCSession)==null?void 0:t.remote_identity.uri.host,incomingNumber:(n=this.incomingRTCSession)==null?void 0:n.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get requested(){return this.isPendingInitUa||this.isPendingConnect||this.isPendingCall||this.isPendingAnswer}get establishedRTCSession(){var e;return((e=this.rtcSession)==null?void 0:e.isEstablished())===!0?this.rtcSession:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this.isRegisterConfigInner}get isCallActive(){return!!(this.ua&&this.rtcSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(O,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,r)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{i()},failed:r}})}catch(a){r(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:r,extraHeaders:a}){return new Promise((c,E)=>{const{configuration:d}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),T=this.createUa({...d,remoteAddress:r,extraHeaders:a}),l=()=>{const u=new Error("Telephony is not available");E(u)};T.once(C,l);const S=()=>{T.removeAllListeners(),T.once(C,c),T.stop()};T.once(P,S),T.start()})}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:n}=t??{},i=p(e,{contentHint:n});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.rtcSession)throw new Error("No rtcSession established");const t=[Bn];return this.rtcSession.sendInfo(Ue,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(qn(n))throw n})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:c}={},E){const d=this.establishedRTCSession;if(!d)throw new Error("No rtcSession established");if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return n===!0&&await this.sendMustStopPresentation(),this.sendPresentationWithDuplicatedCalls({rtcSession:d,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:c},options:E})}async stopPresentation({isP2P:e=!1}={}){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=e?[Wn]:[Un],r=this.establishedRTCSession;return r&&t&&(n=n.then(async()=>r.sendInfo(D,void 0,{extraHeaders:i})).then(async()=>r.stopPresentation(t)).catch(a=>{throw this.sessionEvents.trigger(W,a),a})),!r&&t&&this.sessionEvents.trigger(De,t),this.promisePendingStopPresentation=n,n.finally(()=>{this.resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:r,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:r,onAddedTransceiver:a})}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 dn(t)?this.generateStreams(t):this.generateAudioStreams(t)}getIncomingRTCSession(){const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e}cancelSendPresentationWithRepeatedCalls(){var e;(e=this.cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}async waitChannels(){return this.waitSession(b)}async waitSyncMediaState(){return this.waitSession(U)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.rtcSession)throw new Error("No rtcSession established");const n=`${Le}: ${e}`,i=`${He}: ${t}`,r=[n,i];return this.rtcSession.sendInfo(un,void 0,{extraHeaders:r})}async sendMediaState({cam:e,mic:t},n={}){if(!this.rtcSession)throw new Error("No rtcSession established");const i=`${On}: currentstate`,r=`${Mn}: ${Number(e)}`,a=`${Dn}: ${Number(t)}`,c=[i,r,a];return this.rtcSession.sendInfo(gn,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async sendRefusalToTurnOn(e,t={}){if(!this.rtcSession)throw new Error("No rtcSession established");const c=[`${mn}: ${e==="mic"?0:1}`];return this.rtcSession.sendInfo(Cn,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})}async sendMustStopPresentation(){const e=this.establishedRTCSession;if(!e)throw new Error("No rtcSession established");await e.sendInfo(D,void 0,{extraHeaders:[Ln]})}async sendPresentationWithDuplicatedCalls({rtcSession:e,stream:t,presentationOptions:n,options:i={callLimit:zn}}){const r=async()=>this.sendPresentation(e,t,n),a=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:r,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.uri.toString()===t.uri&&n.display_name===t.display_name&&n.user_agent===t.user_agent&&n.sockets===t.sockets&&n.session_timers===t.session_timers&&n.register_expires===t.register_expires&&n.connection_recovery_min_interval===t.connection_recovery_min_interval&&n.connection_recovery_max_interval===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:c=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:d=2,connectionRecoveryMaxInterval:T=6,userAgent:l}){if(a&&(t===void 0||t===""))throw new Error("password is required for authorized connection");const S=a&&e!==void 0&&e.trim()!==""?e.trim():`${En()}`,u=an(r),h=u(S),g=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:h,display_name:be(i),user_agent:l,sdp_semantics:"unified-plan",sockets:[g],session_timers:c,register_expires:E,connection_recovery_min_interval:d,connection_recovery_max_interval:T},helpers:{socket:g,getSipServerUrl:u}}}async sendPresentation(e,t,{maxBitrate:n=St,isNeedReinvite:i=!0,isP2P:r=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:E}){const d=p(t,{contentHint:a});if(d===void 0)throw new Error("No streamPresentationCurrent");this.streamPresentationCurrent=d;const T=r?[Hn]:[bn],l=e.sendInfo(D,void 0,{extraHeaders:T}).then(async()=>e.startPresentation(d,i,{sendEncodings:c,onAddedTransceiver:E})).then(async()=>{const{connection:S}=this;if(!S)return;const u=S.getSenders();await Gn(u,t,n)}).then(()=>t).catch(S=>{throw this.removeStreamPresentationCurrent(),this.sessionEvents.trigger(W,S),S});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}cancelRequestsAndResetPresentation(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}generateStream(e,t){const{id:n}=e,i=this.remoteStreams[n]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[n]=i,i}generateAudioStream(e){const{id:t}=e,n=this.remoteStreams[t]??new MediaStream;return n.addTrack(e),this.remoteStreams[t]=n,n}generateStreams(e){const t=[];return e.forEach((n,i)=>{if(n.kind==="audio")return;const r=n,a=e[i-1];let c;(a==null?void 0:a.kind)==="audio"&&(c=a);const E=this.generateStream(r,c);t.push(E)}),t}generateAudioStreams(e){return e.map(n=>this.generateAudioStream(n))}cancelRequests(){this.cancelConnectWithRepeatedCalls()}cancelConnectWithRepeatedCalls(){var e;(e=this.cancelableConnectWithRepeatedCalls)==null||e.cancel()}}exports.BAD_MEDIA_DESCRIPTION=xe;exports.EEventsMainCAM=R;exports.EEventsMic=k;exports.EEventsSyncMediaState=B;exports.EMimeTypesVideoCodecs=At;exports.EUseLicense=Nt;exports.NOT_FOUND=Be;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=x;exports.REJECTED=X;exports.SESSION_EVENT_NAMES=ve;exports.SipConnector=hs;exports.UA_JSSIP_EVENT_NAMES=Y;exports.causes=$t;exports.constants=Gt;exports.disableDebug=Qt;exports.enableDebug=Xt;exports.eventNames=Jt;exports.hasCanceledCallError=Kn;exports.hasCanceledStartPresentationError=Zn;exports.logger=v;exports.setEncodingsToSender=Rt;exports.setParametersToSender=_t;