sip-connector 11.3.0 → 11.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";var Dt=Object.defineProperty;var Mt=(s,e,t)=>e in s?Dt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var o=(s,e,t)=>Mt(s,typeof e!="symbol"?e+"":e,t);const C=require("@krivega/cancelable-promise"),be=require("events-constructor"),we=require("repeated-calls"),G=require("debug"),pt="Connection Error",Be="Request Timeout",vt="SIP Failure Code",yt="Internal Error",bt="Busy",$="Rejected",wt="Redirected",Ut="Unavailable",Fe="Not Found",Lt="Address Incomplete",Ht="Incompatible SDP",Wt="Missing SDP",qt="Authentication Error",Ve="Terminated",kt="WebRTC Error",xe="Canceled",Bt="No Answer",Ft="Expires",Vt="No ACK",xt="Dialog Error",Yt="User Denied Media Access",Ye="Bad Media Description",Gt="RTP Timeout",$t=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Lt,AUTHENTICATION_ERROR:qt,BAD_MEDIA_DESCRIPTION:Ye,BUSY:bt,BYE:Ve,CANCELED:xe,CONNECTION_ERROR:pt,DIALOG_ERROR:xt,EXPIRES:Ft,INCOMPATIBLE_SDP:Ht,INTERNAL_ERROR:yt,MISSING_SDP:Wt,NOT_FOUND:Fe,NO_ACK:Vt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:$,REQUEST_TIMEOUT:Be,RTP_TIMEOUT:Gt,SIP_FAILURE_CODE:vt,UNAVAILABLE:Ut,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),J="incomingCall",X="declinedIncomingCall",Q="failedIncomingCall",z="terminatedIncomingCall",B="connecting",P="connected",N="disconnected",y="newRTCSession",m="registered",j="unregistered",O="registrationFailed",Ge="newMessage",K="sipEvent",Z="availableSecondRemoteStream",ee="notAvailableSecondRemoteStream",te="mustStopPresentation",b="shareState",ne="enterRoom",se="useLicense",ie="peerconnection:confirmed",oe="peerconnection:ontrack",w="channels",re="channels:notify",ae="ended:fromserver",ce="main-cam-control",Ee="admin-stop-main-cam",_e="admin-start-main-cam",le="admin-stop-mic",de="admin-start-mic",U="admin-force-sync-media-state",he="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",ue="participant:move-request-to-stream",F="participant:move-request-to-spectators",V="participant:move-request-to-participants",Se="participation:accepting-word-request",Ne="participation:cancelling-word-request",Ce="webcast:started",ge="webcast:stopped",Ae="account:changed",Re="account:deleted",Ie="conference:participant-token-issued",D="ended",$e="sending",Je="reinvite",Xe="replaces",Qe="refer",ze="progress",je="accepted",L="confirmed",H="peerconnection",R="failed",Ke="muted",Ze="unmuted",fe="newDTMF",Pe="newInfo",et="hold",tt="unhold",nt="update",st="sdp",it="icecandidate",ot="getusermediafailed",rt="peerconnection:createofferfailed",at="peerconnection:createanswerfailed",ct="peerconnection:setlocaldescriptionfailed",Et="peerconnection:setremotedescriptionfailed",_t="presentation:start",lt="presentation:started",dt="presentation:end",me="presentation:ended",W="presentation:failed",ht="SPECTATOR",Tt="PARTICIPANT",ut=1e6,Jt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:je,ACCOUNT_CHANGED:Ae,ACCOUNT_DELETED:Re,ADMIN_FORCE_SYNC_MEDIA_STATE:U,ADMIN_START_MAIN_CAM:_e,ADMIN_START_MIC:de,ADMIN_STOP_MAIN_CAM:Ee,ADMIN_STOP_MIC:le,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Z,CHANNELS:w,CHANNELS_NOTIFY:re,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ie,CONFIRMED:L,CONNECTED:P,CONNECTING:B,DECLINED_INCOMING_CALL:X,DISCONNECTED:N,ENDED:D,ENDED_FROM_SERVER:ae,ENTER_ROOM:ne,FAILED:R,FAILED_INCOMING_CALL:Q,GET_USER_MEDIA_FAILED:ot,HOLD:et,ICE_CANDIDATE:it,INCOMING_CALL:J,MAIN_CAM_CONTROL:ce,MUST_STOP_PRESENTATION_EVENT:te,MUTED:Ke,NEW_DTMF:fe,NEW_INFO:Pe,NEW_MESSAGE:Ge,NEW_RTC_SESSION:y,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ee,ONE_MEGABIT_IN_BITS:ut,PARTICIPANT:Tt,PARTICIPANT_ADDED_TO_LIST_MODERATORS:he,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:F,PARTICIPANT_MOVE_REQUEST_TO_STREAM:ue,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Te,PARTICIPATION_ACCEPTING_WORD_REQUEST:Se,PARTICIPATION_CANCELLING_WORD_REQUEST:Ne,PEER_CONNECTION:H,PEER_CONNECTION_CONFIRMED:ie,PEER_CONNECTION_CREATE_ANSWER_FAILED:at,PEER_CONNECTION_CREATE_OFFER_FAILED:rt,PEER_CONNECTION_ONTRACK:oe,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ct,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:Et,PRESENTATION_END:dt,PRESENTATION_ENDED:me,PRESENTATION_FAILED:W,PRESENTATION_START:_t,PRESENTATION_STARTED:lt,PROGRESS:ze,REFER:Qe,REGISTERED:m,REGISTRATION_FAILED:O,REINVITE:Je,REPLACES:Xe,SDP:st,SENDING:$e,SHARE_STATE:b,SIP_EVENT:K,SPECTATOR:ht,TERMINATED_INCOMING_CALL:z,UNHOLD:tt,UNMUTED:Ze,UNREGISTERED:j,UPDATE:nt,USE_LICENSE:se,WEBCAST_STARTED:Ce,WEBCAST_STOPPED:ge},Symbol.toStringTag,{value:"Module"})),St=[J,X,z,Q,Se,Ne,ue,re,Ie,Ae,Re,Ce,ge,he,Te],Oe=[B,P,N,y,m,j,O,Ge,K],Nt=[Z,ee,te,b,ne,se,ie,oe,w,ae,ce,_e,Ee,le,de,U,F,V],De=[D,B,$e,Je,Xe,Qe,ze,je,L,H,R,Ke,Ze,fe,Pe,et,tt,nt,st,it,ot,rt,at,ct,Et,_t,lt,dt,me,W],Me=[...Oe,...St],pe=[...De,...Nt],Xt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:pe,SESSION_JSSIP_EVENT_NAMES:De,SESSION_SYNTHETICS_EVENT_NAMES:Nt,UA_EVENT_NAMES:Me,UA_JSSIP_EVENT_NAMES:Oe,UA_SYNTHETICS_EVENT_NAMES:St},Symbol.toStringTag,{value:"Module"})),Qt=s=>{const e=[];return s&&e.push(`X-Vinteo-Remote: ${s}`),e},zt="content-type",jt="x-webrtc-enter-room",M="application/vinteo.webrtc.sharedesktop",Kt="application/vinteo.webrtc.roomname",Zt="application/vinteo.webrtc.channels",en="application/vinteo.webrtc.mediastate",tn="application/vinteo.webrtc.refusal",Ue="application/vinteo.webrtc.maincam",nn="application/vinteo.webrtc.mic",sn="application/vinteo.webrtc.uselic",on="X-WEBRTC-USE-LICENSE",rn="X-WEBRTC-PARTICIPANT-NAME",Le="X-WEBRTC-INPUT-CHANNELS",He="X-WEBRTC-OUTPUT-CHANNELS",an="X-WEBRTC-MAINCAM",cn="X-WEBRTC-MIC",We="X-WEBRTC-SYNC",En="X-WEBRTC-MAINCAM-RESOLUTION",_n="X-WEBRTC-MEDIA-STATE",ln="X-Vinteo-Media-Type",dn="X-Vinteo-MainCam-State",hn="X-Vinteo-Mic-State",Tn="application/vinteo.webrtc.partstate",un="X-WEBRTC-PARTSTATE",Sn="application/vinteo.webrtc.notify",Nn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",Cn=`${f}: LETMESTARTPRESENTATION`,gn=`${f}: STOPPRESENTATION`,Ct="YOUCANRECEIVECONTENT",gt="CONTENTEND",At="YOUMUSTSTOPSENDCONTENT",An=`${f}: ${At}`,Rn=`${f}: ${Ct}`,In=`${f}: ${gt}`,fn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Pn=`${fn}: LETMESTARTMAINCAM`,ve="sip-connector",v=G(ve),mn=()=>{G.enable(ve)},On=()=>{G.enable(`-${ve}`)},Dn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(s,{videoMode:e,audioMode:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),r=e==="recvonly"?[]:s.getVideoTracks(),a=[...i,...r],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Dn(c,n),c};var I=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(I||{}),q=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(q||{}),k=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(k||{}),Rt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Rt||{});function Mn(s){return e=>`sip:${e}@${s}`}const pn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,qe=s=>s.trim().replaceAll(" ","_"),vn=pn(1e5,99999999),yn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),bn="Error decline with 603",wn=1006,Un=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===wn,Ln=s=>s.message===bn,Hn=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Wn=(s,e)=>(s.degradationPreference=e.degradationPreference,s),qn=(s,e)=>{s.encodings===void 0&&(s.encodings=[]);for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},It=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,kn=It(),Bn=(s,e)=>{if(kn(s,e))return s},Fn=(s,e)=>{const t=s.maxBitrate,n=Bn(e,t);return n!==void 0&&(s.maxBitrate=n),s},ft=1,Vn=It(ft),xn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,ft);if(t!==void 0&&Vn(t,e))return t},Yn=(s,e)=>{const t=s.scaleResolutionDownBy,n=xn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},Gn=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return qn(s,t),s.encodings.forEach((i,r)=>{const a=((e==null?void 0:e.encodings)??[])[r],c=a==null?void 0:a.maxBitrate,_=a==null?void 0:a.scaleResolutionDownBy;Fn(i,c),Yn(i,_)}),s},$n=(s,e)=>{var t,n,i,r,a,c,_,l;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let E=0;E<(((i=s.codecs)==null?void 0:i.length)??0);E++)if(JSON.stringify(s.codecs[E])!==JSON.stringify(e.codecs[E]))return!0;if(((r=s.headerExtensions)==null?void 0:r.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let E=0;E<(((c=s.headerExtensions)==null?void 0:c.length)??0);E++)if(JSON.stringify(s.headerExtensions[E])!==JSON.stringify(e.headerExtensions[E]))return!0;if(((_=s.encodings)==null?void 0:_.length)!==((l=e.encodings)==null?void 0:l.length))return!0;for(let E=0;E<(s.encodings.length??0);E++)if(JSON.stringify(s.encodings[E])!==JSON.stringify(e.encodings[E]))return!0;return s.rtcp.cname!==e.rtcp.cname||s.rtcp.reducedSize!==e.rtcp.reducedSize||s.degradationPreference!==e.degradationPreference},Pt=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));Gn(t,e),Wn(t,e);const i=$n(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}},mt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await Pt(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}},Jn=async(s,e,t)=>{const n=Hn(s,e);if(n)return mt(n,{maxBitrate:t})},Xn=486,Qn=487,Y="local",ke="remote",zn=3,jn=1,Kn=(s=new Error)=>{const{originator:e,cause:t}=s;return C.isCanceledError(s)?!0:typeof t=="string"?t===Be||t===$||e===Y&&(t===xe||t===Ve):!1},g="SipConnector",Zn="channels",es="WebcastStarted",ts="WebcastStopped",ns="accountChanged",ss="accountDeleted",is="addedToListModerators",os="removedFromListModerators",rs="ParticipationRequestAccepted",as="ParticipationRequestRejected",cs="ParticipantMovedToWebcast",Es="ConferenceParticipantTokenIssued";class _s{constructor({JsSIP:e}){o(this,"_isRegisterConfig",!1);o(this,"_connectionConfiguration",{});o(this,"_remoteStreams",{});o(this,"JsSIP");o(this,"_sessionEvents");o(this,"_uaEvents");o(this,"_cancelableConnect");o(this,"_cancelableConnectWithRepeatedCalls");o(this,"_cancelableSendPresentationWithRepeatedCalls");o(this,"_cancelableInitUa");o(this,"_cancelableDisconnect");o(this,"_cancelableSet");o(this,"_cancelableCall");o(this,"_cancelableAnswer");o(this,"_cancelableSendDTMF");o(this,"getSipServerUrl",e=>e);o(this,"promisePendingStartPresentation");o(this,"promisePendingStopPresentation");o(this,"ua");o(this,"session");o(this,"incomingSession");o(this,"_streamPresentationCurrent");o(this,"socket");o(this,"connect",async(e,t)=>(this._cancelRequests(),this._connectWithDuplicatedCalls(e,t)));o(this,"initUa",async e=>this._cancelableInitUa.request(e));o(this,"set",async e=>this._cancelableSet.request(e));o(this,"call",async e=>this._cancelableCall.request(e));o(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));o(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));o(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));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(B,void 0);try{await this.unregister()}catch(e){v("tryRegister",e)}return this.register()});o(this,"declineToIncomingCall",async({statusCode:e=Qn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingSession"));return}const i=this.incomingSession,r=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(X,r),t(i.terminate({status_code:e}))}));o(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Xn}));o(this,"removeIncomingSession",()=>{delete this.incomingSession});o(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=zn}={})=>{const n=async()=>this._cancelableConnect.request(e),i=r=>{var l;const c=!!((l=this.ua)!=null&&l.isConnected())&&this.hasEqualConnectionConfiguration(e),_=!!r&&!Un(r);return c||_};return this._cancelableConnectWithRepeatedCalls=we.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1,onAfterCancel:()=>{this._cancelableConnect.cancelRequest()}}),this._cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r})});o(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===ke){this.incomingSession=t;const n=this.remoteCallerData;t.on(R,i=>{this.removeIncomingSession(),i.originator===Y?this._uaEvents.trigger(z,n):this._uaEvents.trigger(Q,n)}),this._uaEvents.trigger(J,n)}});o(this,"_connect",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:_,connectionRecoveryMaxInterval:l,userAgent:E,displayName:h="",register:d=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(d&&!e)throw new Error("user is required for authorized connection");if(d&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:h,register:d,user:e,password:t};const{configuration:u,helpers:S}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:h,register:d,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:l,userAgent:E});return this.getSipServerUrl=S.getSipServerUrl,this.socket=S.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!d,this.ua=this._createUa({...u,remoteAddress:r,extraHeaders:T}),this._uaEvents.eachTriggers((A,x)=>{const ye=Oe.find(Ot=>Ot===x);ye&&this.ua&&this.ua.on(ye,A)}),this.ua});o(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e?Qt(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=_=>{c(),t(_)},a=()=>{this.isRegisterConfig?(this.on(m,i),this.on(O,r)):this.on(P,i),this.on(N,r)},c=()=>{this.off(m,i),this.off(O,r),this.off(P,i),this.off(N,r)};a(),this.on(y,this.handleNewRTCSession),n.start()}));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",qe(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=r.set("password",t),this._connectionConfiguration.password=t);const _=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(_)}).catch(l=>{i(l)}):_?n(_):i(new Error("nothing changed"))}));o(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());o(this,"_disconnect",async()=>{this.off(y,this.handleNewRTCSession);const e=new Promise(t=>{this.once(N,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(N,void 0)):this._uaEvents.trigger(N,void 0),e});o(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:r,videoMode:a,audioMode:c,contentHint:_,offerToReceiveAudio:l=!0,offerToReceiveVideo:E=!0,sendEncodings:h,onAddedTransceiver:d})=>new Promise((T,u)=>{const{ua:S}=this;if(!S){u(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(T).catch(A=>{u(A)}),this.session=S.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{videoMode:a,audioMode:c,contentHint:_}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:E},sendEncodings:h,onAddedTransceiver:d})}));o(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,videoMode:r,audioMode:a,contentHint:c,sendEncodings:_,onAddedTransceiver:l})=>new Promise((E,h)=>{if(!this.isAvailableIncomingCall){h(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:d}=this;if(!d){h(new Error("No session established"));return}this._sessionEvents.eachTriggers((u,S)=>{const A=De.find(x=>x===S);A&&d.on(A,u)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(E).catch(u=>{h(u)});const T=p(e,{videoMode:r,audioMode:a,contentHint:c});d.answer({extraHeaders:n,videoMode:r,audioMode:a,mediaStream:T,pcConfig:{iceServers:i},sendEncodings:_,onAddedTransceiver:l})}));o(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(H,E),this.onSession(L,h)},r=()=>{this.offSession(H,E),this.offSession(L,h)},a=()=>{this.onSession(R,_),this.onSession(D,_)},c=()=>{this.offSession(R,_),this.offSession(D,_)},_=d=>{r(),c(),n(d)};let l;const E=({peerconnection:d})=>{l=d,l.ontrack=T=>{this._sessionEvents.trigger(oe,l),e&&e(T)}},h=()=>{l&&this._sessionEvents.trigger(ie,l),r(),c(),t(l)};i(),a()}));o(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});o(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{session:i}=this;if(!i){n(new Error("No session established"));return}this.onceSession(fe,({originator:r})=>{r===Y&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));o(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){v("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});o(this,"_handleShareState",e=>{switch(e){case Ct:{this._sessionEvents.trigger(Z,void 0);break}case gt:{this._sessionEvents.trigger(ee,void 0);break}case At:{this._sessionEvents.trigger(te,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(w,i)}});o(this,"_handleNotify",e=>{switch(e.cmd){case Zn:{const t=e;this._triggerChannelsNotify(t);break}case es:{const t=e;this._triggerWebcastStartedNotify(t);break}case ts:{const t=e;this._triggerWebcastStoppedNotify(t);break}case is:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case os:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case rs:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case as:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case cs:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case ns:{this._triggerAccountChangedNotify();break}case ss:{this._triggerAccountDeletedNotify();break}case Es:{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(Te,t)});o(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(he,t)});o(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ce,n)});o(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(ge,n)});o(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ae,void 0)});o(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(Re,void 0)});o(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Ie,i)});o(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this._uaEvents.trigger(re,i)});o(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Se,t)});o(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Ne,t)});o(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});o(this,"_triggerEnterRoom",e=>{const t=e.getHeader(jt),n=e.getHeader(rn);this._sessionEvents.trigger(ne,{room:t,participantName:n})});o(this,"_triggerShareState",e=>{const t=e.getHeader(f);this._sessionEvents.trigger(b,t)});o(this,"_maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(un);t===ht&&this._sessionEvents.trigger(F,void 0),t===Tt&&this._sessionEvents.trigger(V,void 0)});o(this,"_triggerMainCamControl",e=>{const t=e.getHeader(an),n=e.getHeader(We),i=n===k.ADMIN_SYNC_FORCED;if(t===I.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(_e,{isSyncForced:i});return}if(t===I.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(Ee,{isSyncForced:i});return}(t===I.RESUME_MAIN_CAM||t===I.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(U,{isSyncForced:i});const r=e.getHeader(En);this._sessionEvents.trigger(ce,{mainCam:t,resolutionMainCam:r})});o(this,"_triggerMicControl",e=>{const t=e.getHeader(cn),i=e.getHeader(We)===k.ADMIN_SYNC_FORCED;t===q.ADMIN_START_MIC?this._sessionEvents.trigger(de,{isSyncForced:i}):t===q.ADMIN_STOP_MIC&&this._sessionEvents.trigger(le,{isSyncForced:i})});o(this,"_triggerUseLicense",e=>{const t=e.getHeader(on);this._sessionEvents.trigger(se,t)});o(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,i=n.getHeader(zt);if(i)switch(i){case Kt:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case Sn:{this._maybeHandleNotify(n);break}case M:{this._triggerShareState(n);break}case Ue:{this._triggerMainCamControl(n);break}case nn:{this._triggerMicControl(n);break}case sn:{this._triggerUseLicense(n);break}case Tn:{this._maybeTriggerParticipantMoveRequest(n);break}}});o(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});o(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Nn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});o(this,"_handleEnded",e=>{const{originator:t}=e;t===ke&&this._sessionEvents.trigger(ae,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new be(pe),this._uaEvents=new be(Me),this._cancelableConnect=new C.CancelableRequest(this._connect,{moduleName:g,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new C.CancelableRequest(this._initUa,{moduleName:g}),this._cancelableDisconnect=new C.CancelableRequest(this._disconnect,{moduleName:g}),this._cancelableSet=new C.CancelableRequest(this._set,{moduleName:g}),this._cancelableCall=new C.CancelableRequest(this._call,{moduleName:g}),this._cancelableAnswer=new C.CancelableRequest(this._answer,{moduleName:g}),this._cancelableSendDTMF=new C.CancelableRequest(this._sendDTMF,{moduleName:g}),this.onSession(b,this._handleShareState),this.onSession(Pe,this._handleNewInfo),this.on(K,this._handleSipEvent),this.onSession(R,this._handleEnded),this.onSession(D,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(m,e),this.ua.on(O,t),this.ua.register()):t(new Error("Config is not registered"))})}async unregister(){return new Promise((e,t)=>{this.isRegistered&&this.ua?(this.ua.on(j,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,n){if(!this.ua)throw new Error("is not connected");return new Promise((i,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,_)=>{const{configuration:l}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),E=this._createUa({...l,remoteAddress:r,extraHeaders:a}),h=()=>{const T=new Error("Telephony is not available");_(T)};E.once(N,h);const d=()=>{E.removeAllListeners(),E.once(N,c),E.stop()};E.once(P,d),E.start()})}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");const{contentHint:n}=t||{},i=p(e,{contentHint:n});return this.session.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[Pn];return this.session.sendInfo(Ue,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(Ln(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({session:e,stream:t,presentationOptions:n,options:i={callLimit:jn}}){const r=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=we.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==null?void 0:n.uri.toString())===t.uri&&(n==null?void 0:n.display_name)===t.display_name&&(n==null?void 0:n.user_agent)===t.user_agent&&(n==null?void 0:n.sockets)===t.sockets&&(n==null?void 0:n.session_timers)===t.session_timers&&(n==null?void 0:n.register_expires)===t.register_expires&&(n==null?void 0:n.connection_recovery_min_interval)===t.connection_recovery_min_interval&&(n==null?void 0:n.connection_recovery_max_interval)===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:c=!1,registerExpires:_=60*5,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:E=6,userAgent:h}){if(a&&!t)throw new Error("password is required for authorized connection");const d=a&&e?e.trim():`${vn()}`,T=Mn(r),u=T(d),S=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:u,display_name:qe(i),user_agent:h,sdp_semantics:"unified-plan",sockets:[S],session_timers:c,register_expires:_,connection_recovery_min_interval:l,connection_recovery_max_interval:E},helpers:{socket:S,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=ut,isNeedReinvite:i=!0,isP2P:r=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:_}){const l=p(t,{contentHint:a});this._streamPresentationCurrent=l;const E=r?[Rn]:[Cn],h=e.sendInfo(M,void 0,{extraHeaders:E}).then(async()=>e.startPresentation(l,i,{sendEncodings:c,onAddedTransceiver:_})).then(async()=>{const{connection:d}=this;if(!d||n===void 0)return;const T=d.getSenders();await Jn(T,t,n)}).then(()=>t).catch(d=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(W,d),d});return this.promisePendingStartPresentation=h,h.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:c}={},_){const l=this.establishedSession;if(!l)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(l),this._sendPresentationWithDuplicatedCalls({session:l,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:c},options:_})}async sendMustStopPresentation(e){await e.sendInfo(M,void 0,{extraHeaders:[An]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const i=e?[In]:[gn],r=this.establishedSession;return r&&t&&(n=n.then(async()=>r.sendInfo(M,void 0,{extraHeaders:i})).then(async()=>r.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(W,a),a})),!r&&t&&this._sessionEvents.trigger(me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={}){const c=this.establishedSession;if(!c)throw new Error("No session established");if(!this._streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this._sendPresentation(c,e,{isP2P:t,maxBitrate:n,contentHint:i,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:a})}_removeStreamPresentationCurrent(){delete this._streamPresentationCurrent}_resetPresentation(){this._removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}_cancelRequestsAndResetPresentation(){this._cancelSendPresentationWithRepeatedCalls(),this._resetPresentation()}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}async wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}async waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return{...this._connectionConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:n})=>n);return yn(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,i,r,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(i=(n=this.incomingSession)==null?void 0:n.remote_identity)==null?void 0:i.uri.host,incomingNumber:(a=(r=this.incomingSession)==null?void 0:r.remote_identity)==null?void 0:a.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){var e;return(e=this.session)!=null&&e.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_generateStream(e,t){const{id:n}=e,i=this._remoteStreams[n]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[n]=i,i}_generateAudioStream(e){const{id:t}=e,n=this._remoteStreams[t]||new MediaStream;return n.addTrack(e),this._remoteStreams[t]=n,n}_generateStreams(e){const t=[];return e.forEach((n,i)=>{if(n.kind==="audio")return;const r=n,a=e[i-1];let c;a&&a.kind==="audio"&&(c=a);const _=this._generateStream(r,c);t.push(_)}),t}_generateAudioStreams(e){return e.map(n=>this._generateAudioStream(n))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectWithRepeatedCalls()}_cancelConnectWithRepeatedCalls(){var e;(e=this._cancelableConnectWithRepeatedCalls)==null||e.cancel()}_cancelSendPresentationWithRepeatedCalls(){var e;(e=this._cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(w)}async waitSyncMediaState(){return this.waitSession(U)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=`${Le}: ${e}`,i=`${He}: ${t}`,r=[n,i];return this.session.sendInfo(Zt,void 0,{extraHeaders:r})}async sendMediaState({cam:e,mic:t},n={}){if(!this.session)throw new Error("No session established");const i=`${_n}: currentstate`,r=`${dn}: ${Number(e)}`,a=`${hn}: ${Number(t)}`,c=[i,r,a];return this.session.sendInfo(en,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${ln}: ${e==="mic"?0:1}`];return this.session.sendInfo(tn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}exports.BAD_MEDIA_DESCRIPTION=Ye;exports.EEventsMainCAM=I;exports.EEventsMic=q;exports.EEventsSyncMediaState=k;exports.EUseLicense=Rt;exports.NOT_FOUND=Fe;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=F;exports.REJECTED=$;exports.SESSION_EVENT_NAMES=pe;exports.SipConnector=_s;exports.UA_EVENT_NAMES=Me;exports.causes=$t;exports.constants=Jt;exports.disableDebug=On;exports.enableDebug=mn;exports.eventNames=Xt;exports.hasCanceledCallError=Kn;exports.logger=v;exports.setEncodingsToSender=mt;exports.setParametersToSender=Pt;
1
+ "use strict";var Dt=Object.defineProperty;var Mt=(s,e,t)=>e in s?Dt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var o=(s,e,t)=>Mt(s,typeof e!="symbol"?e+"":e,t);const C=require("@krivega/cancelable-promise"),be=require("events-constructor"),we=require("repeated-calls"),G=require("debug"),pt="Connection Error",Be="Request Timeout",vt="SIP Failure Code",yt="Internal Error",bt="Busy",$="Rejected",wt="Redirected",Ut="Unavailable",Fe="Not Found",Lt="Address Incomplete",Ht="Incompatible SDP",Wt="Missing SDP",qt="Authentication Error",Ve="Terminated",kt="WebRTC Error",xe="Canceled",Bt="No Answer",Ft="Expires",Vt="No ACK",xt="Dialog Error",Yt="User Denied Media Access",Ye="Bad Media Description",Gt="RTP Timeout",$t=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Lt,AUTHENTICATION_ERROR:qt,BAD_MEDIA_DESCRIPTION:Ye,BUSY:bt,BYE:Ve,CANCELED:xe,CONNECTION_ERROR:pt,DIALOG_ERROR:xt,EXPIRES:Ft,INCOMPATIBLE_SDP:Ht,INTERNAL_ERROR:yt,MISSING_SDP:Wt,NOT_FOUND:Fe,NO_ACK:Vt,NO_ANSWER:Bt,REDIRECTED:wt,REJECTED:$,REQUEST_TIMEOUT:Be,RTP_TIMEOUT:Gt,SIP_FAILURE_CODE:vt,UNAVAILABLE:Ut,USER_DENIED_MEDIA_ACCESS:Yt,WEBRTC_ERROR:kt},Symbol.toStringTag,{value:"Module"})),J="incomingCall",X="declinedIncomingCall",Q="failedIncomingCall",z="terminatedIncomingCall",B="connecting",P="connected",N="disconnected",y="newRTCSession",m="registered",j="unregistered",O="registrationFailed",Ge="newMessage",K="sipEvent",Z="availableSecondRemoteStream",ee="notAvailableSecondRemoteStream",te="mustStopPresentation",b="shareState",ne="enterRoom",se="useLicense",ie="peerconnection:confirmed",oe="peerconnection:ontrack",w="channels",re="channels:notify",ae="ended:fromserver",ce="main-cam-control",Ee="admin-stop-main-cam",_e="admin-start-main-cam",le="admin-stop-mic",de="admin-start-mic",U="admin-force-sync-media-state",he="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",ue="participant:move-request-to-stream",F="participant:move-request-to-spectators",V="participant:move-request-to-participants",Se="participation:accepting-word-request",Ne="participation:cancelling-word-request",Ce="webcast:started",ge="webcast:stopped",Ae="account:changed",Re="account:deleted",Ie="conference:participant-token-issued",D="ended",$e="sending",Je="reinvite",Xe="replaces",Qe="refer",ze="progress",je="accepted",L="confirmed",H="peerconnection",R="failed",Ke="muted",Ze="unmuted",fe="newDTMF",Pe="newInfo",et="hold",tt="unhold",nt="update",st="sdp",it="icecandidate",ot="getusermediafailed",rt="peerconnection:createofferfailed",at="peerconnection:createanswerfailed",ct="peerconnection:setlocaldescriptionfailed",Et="peerconnection:setremotedescriptionfailed",_t="presentation:start",lt="presentation:started",dt="presentation:end",me="presentation:ended",W="presentation:failed",ht="SPECTATOR",Tt="PARTICIPANT",ut=1e6,Jt=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:je,ACCOUNT_CHANGED:Ae,ACCOUNT_DELETED:Re,ADMIN_FORCE_SYNC_MEDIA_STATE:U,ADMIN_START_MAIN_CAM:_e,ADMIN_START_MIC:de,ADMIN_STOP_MAIN_CAM:Ee,ADMIN_STOP_MIC:le,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:Z,CHANNELS:w,CHANNELS_NOTIFY:re,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ie,CONFIRMED:L,CONNECTED:P,CONNECTING:B,DECLINED_INCOMING_CALL:X,DISCONNECTED:N,ENDED:D,ENDED_FROM_SERVER:ae,ENTER_ROOM:ne,FAILED:R,FAILED_INCOMING_CALL:Q,GET_USER_MEDIA_FAILED:ot,HOLD:et,ICE_CANDIDATE:it,INCOMING_CALL:J,MAIN_CAM_CONTROL:ce,MUST_STOP_PRESENTATION_EVENT:te,MUTED:Ke,NEW_DTMF:fe,NEW_INFO:Pe,NEW_MESSAGE:Ge,NEW_RTC_SESSION:y,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:ee,ONE_MEGABIT_IN_BITS:ut,PARTICIPANT:Tt,PARTICIPANT_ADDED_TO_LIST_MODERATORS:he,PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS:V,PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS:F,PARTICIPANT_MOVE_REQUEST_TO_STREAM:ue,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Te,PARTICIPATION_ACCEPTING_WORD_REQUEST:Se,PARTICIPATION_CANCELLING_WORD_REQUEST:Ne,PEER_CONNECTION:H,PEER_CONNECTION_CONFIRMED:ie,PEER_CONNECTION_CREATE_ANSWER_FAILED:at,PEER_CONNECTION_CREATE_OFFER_FAILED:rt,PEER_CONNECTION_ONTRACK:oe,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:ct,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:Et,PRESENTATION_END:dt,PRESENTATION_ENDED:me,PRESENTATION_FAILED:W,PRESENTATION_START:_t,PRESENTATION_STARTED:lt,PROGRESS:ze,REFER:Qe,REGISTERED:m,REGISTRATION_FAILED:O,REINVITE:Je,REPLACES:Xe,SDP:st,SENDING:$e,SHARE_STATE:b,SIP_EVENT:K,SPECTATOR:ht,TERMINATED_INCOMING_CALL:z,UNHOLD:tt,UNMUTED:Ze,UNREGISTERED:j,UPDATE:nt,USE_LICENSE:se,WEBCAST_STARTED:Ce,WEBCAST_STOPPED:ge},Symbol.toStringTag,{value:"Module"})),St=[J,X,z,Q,Se,Ne,ue,re,Ie,Ae,Re,Ce,ge,he,Te],Oe=[B,P,N,y,m,j,O,Ge,K],Nt=[Z,ee,te,b,ne,se,ie,oe,w,ae,ce,_e,Ee,le,de,U,F,V],De=[D,B,$e,Je,Xe,Qe,ze,je,L,H,R,Ke,Ze,fe,Pe,et,tt,nt,st,it,ot,rt,at,ct,Et,_t,lt,dt,me,W],Me=[...Oe,...St],pe=[...De,...Nt],Xt=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:pe,SESSION_JSSIP_EVENT_NAMES:De,SESSION_SYNTHETICS_EVENT_NAMES:Nt,UA_EVENT_NAMES:Me,UA_JSSIP_EVENT_NAMES:Oe,UA_SYNTHETICS_EVENT_NAMES:St},Symbol.toStringTag,{value:"Module"})),Qt=s=>{const e=[];return s&&e.push(`X-Vinteo-Remote: ${s}`),e},zt="content-type",jt="x-webrtc-enter-room",M="application/vinteo.webrtc.sharedesktop",Kt="application/vinteo.webrtc.roomname",Zt="application/vinteo.webrtc.channels",en="application/vinteo.webrtc.mediastate",tn="application/vinteo.webrtc.refusal",Ue="application/vinteo.webrtc.maincam",nn="application/vinteo.webrtc.mic",sn="application/vinteo.webrtc.uselic",on="X-WEBRTC-USE-LICENSE",rn="X-WEBRTC-PARTICIPANT-NAME",Le="X-WEBRTC-INPUT-CHANNELS",He="X-WEBRTC-OUTPUT-CHANNELS",an="X-WEBRTC-MAINCAM",cn="X-WEBRTC-MIC",We="X-WEBRTC-SYNC",En="X-WEBRTC-MAINCAM-RESOLUTION",_n="X-WEBRTC-MEDIA-STATE",ln="X-Vinteo-Media-Type",dn="X-Vinteo-MainCam-State",hn="X-Vinteo-Mic-State",Tn="application/vinteo.webrtc.partstate",un="X-WEBRTC-PARTSTATE",Sn="application/vinteo.webrtc.notify",Nn="X-VINTEO-NOTIFY",f="x-webrtc-share-state",Cn=`${f}: LETMESTARTPRESENTATION`,gn=`${f}: STOPPRESENTATION`,Ct="YOUCANRECEIVECONTENT",gt="CONTENTEND",At="YOUMUSTSTOPSENDCONTENT",An=`${f}: ${At}`,Rn=`${f}: ${Ct}`,In=`${f}: ${gt}`,fn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Pn=`${fn}: LETMESTARTMAINCAM`,ve="sip-connector",v=G(ve),mn=()=>{G.enable(ve)},On=()=>{G.enable(`-${ve}`)},Dn=(s,e)=>{s.getVideoTracks().forEach(n=>{"contentHint"in n&&n.contentHint!==e&&(n.contentHint=e)})},p=(s,{videoMode:e,audioMode:t,contentHint:n}={})=>{if(!s||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:s.getAudioTracks(),r=e==="recvonly"?[]:s.getVideoTracks(),a=[...i,...r],c=new MediaStream(a);return c.getTracks=()=>[...c.getAudioTracks(),...c.getVideoTracks()],n&&n!=="none"&&Dn(c,n),c};var I=(s=>(s.PAUSE_MAIN_CAM="PAUSEMAINCAM",s.RESUME_MAIN_CAM="RESUMEMAINCAM",s.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",s.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",s.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",s))(I||{}),q=(s=>(s.ADMIN_STOP_MIC="ADMINSTOPMIC",s.ADMIN_START_MIC="ADMINSTARTMIC",s))(q||{}),k=(s=>(s.ADMIN_SYNC_FORCED="1",s.ADMIN_SYNC_NOT_FORCED="0",s))(k||{}),Rt=(s=>(s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",s))(Rt||{});function Mn(s){return e=>`sip:${e}@${s}`}const pn=(s,e)=>()=>Math.floor(Math.random()*(e-s))+s,qe=s=>s.trim().replaceAll(" ","_"),vn=pn(1e5,99999999),yn=s=>s.some(t=>{const{kind:n}=t;return n==="video"}),bn="Error decline with 603",wn=1006,Un=s=>typeof s=="object"&&s!==null&&"code"in s&&s.code===wn,Ln=s=>s.message===bn,Hn=(s,e)=>s.find(t=>t.track&&e.getTracks().includes(t.track)),Wn=(s,e)=>(s.degradationPreference=e.degradationPreference,s),qn=(s,e)=>{s.encodings===void 0&&(s.encodings=[]);for(let t=s.encodings.length;t<e;t+=1)s.encodings.push({});return s},It=s=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==s,kn=It(),Bn=(s,e)=>{if(kn(s,e))return s},Fn=(s,e)=>{const t=s.maxBitrate,n=Bn(e,t);return n!==void 0&&(s.maxBitrate=n),s},ft=1,Vn=It(ft),xn=(s,e)=>{const t=s===void 0?void 0:Math.max(s,ft);if(t!==void 0&&Vn(t,e))return t},Yn=(s,e)=>{const t=s.scaleResolutionDownBy,n=xn(e,t);return n!==void 0&&(s.scaleResolutionDownBy=n),s},Gn=(s,e)=>{var n;const t=((n=e.encodings)==null?void 0:n.length)??0;return qn(s,t),s.encodings.forEach((i,r)=>{const a=((e==null?void 0:e.encodings)??[])[r],c=a==null?void 0:a.maxBitrate,_=a==null?void 0:a.scaleResolutionDownBy;Fn(i,c),Yn(i,_)}),s},$n=(s,e)=>{var t,n,i,r,a,c,_,l;if(((t=s.codecs)==null?void 0:t.length)!==((n=e.codecs)==null?void 0:n.length))return!0;for(let E=0;E<(((i=s.codecs)==null?void 0:i.length)??0);E++)if(JSON.stringify(s.codecs[E])!==JSON.stringify(e.codecs[E]))return!0;if(((r=s.headerExtensions)==null?void 0:r.length)!==((a=e.headerExtensions)==null?void 0:a.length))return!0;for(let E=0;E<(((c=s.headerExtensions)==null?void 0:c.length)??0);E++)if(JSON.stringify(s.headerExtensions[E])!==JSON.stringify(e.headerExtensions[E]))return!0;if(((_=s.encodings)==null?void 0:_.length)!==((l=e.encodings)==null?void 0:l.length))return!0;for(let E=0;E<(s.encodings.length??0);E++)if(JSON.stringify(s.encodings[E])!==JSON.stringify(e.encodings[E]))return!0;return s.rtcp.cname!==e.rtcp.cname||s.rtcp.reducedSize!==e.rtcp.reducedSize||s.degradationPreference!==e.degradationPreference},Pt=async(s,e)=>{const t=s.getParameters(),n=JSON.parse(JSON.stringify(t));Gn(t,e),Wn(t,e);const i=$n(n,t);return i&&await s.setParameters(t),{parameters:t,isChanged:i}},mt=async(s,e,t)=>{const{isChanged:n,parameters:i}=await Pt(s,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return n&&t&&t(i),{isChanged:n,parameters:i}},Jn=async(s,e,t)=>{const n=Hn(s,e);if(n)return mt(n,{maxBitrate:t})},Xn=486,Qn=487,Y="local",ke="remote",zn=3,jn=1,Kn=(s=new Error)=>{const{originator:e,cause:t}=s;return C.isCanceledError(s)?!0:typeof t=="string"?t===Be||t===$||e===Y&&(t===xe||t===Ve):!1},g="SipConnector",Zn="channels",es="WebcastStarted",ts="WebcastStopped",ns="accountChanged",ss="accountDeleted",is="addedToListModerators",os="removedFromListModerators",rs="ParticipationRequestAccepted",as="ParticipationRequestRejected",cs="ParticipantMovedToWebcast",Es="ConferenceParticipantTokenIssued";class _s{constructor({JsSIP:e}){o(this,"_isRegisterConfig",!1);o(this,"_connectionConfiguration",{});o(this,"_remoteStreams",{});o(this,"JsSIP");o(this,"_sessionEvents");o(this,"_uaEvents");o(this,"_cancelableConnect");o(this,"_cancelableConnectWithRepeatedCalls");o(this,"_cancelableSendPresentationWithRepeatedCalls");o(this,"_cancelableInitUa");o(this,"_cancelableDisconnect");o(this,"_cancelableSet");o(this,"_cancelableCall");o(this,"_cancelableAnswer");o(this,"_cancelableSendDTMF");o(this,"getSipServerUrl",e=>e);o(this,"promisePendingStartPresentation");o(this,"promisePendingStopPresentation");o(this,"ua");o(this,"session");o(this,"incomingSession");o(this,"_streamPresentationCurrent");o(this,"socket");o(this,"connect",async(e,t)=>(this._cancelRequests(),this._connectWithDuplicatedCalls(e,t)));o(this,"initUa",async e=>this._cancelableInitUa.request(e));o(this,"set",async e=>this._cancelableSet.request(e));o(this,"call",async e=>this._cancelableCall.request(e));o(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));o(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));o(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));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(B,void 0);try{await this.unregister()}catch(e){v("tryRegister",e)}return this.register()});o(this,"declineToIncomingCall",async({statusCode:e=Qn}={})=>new Promise((t,n)=>{if(!this.isAvailableIncomingCall){n(new Error("no incomingSession"));return}const i=this.incomingSession,r=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(X,r),t(i.terminate({status_code:e}))}));o(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:Xn}));o(this,"removeIncomingSession",()=>{delete this.incomingSession});o(this,"_connectWithDuplicatedCalls",async(e,{callLimit:t=zn}={})=>{const n=async()=>this._cancelableConnect.request(e),i=r=>{var l;const c=!!((l=this.ua)!=null&&l.isConnected())&&this.hasEqualConnectionConfiguration(e),_=!!r&&!Un(r);return c||_};return this._cancelableConnectWithRepeatedCalls=we.repeatedCallsAsync({targetFunction:n,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1,onAfterCancel:()=>{this._cancelableConnect.cancelRequest()}}),this._cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r})});o(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===ke){this.incomingSession=t;const n=this.remoteCallerData;t.on(R,i=>{this.removeIncomingSession(),i.originator===Y?this._uaEvents.trigger(z,n):this._uaEvents.trigger(Q,n)}),this._uaEvents.trigger(J,n)}});o(this,"_connect",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:_,connectionRecoveryMaxInterval:l,userAgent:E,displayName:h="",register:d=!1,extraHeaders:T=[]})=>{if(!n)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(d&&!e)throw new Error("user is required for authorized connection");if(d&&!t)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:n,displayName:h,register:d,user:e,password:t};const{configuration:u,helpers:S}=this.createUaConfiguration({user:e,sipServerUrl:n,sipWebSocketServerURL:i,password:t,displayName:h,register:d,sessionTimers:a,registerExpires:c,connectionRecoveryMinInterval:_,connectionRecoveryMaxInterval:l,userAgent:E});return this.getSipServerUrl=S.getSipServerUrl,this.socket=S.socket,this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!d,this.ua=this._createUa({...u,remoteAddress:r,extraHeaders:T}),this._uaEvents.eachTriggers((A,x)=>{const ye=Oe.find(Ot=>Ot===x);ye&&this.ua&&this.ua.on(ye,A)}),this.ua});o(this,"_createUa",({remoteAddress:e,extraHeaders:t=[],...n})=>{const i=new this.JsSIP.UA(n),a=[...e?Qt(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=_=>{c(),t(_)},a=()=>{this.isRegisterConfig?(this.on(m,i),this.on(O,r)):this.on(P,i),this.on(N,r)},c=()=>{this.off(m,i),this.off(O,r),this.off(P,i),this.off(N,r)};a(),this.on(y,this.handleNewRTCSession),n.start()}));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",qe(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=r.set("password",t),this._connectionConfiguration.password=t);const _=a||c;c&&this.isRegisterConfig?this.register().then(()=>{n(_)}).catch(l=>{i(l)}):_?n(_):i(new Error("nothing changed"))}));o(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());o(this,"_disconnect",async()=>{this.off(y,this.handleNewRTCSession);const e=new Promise(t=>{this.once(N,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(N,void 0)):this._uaEvents.trigger(N,void 0),e});o(this,"_call",async({number:e,mediaStream:t,extraHeaders:n=[],ontrack:i,iceServers:r,videoMode:a,audioMode:c,contentHint:_,offerToReceiveAudio:l=!0,offerToReceiveVideo:E=!0,sendEncodings:h,onAddedTransceiver:d})=>new Promise((T,u)=>{const{ua:S}=this;if(!S){u(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(T).catch(A=>{u(A)}),this.session=S.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:p(t,{videoMode:a,audioMode:c,contentHint:_}),eventHandlers:this._sessionEvents.triggers,videoMode:a,audioMode:c,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:E},sendEncodings:h,onAddedTransceiver:d})}));o(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,videoMode:r,audioMode:a,contentHint:c,sendEncodings:_,onAddedTransceiver:l})=>new Promise((E,h)=>{if(!this.isAvailableIncomingCall){h(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:d}=this;if(!d){h(new Error("No session established"));return}this._sessionEvents.eachTriggers((u,S)=>{const A=De.find(x=>x===S);A&&d.on(A,u)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(E).catch(u=>{h(u)});const T=p(e,{videoMode:r,audioMode:a,contentHint:c});d.answer({extraHeaders:n,videoMode:r,audioMode:a,mediaStream:T,pcConfig:{iceServers:i},sendEncodings:_,onAddedTransceiver:l})}));o(this,"_handleCall",async({ontrack:e})=>new Promise((t,n)=>{const i=()=>{this.onSession(H,E),this.onSession(L,h)},r=()=>{this.offSession(H,E),this.offSession(L,h)},a=()=>{this.onSession(R,_),this.onSession(D,_)},c=()=>{this.offSession(R,_),this.offSession(D,_)},_=d=>{r(),c(),n(d)};let l;const E=({peerconnection:d})=>{l=d,l.ontrack=T=>{this._sessionEvents.trigger(oe,l),e&&e(T)}},h=()=>{l&&this._sessionEvents.trigger(ie,l),r(),c(),t(l)};i(),a()}));o(this,"_restoreSession",()=>{this._cancelRequestsAndResetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});o(this,"_sendDTMF",async e=>new Promise((t,n)=>{const{session:i}=this;if(!i){n(new Error("No session established"));return}this.onceSession(fe,({originator:r})=>{r===Y&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})}));o(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;if(this._streamPresentationCurrent)try{await this.stopPresentation()}catch(t){v("error stop presentation: ",t)}if(this._restoreSession(),!e.isEnded())return e.terminateAsync()}});o(this,"_handleShareState",e=>{switch(e){case Ct:{this._sessionEvents.trigger(Z,void 0);break}case gt:{this._sessionEvents.trigger(ee,void 0);break}case At:{this._sessionEvents.trigger(te,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(w,i)}});o(this,"_handleNotify",e=>{switch(e.cmd){case Zn:{const t=e;this._triggerChannelsNotify(t);break}case es:{const t=e;this._triggerWebcastStartedNotify(t);break}case ts:{const t=e;this._triggerWebcastStoppedNotify(t);break}case is:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case os:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case rs:{const t=e;this._triggerParticipationAcceptingWordRequest(t);break}case as:{const t=e;this._triggerParticipationCancellingWordRequest(t);break}case cs:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case ns:{this._triggerAccountChangedNotify();break}case ss:{this._triggerAccountDeletedNotify();break}case Es:{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(Te,t)});o(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(he,t)});o(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(Ce,n)});o(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger(ge,n)});o(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(Ae,void 0)});o(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(Re,void 0)});o(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this._uaEvents.trigger(Ie,i)});o(this,"_triggerChannelsNotify",e=>{const t=e.input,n=e.output,i={inputChannels:t,outputChannels:n};this._uaEvents.trigger(re,i)});o(this,"_triggerParticipationAcceptingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Se,t)});o(this,"_triggerParticipationCancellingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Ne,t)});o(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ue,t)});o(this,"_triggerEnterRoom",e=>{const t=e.getHeader(jt),n=e.getHeader(rn);this._sessionEvents.trigger(ne,{room:t,participantName:n})});o(this,"_triggerShareState",e=>{const t=e.getHeader(f);this._sessionEvents.trigger(b,t)});o(this,"_maybeTriggerParticipantMoveRequest",e=>{const t=e.getHeader(un);t===ht&&this._sessionEvents.trigger(F,void 0),t===Tt&&this._sessionEvents.trigger(V,void 0)});o(this,"_triggerMainCamControl",e=>{const t=e.getHeader(an),n=e.getHeader(We),i=n===k.ADMIN_SYNC_FORCED;if(t===I.ADMIN_START_MAIN_CAM){this._sessionEvents.trigger(_e,{isSyncForced:i});return}if(t===I.ADMIN_STOP_MAIN_CAM){this._sessionEvents.trigger(Ee,{isSyncForced:i});return}(t===I.RESUME_MAIN_CAM||t===I.PAUSE_MAIN_CAM)&&n&&this._sessionEvents.trigger(U,{isSyncForced:i});const r=e.getHeader(En);this._sessionEvents.trigger(ce,{mainCam:t,resolutionMainCam:r})});o(this,"_triggerMicControl",e=>{const t=e.getHeader(cn),i=e.getHeader(We)===k.ADMIN_SYNC_FORCED;t===q.ADMIN_START_MIC?this._sessionEvents.trigger(de,{isSyncForced:i}):t===q.ADMIN_STOP_MIC&&this._sessionEvents.trigger(le,{isSyncForced:i})});o(this,"_triggerUseLicense",e=>{const t=e.getHeader(on);this._sessionEvents.trigger(se,t)});o(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:n}=e,i=n.getHeader(zt);if(i)switch(i){case Kt:{this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break}case Sn:{this._maybeHandleNotify(n);break}case M:{this._triggerShareState(n);break}case Ue:{this._triggerMainCamControl(n);break}case nn:{this._triggerMicControl(n);break}case sn:{this._triggerUseLicense(n);break}case Tn:{this._maybeTriggerParticipantMoveRequest(n);break}}});o(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});o(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Nn);if(t){const n=JSON.parse(t);this._handleNotify(n)}});o(this,"_handleEnded",e=>{const{originator:t}=e;t===ke&&this._sessionEvents.trigger(ae,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new be(pe),this._uaEvents=new be(Me),this._cancelableConnect=new C.CancelableRequest(this._connect,{moduleName:g,afterCancelRequest:()=>{this._cancelableInitUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableInitUa=new C.CancelableRequest(this._initUa,{moduleName:g}),this._cancelableDisconnect=new C.CancelableRequest(this._disconnect,{moduleName:g}),this._cancelableSet=new C.CancelableRequest(this._set,{moduleName:g}),this._cancelableCall=new C.CancelableRequest(this._call,{moduleName:g}),this._cancelableAnswer=new C.CancelableRequest(this._answer,{moduleName:g}),this._cancelableSendDTMF=new C.CancelableRequest(this._sendDTMF,{moduleName:g}),this.onSession(b,this._handleShareState),this.onSession(Pe,this._handleNewInfo),this.on(K,this._handleSipEvent),this.onSession(R,this._handleEnded),this.onSession(D,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(m,e),this.ua.on(O,t),this.ua.register()):t(new Error("Config is not registered"))})}async unregister(){return new Promise((e,t)=>{this.isRegistered&&this.ua?(this.ua.on(j,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,n){if(!this.ua)throw new Error("is not connected");return new Promise((i,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,_)=>{const{configuration:l}=this.createUaConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:n}),E=this._createUa({...l,remoteAddress:r,extraHeaders:a}),h=()=>{const T=new Error("Telephony is not available");_(T)};E.once(N,h);const d=()=>{E.removeAllListeners(),E.once(N,c),E.stop()};E.once(P,d),E.start()})}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");const{contentHint:n}=t??{},i=p(e,{contentHint:n});return this.session.replaceMediaStream(i,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[Pn];return this.session.sendInfo(Ue,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(n=>{if(Ln(n))throw n})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentationWithDuplicatedCalls({session:e,stream:t,presentationOptions:n,options:i={callLimit:jn}}){const r=async()=>this._sendPresentation(e,t,n),a=()=>!!this._streamPresentationCurrent;return this._cancelableSendPresentationWithRepeatedCalls=we.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==null?void 0:n.uri.toString())===t.uri&&(n==null?void 0:n.display_name)===t.display_name&&(n==null?void 0:n.user_agent)===t.user_agent&&(n==null?void 0:n.sockets)===t.sockets&&(n==null?void 0:n.session_timers)===t.session_timers&&(n==null?void 0:n.register_expires)===t.register_expires&&(n==null?void 0:n.connection_recovery_min_interval)===t.connection_recovery_min_interval&&(n==null?void 0:n.connection_recovery_max_interval)===t.connection_recovery_max_interval}createUaConfiguration({user:e,password:t,sipWebSocketServerURL:n,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:c=!1,registerExpires:_=60*5,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:E=6,userAgent:h}){if(a&&!t)throw new Error("password is required for authorized connection");const d=a&&e?e.trim():`${vn()}`,T=Mn(r),u=T(d),S=new this.JsSIP.WebSocketInterface(n);return{configuration:{password:t,register:a,uri:u,display_name:qe(i),user_agent:h,sdp_semantics:"unified-plan",sockets:[S],session_timers:c,register_expires:_,connection_recovery_min_interval:l,connection_recovery_max_interval:E},helpers:{socket:S,getSipServerUrl:T}}}async _sendPresentation(e,t,{maxBitrate:n=ut,isNeedReinvite:i=!0,isP2P:r=!1,contentHint:a="detail",sendEncodings:c,onAddedTransceiver:_}){const l=p(t,{contentHint:a});this._streamPresentationCurrent=l;const E=r?[Rn]:[Cn],h=e.sendInfo(M,void 0,{extraHeaders:E}).then(async()=>e.startPresentation(l,i,{sendEncodings:c,onAddedTransceiver:_})).then(async()=>{const{connection:d}=this;if(!d||n===void 0)return;const T=d.getSenders();await Jn(T,t,n)}).then(()=>t).catch(d=>{throw this._removeStreamPresentationCurrent(),this._sessionEvents.trigger(W,d),d});return this.promisePendingStartPresentation=h,h.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:c}={},_){const l=this.establishedSession;if(!l)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return n&&await this.sendMustStopPresentation(l),this._sendPresentationWithDuplicatedCalls({session:l,stream:e,presentationOptions:{isNeedReinvite:t,isP2P:n,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:c},options:_})}async sendMustStopPresentation(e){await e.sendInfo(M,void 0,{extraHeaders:[An]})}async stopPresentation({isP2P:e=!1}={}){this._cancelSendPresentationWithRepeatedCalls();const t=this._streamPresentationCurrent;let n=this.promisePendingStartPresentation??Promise.resolve();const i=e?[In]:[gn],r=this.establishedSession;return r&&t&&(n=n.then(async()=>r.sendInfo(M,void 0,{extraHeaders:i})).then(async()=>r.stopPresentation(t)).catch(a=>{throw this._sessionEvents.trigger(W,a),a})),!r&&t&&this._sessionEvents.trigger(me,t),this.promisePendingStopPresentation=n,n.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t,maxBitrate:n,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={}){const c=this.establishedSession;if(!c)throw new Error("No session established");if(!this._streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this._sendPresentation(c,e,{isP2P:t,maxBitrate:n,contentHint:i,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:a})}_removeStreamPresentationCurrent(){delete this._streamPresentationCurrent}_resetPresentation(){this._removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}_cancelRequestsAndResetPresentation(){this._cancelSendPresentationWithRepeatedCalls(),this._resetPresentation()}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}async wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}async waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return{...this._connectionConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:n})=>n);return yn(t)?this._generateStreams(t):this._generateAudioStreams(t)}get connection(){var t;return(t=this.session)==null?void 0:t.connection}get remoteCallerData(){var e,t,n,i,r,a;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(i=(n=this.incomingSession)==null?void 0:n.remote_identity)==null?void 0:i.uri.host,incomingNumber:(a=(r=this.incomingSession)==null?void 0:r.remote_identity)==null?void 0:a.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableInitUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){var e;return(e=this.session)!=null&&e.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_generateStream(e,t){const{id:n}=e,i=this._remoteStreams[n]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[n]=i,i}_generateAudioStream(e){const{id:t}=e,n=this._remoteStreams[t]||new MediaStream;return n.addTrack(e),this._remoteStreams[t]=n,n}_generateStreams(e){const t=[];return e.forEach((n,i)=>{if(n.kind==="audio")return;const r=n,a=e[i-1];let c;a&&a.kind==="audio"&&(c=a);const _=this._generateStream(r,c);t.push(_)}),t}_generateAudioStreams(e){return e.map(n=>this._generateAudioStream(n))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectWithRepeatedCalls()}_cancelConnectWithRepeatedCalls(){var e;(e=this._cancelableConnectWithRepeatedCalls)==null||e.cancel()}_cancelSendPresentationWithRepeatedCalls(){var e;(e=this._cancelableSendPresentationWithRepeatedCalls)==null||e.cancel()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(w)}async waitSyncMediaState(){return this.waitSession(U)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=`${Le}: ${e}`,i=`${He}: ${t}`,r=[n,i];return this.session.sendInfo(Zt,void 0,{extraHeaders:r})}async sendMediaState({cam:e,mic:t},n={}){if(!this.session)throw new Error("No session established");const i=`${_n}: currentstate`,r=`${dn}: ${Number(e)}`,a=`${hn}: ${Number(t)}`,c=[i,r,a];return this.session.sendInfo(en,void 0,{noTerminateWhenError:!0,...n,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${ln}: ${e==="mic"?0:1}`];return this.session.sendInfo(tn,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}}exports.BAD_MEDIA_DESCRIPTION=Ye;exports.EEventsMainCAM=I;exports.EEventsMic=q;exports.EEventsSyncMediaState=k;exports.EUseLicense=Rt;exports.NOT_FOUND=Fe;exports.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=V;exports.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=F;exports.REJECTED=$;exports.SESSION_EVENT_NAMES=pe;exports.SipConnector=_s;exports.UA_EVENT_NAMES=Me;exports.causes=$t;exports.constants=Jt;exports.disableDebug=On;exports.enableDebug=mn;exports.eventNames=Xt;exports.hasCanceledCallError=Kn;exports.logger=v;exports.setEncodingsToSender=mt;exports.setParametersToSender=Pt;
@@ -956,7 +956,7 @@ class Ss {
956
956
  async replaceMediaStream(e, t) {
957
957
  if (!this.session)
958
958
  throw new Error("No session established");
959
- const { contentHint: n } = t || {}, i = M(e, { contentHint: n });
959
+ const { contentHint: n } = t ?? {}, i = M(e, { contentHint: n });
960
960
  return this.session.replaceMediaStream(i, t);
961
961
  }
962
962
  async askPermissionToEnableCam(e = {}) {
@@ -1306,11 +1306,11 @@ export {
1306
1306
  xt as B,
1307
1307
  f as E,
1308
1308
  yt as N,
1309
- le as P,
1309
+ Te as P,
1310
1310
  ke as R,
1311
1311
  Ss as S,
1312
1312
  Tt as U,
1313
- Te as a,
1313
+ le as a,
1314
1314
  xn as b,
1315
1315
  Es as c,
1316
1316
  ds as d,
@@ -181,9 +181,9 @@ export default class SipConnector {
181
181
  ping(body?: string, extraHeaders?: string[]): Promise<void>;
182
182
  checkTelephony({ userAgent, displayName, sipServerUrl, sipWebSocketServerURL, remoteAddress, extraHeaders, }: TParametersCheckTelephony): Promise<void>;
183
183
  replaceMediaStream(mediaStream: MediaStream, options?: {
184
- deleteExisting: boolean;
185
- addMissing: boolean;
186
- forceRenegotiation: boolean;
184
+ deleteExisting?: boolean;
185
+ addMissing?: boolean;
186
+ forceRenegotiation?: boolean;
187
187
  contentHint?: TContentHint;
188
188
  sendEncodings?: RTCRtpEncodingParameters[];
189
189
  onAddedTransceiver?: TOnAddedTransceiver;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var k=Object.defineProperty;var b=(o,t,e)=>t in o?k(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>b(o,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("./SipConnector-_gw-GKlW.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),F=require("node:events"),V=require("@krivega/jssip/lib/SIPMessage"),C=require("webrtc-mock"),I=require("events-constructor"),T=require("@krivega/jssip");class y extends V.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class z{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new I(g.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get remote_identity(){return this._remote_identity}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class x{constructor({track:t}={}){r(this,"dtmf",null);r(this,"track",null);r(this,"transport",null);r(this,"transform",null);r(this,"_parameters",{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}});r(this,"_parametersGets");this.track=t??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(t){this.track=t??null}async setParameters(t){if(t!==this._parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:e}=this._parameters;this._parameters={...this._parameters,...t,transactionId:`${Number(e)+1}`}}getParameters(){return this._parametersGets={...this._parameters},this._parametersGets}setStreams(){throw new Error("Method not implemented.")}}class U{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e=new x({track:t});return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function q(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const w=400,N="777",H=o=>o.getVideoTracks().length>0,a=class a extends z{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"answer",jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},w)}));this.url=e,this.initPeerconnection(n)}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(e){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(e)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=C.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(H(e)){const u=C.createVideoMediaStreamTrackMock();u.id="mainvideo1",i.push(u)}this._connection=new U(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},w)}connect(e){const n=q(e);setTimeout(()=>{this.url.includes(N)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:g.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},w)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let l=a;class Y{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const c="PASSWORD_CORRECT",f="PASSWORD_CORRECT_2",P="NAME_INCORRECT",m=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new l({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new I(g.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,d]=n.split("@"),u={...t,uri:new T.URI(e,i,d)};this.configuration=u,this._registrator=new Y}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},m):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(P)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},m)):!this._isRegistered&&e&&(t===c||t===f)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},m)):e&&t!==c&&t!==f&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},m)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class j{constructor(t){r(this,"url");this.url=t}}class B extends F.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const S="remote",G=(o,t)=>{const e=new y(t),n={originator:S,request:e,info:new B("","")};o.newInfo(n)},K=(o,t)=>{const n={request:new y(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new l({originator:S}),d=new L("sip",t,n);i._remote_identity=new D(d,e),o.trigger("newRTCSession",{originator:S,session:i})},J=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:G,triggerNewSipEvent:K,triggerIncomingSession:$,triggerFailIncomingSession:J,WebSocketInterface:j,UA:M,C:{INVITE:"INVITE"}},_="user",h="displayName",p="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",X=new A.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:p,sipWebSocketServerURL:R},Q={...v},O={...v,user:_,password:c,register:!0},Z={...O,displayName:h},ee={...v,displayName:h,register:!1},E={session_timers:!1,sockets:[X],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},te={...E,password:c,uri:new T.URI("sip",_,p),display_name:"",register:!0},re={...E,password:c,uri:new T.URI("sip",_,p),display_name:h,register:!0},ne={...E,display_name:h,register:!1},oe={...E,display_name:"",register:!1},W="10.10.10.10",ie=[`X-Vinteo-Remote: ${W}`],se=()=>new g.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=N;exports.NAME_INCORRECT=P;exports.PASSWORD_CORRECT=c;exports.PASSWORD_CORRECT_2=f;exports.SIP_SERVER_URL=p;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=Z;exports.dataForConnectionWithoutAuthorization=ee;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Q;exports.default=se;exports.displayName=h;exports.extraHeadersRemoteAddress=ie;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=te;exports.uaConfigurationWithAuthorizationWithDisplayName=re;exports.uaConfigurationWithoutAuthorization=ne;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=oe;exports.user=_;
1
+ "use strict";var k=Object.defineProperty;var b=(o,t,e)=>t in o?k(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>b(o,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("./SipConnector-BWx586hI.cjs"),D=require("@krivega/jssip/lib/NameAddrHeader"),L=require("@krivega/jssip/lib/URI"),F=require("node:events"),V=require("@krivega/jssip/lib/SIPMessage"),C=require("webrtc-mock"),I=require("events-constructor"),T=require("@krivega/jssip");class y extends V.IncomingRequest{constructor(e){super();r(this,"headers");this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)||""}}class z{constructor({originator:t="local",eventHandlers:e}){r(this,"originator");r(this,"_connection");r(this,"_events");r(this,"_remote_identity");r(this,"_mutedOptions",{audio:!1,video:!1});this.originator=t,this._events=new I(g.SESSION_EVENT_NAMES),this.initEvents(e)}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}set data(t){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}get connection(){return this._connection}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get remote_identity(){return this._remote_identity}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(t){throw new Error("Method not implemented.")}terminate(t){throw new Error("Method not implemented.")}async sendInfo(t,e,n){throw new Error("Method not implemented.")}hold(t,e){throw new Error("Method not implemented.")}unhold(t,e){throw new Error("Method not implemented.")}async renegotiate(t,e){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(t){throw new Error("Method not implemented.")}unmute(t){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(t,e){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(t,e){throw new Error("Method not implemented.")}addListener(t,e){throw new Error("Method not implemented.")}once(t,e){throw new Error("Method not implemented.")}removeListener(t,e){throw new Error("Method not implemented.")}off(t,e){throw new Error("Method not implemented.")}removeAllListeners(t){throw new Error("Method not implemented.")}setMaxListeners(t){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(t){throw new Error("Method not implemented.")}rawListeners(t){throw new Error("Method not implemented.")}emit(t,...e){throw new Error("Method not implemented.")}listenerCount(t){throw new Error("Method not implemented.")}prependListener(t,e){throw new Error("Method not implemented.")}prependOnceListener(t,e){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(t=[]){Object.entries(t).forEach(([e,n])=>this.on(e,n))}on(t,e){return this._events.on(t,e),this}trigger(t,e){this._events.trigger(t,e)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(t){return t}async updatePresentation(t){return t}async stopPresentation(t){return t}isEstablished(){return!0}}class x{constructor({track:t}={}){r(this,"dtmf",null);r(this,"track",null);r(this,"transport",null);r(this,"transform",null);r(this,"_parameters",{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}});r(this,"_parametersGets");this.track=t??null}async getStats(){throw new Error("Method not implemented.")}async replaceTrack(t){this.track=t??null}async setParameters(t){if(t!==this._parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:e}=this._parameters;this._parameters={...this._parameters,...t,transactionId:`${Number(e)+1}`}}getParameters(){return this._parametersGets={...this._parameters},this._parametersGets}setStreams(){throw new Error("Method not implemented.")}}class U{constructor(t,e){r(this,"_senders",[]);r(this,"_receivers",[]);r(this,"canTrickleIceCandidates");r(this,"connectionState");r(this,"currentLocalDescription");r(this,"currentRemoteDescription");r(this,"iceConnectionState");r(this,"iceGatheringState");r(this,"idpErrorInfo");r(this,"idpLoginUrl");r(this,"localDescription");r(this,"onconnectionstatechange");r(this,"ondatachannel");r(this,"onicecandidate");r(this,"onicecandidateerror",null);r(this,"oniceconnectionstatechange");r(this,"onicegatheringstatechange");r(this,"onnegotiationneeded");r(this,"onsignalingstatechange");r(this,"ontrack");r(this,"peerIdentity");r(this,"pendingLocalDescription");r(this,"pendingRemoteDescription");r(this,"remoteDescription");r(this,"sctp",null);r(this,"signalingState");r(this,"getReceivers",()=>this._receivers);r(this,"getSenders",()=>this._senders);r(this,"addTrack",t=>{const e=new x({track:t});return this._senders.push(e),e});this._receivers=e.map(n=>({track:n}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(t){throw new Error("Method not implemented.")}addTransceiver(t,e){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(t,e){throw new Error("Method not implemented.")}createDataChannel(t,e){throw new Error("Method not implemented.")}async createOffer(t,e,n){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(t){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(t){throw new Error("Method not implemented.")}setConfiguration(t){throw new Error("Method not implemented.")}async setLocalDescription(t){throw new Error("Method not implemented.")}async setRemoteDescription(t){throw new Error("Method not implemented.")}addEventListener(t,e,n){throw new Error("Method not implemented.")}removeEventListener(t,e,n){throw new Error("Method not implemented.")}dispatchEvent(t){throw new Error("Method not implemented.")}}function q(o){const t=o.match(/(purgatory)|[\d.]+/g);if(!t)throw new Error("wrong sip url");return t[0]}const w=400,N="777",H=o=>o.getVideoTracks().length>0,a=class a extends z{constructor({url:e="",mediaStream:n,eventHandlers:i,originator:d}){super({originator:d,eventHandlers:i});r(this,"url");r(this,"status_code");r(this,"_isEnded",!1);r(this,"answer",jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},w)}));this.url=e,this.initPeerconnection(n)}static setStartPresentationError(e,{count:n=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=n}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}async startPresentation(e){if(a.countStartsPresentation+=1,a.startPresentationError&&a.countStartsPresentation<a.countStartPresentationError)throw a.startPresentationError;return super.startPresentation(e)}initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const n=C.createAudioMediaStreamTrackMock();n.id="mainaudio1";const i=[n];if(H(e)){const u=C.createVideoMediaStreamTrackMock();u.id="mainvideo1",i.push(u)}this._connection=new U(void 0,i),this._addStream(e),setTimeout(()=>{this.trigger("peerconnection",{peerconnection:this.connection})},w)}connect(e){const n=q(e);setTimeout(()=>{this.url.includes(N)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:g.REJECTED}):(this.trigger("connecting"),setTimeout(()=>{this.trigger("enterRoom",{room:n})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},w)}terminate({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e}),this._isEnded=!1,this}async terminateAsync({status_code:e}={}){this.terminate({status_code:e})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}_addStream(e,n="getTracks"){e[n]().forEach(i=>this.connection.addTrack(i))}_forEachSenders(e){const n=this.connection.getSenders();for(const i of n)e(i);return n}_toggleMuteAudio(e){this._forEachSenders(({track:n})=>{n&&n.kind==="audio"&&(n.enabled=!e)})}_toggleMuteVideo(e){this._forEachSenders(({track:n})=>{n&&n.kind==="video"&&(n.enabled=!e)})}mute(e){e.audio&&(this._mutedOptions.audio=!0,this._toggleMuteAudio(this._mutedOptions.audio)),e.video&&(this._mutedOptions.video=!0,this._toggleMuteVideo(this._mutedOptions.video)),this._onmute(e)}unmute(e){e.audio&&(this._mutedOptions.audio=!1),e.video&&(this._mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this._mutedOptions}async replaceMediaStream(e){return e}_onmute({audio:e,video:n}){this.trigger("muted",{audio:e,video:n})}async sendInfo(){}isEnded(){return this._isEnded}newInfo(e){this.trigger("newInfo",e)}};r(a,"startPresentationError"),r(a,"countStartPresentationError",Number.POSITIVE_INFINITY),r(a,"countStartsPresentation",0);let l=a;class Y{constructor(){r(this,"extraHeaders",[])}setExtraHeaders(t){this.extraHeaders=t}setExtraContactParams(){}}const c="PASSWORD_CORRECT",f="PASSWORD_CORRECT_2",P="NAME_INCORRECT",m=400,s=class s{constructor(t){r(this,"_events");r(this,"_startedTimeout");r(this,"_stopedTimeout");r(this,"session");r(this,"_isRegistered");r(this,"_isConnected");r(this,"configuration");r(this,"_registrator");r(this,"call",jest.fn((t,e)=>{const{mediaStream:n,eventHandlers:i}=e;return this.session=new l({url:t,mediaStream:n,eventHandlers:i,originator:"local"}),this.session.connect(t),this.session}));this._events=new I(g.UA_EVENT_NAMES);const[e,n]=t.uri.split(":"),[i,d]=n.split("@"),u={...t,uri:new T.URI(e,i,d)};this.configuration=u,this._registrator=new Y}static setStartError(t,{count:e=Number.POSITIVE_INFINITY}={}){this.startError=t,this.countStartError=e}static resetStartError(){this.startError=void 0,this.countStartError=Number.POSITIVE_INFINITY,this.countStarts=0}static setAvailableTelephony(){this.isAvailableTelephony=!0}static setNotAvailableTelephony(){this.isAvailableTelephony=!1}isConnected(){return!!this._isConnected}start(){if(s.countStarts+=1,s.startError&&s.countStarts<s.countStartError){this.trigger("disconnected",s.startError);return}this.register()}stop(){this._startedTimeout&&clearTimeout(this._startedTimeout),this._stopedTimeout&&clearTimeout(this._stopedTimeout),this.unregister(),this.isStarted()?this._stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:new Error("stoped")})},m):this.trigger("disconnected",{error:new Error("stoped")})}on(t,e){return this._events.on(t,e),this}once(t,e){return this._events.once(t,e),this}off(t,e){return this._events.off(t,e),this}removeAllListeners(){return this._events.removeEventHandlers(),this}trigger(t,e){this._events.trigger(t,e)}terminateSessions(){this.session.terminate()}set(t,e){return this.configuration[t]=e,!0}register(){this._startedTimeout&&clearTimeout(this._startedTimeout);const{password:t,register:e,uri:n}=this.configuration;e&&n.user.includes(P)?(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Request Timeout"})},m)):!this._isRegistered&&e&&(t===c||t===f)?(this._isRegistered=!0,this._startedTimeout=setTimeout(()=>{this.trigger("registered")},m)):e&&t!==c&&t!==f&&(this._isRegistered=!1,this._isConnected=!1,this._startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:null,cause:"Wrong credentials"})},m)),s.isAvailableTelephony?(this.trigger("connected"),this._isConnected=!0):this.stop()}unregister(){this._isRegistered=!1,this._isConnected=!1,this.trigger("unregistered")}isRegistered(){return!!this._isRegistered}isStarted(){return this.configuration&&(this.configuration.register&&!!this._isRegistered||!this.configuration.register&&!!this._isConnected)}registrator(){return this._registrator}newSipEvent(t){this.trigger("sipEvent",t)}};r(s,"isAvailableTelephony",!0),r(s,"startError"),r(s,"countStartError",Number.POSITIVE_INFINITY),r(s,"countStarts",0);let M=s;class j{constructor(t){r(this,"url");this.url=t}}class B extends F.EventEmitter{constructor(e,n){super();r(this,"contentType");r(this,"body");this.contentType=e,this.body=n}}const S="remote",G=(o,t)=>{const e=new y(t),n={originator:S,request:e,info:new B("","")};o.newInfo(n)},K=(o,t)=>{const n={request:new y(t)};o.newSipEvent(n)},$=(o,{incomingNumber:t="1234",displayName:e,host:n})=>{const i=new l({originator:S}),d=new L("sip",t,n);i._remote_identity=new D(d,e),o.trigger("newRTCSession",{originator:S,session:i})},J=(o,t)=>{t?o.trigger("failed",t):o.trigger("failed",o)},A={triggerNewInfo:G,triggerNewSipEvent:K,triggerIncomingSession:$,triggerFailIncomingSession:J,WebSocketInterface:j,UA:M,C:{INVITE:"INVITE"}},_="user",h="displayName",p="SIP_SERVER_URL",R="SIP_WEB_SOCKET_SERVER_URL",X=new A.WebSocketInterface(R),v={userAgent:"Chrome",sipServerUrl:p,sipWebSocketServerURL:R},Q={...v},O={...v,user:_,password:c,register:!0},Z={...O,displayName:h},ee={...v,displayName:h,register:!1},E={session_timers:!1,sockets:[X],user_agent:"Chrome",sdp_semantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},te={...E,password:c,uri:new T.URI("sip",_,p),display_name:"",register:!0},re={...E,password:c,uri:new T.URI("sip",_,p),display_name:h,register:!0},ne={...E,display_name:h,register:!1},oe={...E,display_name:"",register:!1},W="10.10.10.10",ie=[`X-Vinteo-Remote: ${W}`],se=()=>new g.SipConnector({JsSIP:A});exports.FAILED_CONFERENCE_NUMBER=N;exports.NAME_INCORRECT=P;exports.PASSWORD_CORRECT=c;exports.PASSWORD_CORRECT_2=f;exports.SIP_SERVER_URL=p;exports.SIP_WEB_SOCKET_SERVER_URL=R;exports.dataForConnectionWithAuthorization=O;exports.dataForConnectionWithAuthorizationWithDisplayName=Z;exports.dataForConnectionWithoutAuthorization=ee;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Q;exports.default=se;exports.displayName=h;exports.extraHeadersRemoteAddress=ie;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=te;exports.uaConfigurationWithAuthorizationWithDisplayName=re;exports.uaConfigurationWithoutAuthorization=ne;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=oe;exports.user=_;
package/dist/doMock.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var y = Object.defineProperty;
2
2
  var N = (o, t, e) => t in o ? y(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
3
  var r = (o, t, e) => N(o, typeof t != "symbol" ? t + "" : t, e);
4
- import { m as P, R as O, U as k, S as A } from "./SipConnector-BGDcrO00.js";
4
+ import { m as P, R as O, U as k, S as A } from "./SipConnector-DhuPlarI.js";
5
5
  import b from "@krivega/jssip/lib/NameAddrHeader";
6
6
  import D from "@krivega/jssip/lib/URI";
7
7
  import { EventEmitter as L } from "node:events";
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const s=require("./SipConnector-_gw-GKlW.cjs"),ee=require("ts-debounce"),ne=require("@krivega/cancelable-promise"),te=require("repeated-calls"),re=require("sequent-promises"),se=require("stack-promises"),oe=require("debug"),ce=e=>e.getVideoTracks()[0],ae=1e6,E=e=>e*ae,j=E(.06),ie=E(4),ue=e=>e<=64?j:e<=128?E(.12):e<=256?E(.25):e<=384?E(.32):e<=426?E(.38):e<=640?E(.5):e<=848?E(.7):e<=1280?E(1):e<=1920?E(2):ie,G=(e,t)=>e!==void 0&&t!==void 0&&e.toLowerCase().includes(t.toLowerCase()),le="av1",ge=e=>G(e,le),de=.6,H=(e,t)=>ge(t)?e*de:e,Se=e=>H(j,e),W=(e,t)=>{const n=ue(e);return H(n,t)},me=1,K=({videoTrack:e,targetSize:t,codec:n})=>{const r=e.getSettings(),o=r.width,c=r.height,a=o/t.width,i=c/t.height,u=Math.max(a,i,me),g=W(t.width,n);return{scaleResolutionDownBy:u,maxBitrate:g}},N=({mediaStream:e,simulcastEncodings:t,sendEncodings:n})=>{if(t&&t.length>0){const r=n??[],o=ce(e);return t.forEach((c,a)=>{const i=r[a]??{},{maxBitrate:u,scaleResolutionDownBy:g}=K({videoTrack:o,targetSize:{width:c.width,height:c.height}});i.maxBitrate=u,i.scaleResolutionDownBy=g,r[a]=i}),r}return n},Y="purgatory",P=e=>e===Y,L=e=>()=>(s.logger("getRemoteStreams"),e.getRemoteStreams()),fe=({kind:e,readyState:t})=>e==="video"&&t==="live",z=e=>({track:t})=>{fe(t)&&e()},V=({getRemoteStreams:e,setRemoteStreams:t})=>ee.debounce(()=>{const n=e();s.logger("remoteStreams",n),n&&t(n)},200),I=e=>async t=>{Object.keys(e).length>0&&await s.setParametersToSender(t.sender,e)},Ce=e=>async n=>{const{mediaStream:r,extraHeaders:o,iceServers:c,contentHint:a,simulcastEncodings:i,degradationPreference:u,sendEncodings:g,setRemoteStreams:m,onBeforeProgressCall:f,onSuccessProgressCall:S,onEnterPurgatory:h,onEnterConference:d,onFailProgressCall:C,onFinishProgressCall:T,onEndedCall:y}=n,v=V({setRemoteStreams:m,getRemoteStreams:L(e)}),_=z(v),b=I({degradationPreference:u});s.logger("answerIncomingCall",n);const O=async()=>e.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:c,contentHint:a,sendEncodings:N({mediaStream:r,simulcastEncodings:i,sendEncodings:g}),onAddedTransceiver:b,ontrack:_}),A=()=>{const{remoteCallerData:l}=e;return l.incomingNumber};let R=!1,M;const p=(s.logger("subscribeEnterConference: onEnterConference",d),h??d?e.onSession("enterRoom",l=>{s.logger("enterRoom",{_room:l,isSuccessProgressCall:R}),M=l,P(M)?h&&h():d&&d({isSuccessProgressCall:R})}):()=>{}),D=l=>(s.logger("onSuccess"),R=!0,v(),S&&S({isPurgatory:P(M)}),e.onceRaceSession(["ended","failed"],()=>{p(),y&&y()}),l),w=l=>{throw s.logger("onFail"),C&&C(),p(),l},F=()=>{s.logger("onFinish"),T&&T()};if(s.logger("onBeforeProgressCall"),f){const l=A();f(l)}return O().then(D).catch(l=>w(l)).finally(F)},Ee=e=>async n=>{const{conference:r,mediaStream:o,extraHeaders:c,iceServers:a,contentHint:i,simulcastEncodings:u,degradationPreference:g,sendEncodings:m,setRemoteStreams:f,onBeforeProgressCall:S,onSuccessProgressCall:h,onEnterPurgatory:d,onEnterConference:C,onFailProgressCall:T,onFinishProgressCall:y,onEndedCall:v}=n,_=V({setRemoteStreams:f,getRemoteStreams:L(e)}),b=z(_),O=I({degradationPreference:g});s.logger("callToServer",n);const A=async()=>(s.logger("startCall"),e.call({mediaStream:o,extraHeaders:c,iceServers:a,contentHint:i,sendEncodings:N({mediaStream:o,simulcastEncodings:u,sendEncodings:m}),number:r,onAddedTransceiver:O,ontrack:b}));let R=!1,M;const p=(s.logger("subscribeEnterConference: onEnterConference",C),d??C?e.onSession("enterRoom",({room:l})=>{s.logger("enterRoom",{_room:l,isSuccessProgressCall:R}),M=l,P(M)?d&&d():C&&C({isSuccessProgressCall:R})}):()=>{}),D=l=>(s.logger("onSuccess"),R=!0,_(),h&&h({isPurgatory:P(M)}),e.onceRaceSession(["ended","failed"],()=>{p(),v&&v()}),l),w=l=>{throw s.logger("onFail"),T&&T(),p(),l},F=()=>{s.logger("onFinish"),y&&y()};return s.logger("onBeforeProgressCall"),S&&S(r),A().then(D).catch(l=>w(l)).finally(F)},k=e=>{if(!ne.isCanceledError(e)&&!te.hasCanceledError(e))throw e;return{isSuccessful:!1}},Te=e=>async n=>{const{userAgent:r,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,name:u,password:g,isRegisteredUser:m,isDisconnectOnFail:f}=n;return s.logger("connectToServer",n),e.connect({userAgent:r,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,password:g,user:u,register:m}).then(S=>(s.logger("connectToServer then"),{ua:S,isSuccessful:!0})).catch(async S=>(s.logger("connectToServer catch: error",S),f===!0?e.disconnect().then(()=>k(S)).catch(()=>k(S)):k(S)))},Re=e=>async()=>(s.logger("disconnectFromServer"),e.disconnect().then(()=>(s.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(t=>(s.logger("disconnectFromServer: catch",t),{isSuccessful:!1}))),x=e=>{const{url:t,cause:n}=e;let r=t;return(n===s.BAD_MEDIA_DESCRIPTION||n===s.NOT_FOUND)&&(r=`${e.message.to.uri.user}@${e.message.to.uri.host}`),r};var Q=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(Q||{});const Me=(e=new Error)=>{var o;const{cause:t,socket:n}=e;let r="CONNECT_SERVER_FAILED";switch(t){case"Forbidden":{r="WRONG_USER_OR_PASSWORD";break}case s.BAD_MEDIA_DESCRIPTION:{r="BAD_MEDIA_ERROR";break}case s.NOT_FOUND:{r="NOT_FOUND_ERROR";break}default:n&&((o=n==null?void 0:n._ws)==null?void 0:o.readyState)===3?r="WS_CONNECTION_FAILED":x(e)&&(r="CONNECT_SERVER_FAILED_BY_LINK")}return r},he=e=>{let t="";try{t=JSON.stringify(e)}catch(n){s.logger("failed to stringify message",n)}return t},ye=(e=new Error)=>{const{code:t,cause:n,message:r}=e,o=x(e),c={code:"",cause:"",message:""};return typeof r=="object"&&r!==null?c.message=he(r):r&&(c.message=String(r)),o&&(c.link=o),t&&(c.code=t),n&&(c.cause=n),c},ve=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:Q,getLinkError:x,getTypeFromError:Me,getValuesFromError:ye},Symbol.toStringTag,{value:"Module"})),_e=({sessionId:e,remoteAddress:t,isMutedAudio:n,isMutedVideo:r,isRegistered:o,isPresentationCall:c})=>{const a=[],i=n?"0":"1",u=r?"0":"1";return a.push(`X-Vinteo-Mic-State: ${i}`,`X-Vinteo-MainCam-State: ${u}`),o||a.push("X-Vinteo-Purgatory-Call: yes"),e&&a.push(`X-Vinteo-Session: ${e}`),c&&a.push("X-Vinteo-Presentation-Call: yes"),t&&a.push(`X-Vinteo-Remote: ${t}`),a},be="[@*!|]",Oe="_",Ae=e=>{let t=e;return t=t.replaceAll(new RegExp(be,"g"),Oe),t},pe=({appName:e,appVersion:t,browserName:n,browserVersion:r})=>{const c=`${Ae(e)} ${t}`;return`ChromeNew - ${n?`${n} ${r}, ${c}`:c}`},Pe=({isUnifiedSdpSemantic:e,appVersion:t,browserName:n,browserVersion:r,appName:o})=>e?pe({appVersion:t,browserName:n,browserVersion:r,appName:o}):"Chrome",Ne=e=>async()=>{if(e.isCallActive)return s.logger("askPermissionToEnableCam"),e.askPermissionToEnableCam()},Ie=e=>n=>(s.logger("onMustStopPresentation"),e.onSession("mustStopPresentation",n)),Be=e=>n=>(s.logger("onMoveToSpectators"),e.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,n)),De=e=>n=>(s.logger("onMoveToParticipants"),e.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,n)),we=e=>n=>(s.logger("onUseLicense"),e.onSession("useLicense",n)),Fe=e=>async({isEnabledCam:n,isEnabledMic:r})=>{if(e.isCallActive)return s.logger("sendMediaState"),e.sendMediaState({cam:n,mic:r})},ke=e=>async()=>{if(e.isCallActive)return s.logger("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch(n=>{s.logger("sendRefusalToTurnOnCam: error",n)})},Ue=e=>async()=>{if(e.isCallActive)return s.logger("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch(n=>{s.logger("sendRefusalToTurnOnMic: error",n)})},Le=e=>async({mediaStream:n,isP2P:r,maxBitrate:o,contentHint:c,simulcastEncodings:a,degradationPreference:i,sendEncodings:u},g)=>{const m=I({degradationPreference:i});return s.logger("startPresentation"),e.startPresentation(n,{isP2P:r,maxBitrate:o,contentHint:c,sendEncodings:N({mediaStream:n,simulcastEncodings:a,sendEncodings:u}),onAddedTransceiver:m},g)},Ve=e=>async({isP2P:n=!1}={})=>(s.logger("stopShareSipConnector"),e.stopPresentation({isP2P:n}).catch(r=>{s.logger(r)})),xe=e=>async({mediaStream:n,isP2P:r,maxBitrate:o,contentHint:c,simulcastEncodings:a,degradationPreference:i,sendEncodings:u})=>{const g=I({degradationPreference:i});return s.logger("updatePresentation"),e.updatePresentation(n,{isP2P:r,maxBitrate:o,contentHint:c,sendEncodings:N({mediaStream:n,simulcastEncodings:a,sendEncodings:u}),onAddedTransceiver:g})},$e=e=>t=>[...t].map(r=>async()=>e(r)),qe=async({accumulatedKeys:e,sendKey:t,canRunTask:n})=>{const o=$e(t)(e);return re.sequentPromises(o,n)},Xe=e=>n=>(s.logger("onStartMainCam"),e.onSession("admin-start-main-cam",n)),je=e=>n=>(s.logger("onStartMic"),e.onSession("admin-start-mic",n)),Ge=e=>n=>(s.logger("onStopMainCam"),e.onSession("admin-stop-main-cam",n)),He=e=>n=>(s.logger("onStopMic"),e.onSession("admin-stop-mic",n)),We=({sipConnector:e})=>{const t=(d,C)=>({isSyncForced:T=!1})=>{if(T){d();return}C()},n=Xe(e),r=Ge(e),o=je(e),c=He(e);let a=()=>{},i=()=>{},u=()=>{},g=()=>{};const m=({onStartMainCamForced:d,onStartMainCamNotForced:C,onStopMainCamForced:T,onStopMainCamNotForced:y,onStartMicForced:v,onStartMicNotForced:_,onStopMicForced:b,onStopMicNotForced:O})=>{const A=t(d,C);a=n(A);const R=t(T,y);i=r(R);const M=t(v,_);u=o(M);const B=t(b,O);g=c(B)},f=()=>{a(),i(),u(),g()};return{start:d=>{m(d)},stop:()=>{f()}}},Ke=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:Y,createSyncMediaState:We,error:ve,getExtraHeaders:_e,getUserAgent:Pe,hasPurgatory:P,resolveAnswerIncomingCall:Ce,resolveAskPermissionToEnableCam:Ne,resolveCallToServer:Ee,resolveConnectToServer:Te,resolveDisconnectFromServer:Re,resolveGetRemoteStreams:L,resolveOnMoveToParticipants:De,resolveOnMoveToSpectators:Be,resolveOnMustStopPresentation:Ie,resolveOnUseLicense:we,resolveSendMediaState:Fe,resolveSendRefusalToTurnOnCam:ke,resolveSendRefusalToTurnOnMic:Ue,resolveStartPresentation:Le,resolveStopShareSipConnector:Ve,resolveUpdatePresentation:xe,resolveUpdateRemoteStreams:V,sendDTMFAccumulated:qe},Symbol.toStringTag,{value:"Module"})),Ye=e=>[...e.keys()].map(t=>e.get(t)),ze=(e,t)=>Ye(e).find(n=>n.type===t),J=async e=>e.getStats().then(t=>{const n=ze(t,"codec");return n==null?void 0:n.mimeType}),Qe=e=>e.find(t=>{var n;return((n=t==null?void 0:t.track)==null?void 0:n.kind)==="video"}),Z=se.createStackPromises(),Je=async()=>Z().catch(e=>{s.logger("videoSendingBalancer: error",e)}),Ze=async e=>(Z.add(e),Je()),$=async({sender:e,scaleResolutionDownBy:t,maxBitrate:n,onSetParameters:r})=>Ze(async()=>s.setEncodingsToSender(e,{scaleResolutionDownBy:t,maxBitrate:n},r)),en=async({sender:e,codec:t},n)=>{const o=Se(t);return $({sender:e,maxBitrate:o,onSetParameters:n,scaleResolutionDownBy:200})},U=async({sender:e,videoTrack:t,codec:n},r)=>{const a=t.getSettings().width,i=W(a,n);return $({sender:e,maxBitrate:i,onSetParameters:r,scaleResolutionDownBy:1})},nn=async({sender:e,videoTrack:t,resolution:n,codec:r},o)=>{const[c,a]=n.split("x"),{maxBitrate:i,scaleResolutionDownBy:u}=K({videoTrack:t,codec:r,targetSize:{width:Number(c),height:Number(a)}});return $({sender:e,maxBitrate:i,onSetParameters:o,scaleResolutionDownBy:u})},tn=async({mainCam:e,resolutionMainCam:t,sender:n,videoTrack:r,codec:o},c)=>{switch(e){case s.EEventsMainCAM.PAUSE_MAIN_CAM:return en({sender:n,codec:o},c);case s.EEventsMainCAM.RESUME_MAIN_CAM:return U({sender:n,videoTrack:r,codec:o},c);case s.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return t!==void 0?nn({sender:n,videoTrack:r,codec:o,resolution:t},c):U({sender:n,videoTrack:r,codec:o},c);default:return U({sender:n,videoTrack:r,codec:o},c)}},q={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},X=async({mainCam:e,resolutionMainCam:t,connection:n,onSetParameters:r,ignoreForCodec:o})=>{const c=n.getSenders(),a=Qe(c);if(!(a!=null&&a.track))return q;const i=await J(a);return G(i,o)?q:tn({mainCam:e,resolutionMainCam:t,sender:a,codec:i,videoTrack:a.track},r)},rn=(e,{ignoreForCodec:t,onSetParameters:n}={})=>{const r=async()=>{const{connection:u}=e;if(!u)throw new Error("connection is not exist");return X({connection:u,onSetParameters:n,ignoreForCodec:t})};let o=r;const c=async u=>(o=async()=>{const{mainCam:g,resolutionMainCam:m}=u,{connection:f}=e;if(!f)throw new Error("connection is not exist");return X({mainCam:g,resolutionMainCam:m,connection:f,onSetParameters:n,ignoreForCodec:t})},o());return{subscribe:()=>{e.onSession("main-cam-control",c)},unsubscribe:()=>{e.offSession("main-cam-control",c)},balanceByTrack:r,resetMainCamControl(){o=r},async reBalance(){return o()}}};exports.EEventsMainCAM=s.EEventsMainCAM;exports.EEventsMic=s.EEventsMic;exports.EEventsSyncMediaState=s.EEventsSyncMediaState;exports.EUseLicense=s.EUseLicense;exports.causes=s.causes;exports.constants=s.constants;exports.default=s.SipConnector;exports.disableDebug=s.disableDebug;exports.enableDebug=s.enableDebug;exports.eventNames=s.eventNames;exports.hasCanceledCallError=s.hasCanceledCallError;exports.setParametersToSender=s.setParametersToSender;exports.debug=oe;exports.getCodecFromSender=J;exports.resolveVideoSendingBalancer=rn;exports.tools=Ke;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const s=require("./SipConnector-BWx586hI.cjs"),ee=require("ts-debounce"),ne=require("@krivega/cancelable-promise"),te=require("repeated-calls"),re=require("sequent-promises"),se=require("stack-promises"),oe=require("debug"),ce=e=>e.getVideoTracks()[0],ae=1e6,E=e=>e*ae,j=E(.06),ie=E(4),ue=e=>e<=64?j:e<=128?E(.12):e<=256?E(.25):e<=384?E(.32):e<=426?E(.38):e<=640?E(.5):e<=848?E(.7):e<=1280?E(1):e<=1920?E(2):ie,G=(e,t)=>e!==void 0&&t!==void 0&&e.toLowerCase().includes(t.toLowerCase()),le="av1",ge=e=>G(e,le),de=.6,H=(e,t)=>ge(t)?e*de:e,Se=e=>H(j,e),W=(e,t)=>{const n=ue(e);return H(n,t)},me=1,K=({videoTrack:e,targetSize:t,codec:n})=>{const r=e.getSettings(),o=r.width,c=r.height,a=o/t.width,i=c/t.height,u=Math.max(a,i,me),g=W(t.width,n);return{scaleResolutionDownBy:u,maxBitrate:g}},N=({mediaStream:e,simulcastEncodings:t,sendEncodings:n})=>{if(t&&t.length>0){const r=n??[],o=ce(e);return t.forEach((c,a)=>{const i=r[a]??{},{maxBitrate:u,scaleResolutionDownBy:g}=K({videoTrack:o,targetSize:{width:c.width,height:c.height}});i.maxBitrate=u,i.scaleResolutionDownBy=g,r[a]=i}),r}return n},Y="purgatory",P=e=>e===Y,L=e=>()=>(s.logger("getRemoteStreams"),e.getRemoteStreams()),fe=({kind:e,readyState:t})=>e==="video"&&t==="live",z=e=>({track:t})=>{fe(t)&&e()},V=({getRemoteStreams:e,setRemoteStreams:t})=>ee.debounce(()=>{const n=e();s.logger("remoteStreams",n),n&&t(n)},200),I=e=>async t=>{Object.keys(e).length>0&&await s.setParametersToSender(t.sender,e)},Ce=e=>async n=>{const{mediaStream:r,extraHeaders:o,iceServers:c,contentHint:a,simulcastEncodings:i,degradationPreference:u,sendEncodings:g,setRemoteStreams:S,onBeforeProgressCall:f,onSuccessProgressCall:m,onEnterPurgatory:h,onEnterConference:d,onFailProgressCall:C,onFinishProgressCall:T,onEndedCall:v}=n,y=V({setRemoteStreams:S,getRemoteStreams:L(e)}),_=z(y),b=I({degradationPreference:u});s.logger("answerIncomingCall",n);const O=async()=>e.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:c,contentHint:a,sendEncodings:N({mediaStream:r,simulcastEncodings:i,sendEncodings:g}),onAddedTransceiver:b,ontrack:_}),A=()=>{const{remoteCallerData:l}=e;return l.incomingNumber};let R=!1,M;const p=(s.logger("subscribeEnterConference: onEnterConference",d),h??d?e.onSession("enterRoom",l=>{s.logger("enterRoom",{_room:l,isSuccessProgressCall:R}),M=l,P(M)?h&&h():d&&d({isSuccessProgressCall:R})}):()=>{}),D=l=>(s.logger("onSuccess"),R=!0,y(),m&&m({isPurgatory:P(M)}),e.onceRaceSession(["ended","failed"],()=>{p(),v&&v()}),l),w=l=>{throw s.logger("onFail"),C&&C(),p(),l},F=()=>{s.logger("onFinish"),T&&T()};if(s.logger("onBeforeProgressCall"),f){const l=A();f(l)}return O().then(D).catch(l=>w(l)).finally(F)},Ee=e=>async n=>{const{conference:r,mediaStream:o,extraHeaders:c,iceServers:a,contentHint:i,simulcastEncodings:u,degradationPreference:g,sendEncodings:S,setRemoteStreams:f,onBeforeProgressCall:m,onSuccessProgressCall:h,onEnterPurgatory:d,onEnterConference:C,onFailProgressCall:T,onFinishProgressCall:v,onEndedCall:y}=n,_=V({setRemoteStreams:f,getRemoteStreams:L(e)}),b=z(_),O=I({degradationPreference:g});s.logger("callToServer",n);const A=async()=>(s.logger("startCall"),e.call({mediaStream:o,extraHeaders:c,iceServers:a,contentHint:i,sendEncodings:N({mediaStream:o,simulcastEncodings:u,sendEncodings:S}),number:r,onAddedTransceiver:O,ontrack:b}));let R=!1,M;const p=(s.logger("subscribeEnterConference: onEnterConference",C),d??C?e.onSession("enterRoom",({room:l})=>{s.logger("enterRoom",{_room:l,isSuccessProgressCall:R}),M=l,P(M)?d&&d():C&&C({isSuccessProgressCall:R})}):()=>{}),D=l=>(s.logger("onSuccess"),R=!0,_(),h&&h({isPurgatory:P(M)}),e.onceRaceSession(["ended","failed"],()=>{p(),y&&y()}),l),w=l=>{throw s.logger("onFail"),T&&T(),p(),l},F=()=>{s.logger("onFinish"),v&&v()};return s.logger("onBeforeProgressCall"),m&&m(r),A().then(D).catch(l=>w(l)).finally(F)},k=e=>{if(!ne.isCanceledError(e)&&!te.hasCanceledError(e))throw e;return{isSuccessful:!1}},Te=e=>async n=>{const{userAgent:r,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,name:u,password:g,isRegisteredUser:S,isDisconnectOnFail:f}=n;return s.logger("connectToServer",n),e.connect({userAgent:r,sipWebSocketServerURL:o,sipServerUrl:c,remoteAddress:a,displayName:i,password:g,user:u,register:S}).then(m=>(s.logger("connectToServer then"),{ua:m,isSuccessful:!0})).catch(async m=>(s.logger("connectToServer catch: error",m),f===!0?e.disconnect().then(()=>k(m)).catch(()=>k(m)):k(m)))},Re=e=>async()=>(s.logger("disconnectFromServer"),e.disconnect().then(()=>(s.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(t=>(s.logger("disconnectFromServer: catch",t),{isSuccessful:!1}))),x=e=>{const{url:t,cause:n}=e;let r=t;return(n===s.BAD_MEDIA_DESCRIPTION||n===s.NOT_FOUND)&&(r=`${e.message.to.uri.user}@${e.message.to.uri.host}`),r};var Q=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(Q||{});const Me=(e=new Error)=>{var o;const{cause:t,socket:n}=e;let r="CONNECT_SERVER_FAILED";switch(t){case"Forbidden":{r="WRONG_USER_OR_PASSWORD";break}case s.BAD_MEDIA_DESCRIPTION:{r="BAD_MEDIA_ERROR";break}case s.NOT_FOUND:{r="NOT_FOUND_ERROR";break}default:n&&((o=n==null?void 0:n._ws)==null?void 0:o.readyState)===3?r="WS_CONNECTION_FAILED":x(e)&&(r="CONNECT_SERVER_FAILED_BY_LINK")}return r},he=e=>{let t="";try{t=JSON.stringify(e)}catch(n){s.logger("failed to stringify message",n)}return t},ve=(e=new Error)=>{const{code:t,cause:n,message:r}=e,o=x(e),c={code:"",cause:"",message:""};return typeof r=="object"&&r!==null?c.message=he(r):r&&(c.message=String(r)),o&&(c.link=o),t&&(c.code=t),n&&(c.cause=n),c},ye=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:Q,getLinkError:x,getTypeFromError:Me,getValuesFromError:ve},Symbol.toStringTag,{value:"Module"})),_e=({sessionId:e,remoteAddress:t,isMutedAudio:n,isMutedVideo:r,isRegistered:o,isPresentationCall:c})=>{const a=[],i=n?"0":"1",u=r?"0":"1";return a.push(`X-Vinteo-Mic-State: ${i}`,`X-Vinteo-MainCam-State: ${u}`),o||a.push("X-Vinteo-Purgatory-Call: yes"),e&&a.push(`X-Vinteo-Session: ${e}`),c&&a.push("X-Vinteo-Presentation-Call: yes"),t&&a.push(`X-Vinteo-Remote: ${t}`),a},be="[@*!|]",Oe="_",Ae=e=>{let t=e;return t=t.replaceAll(new RegExp(be,"g"),Oe),t},pe=({appName:e,appVersion:t,browserName:n,browserVersion:r})=>{const c=`${Ae(e)} ${t}`;return`ChromeNew - ${n?`${n} ${r}, ${c}`:c}`},Pe=({isUnifiedSdpSemantic:e,appVersion:t,browserName:n,browserVersion:r,appName:o})=>e?pe({appVersion:t,browserName:n,browserVersion:r,appName:o}):"Chrome",Ne=e=>async()=>{if(e.isCallActive)return s.logger("askPermissionToEnableCam"),e.askPermissionToEnableCam()},Ie=e=>n=>(s.logger("onMoveToParticipants"),e.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,n)),Be=e=>n=>(s.logger("onMoveToSpectators"),e.onSession(s.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,n)),De=e=>n=>(s.logger("onMustStopPresentation"),e.onSession("mustStopPresentation",n)),we=e=>n=>(s.logger("onUseLicense"),e.onSession("useLicense",n)),Fe=e=>async(n,{deleteExisting:r,addMissing:o,forceRenegotiation:c,contentHint:a,simulcastEncodings:i,degradationPreference:u,sendEncodings:g}={})=>{const S=I({degradationPreference:u});return s.logger("replaceMediaStream"),e.replaceMediaStream(n,{deleteExisting:r,addMissing:o,forceRenegotiation:c,contentHint:a,sendEncodings:N({mediaStream:n,simulcastEncodings:i,sendEncodings:g}),onAddedTransceiver:S})},ke=e=>async({isEnabledCam:n,isEnabledMic:r})=>{if(e.isCallActive)return s.logger("sendMediaState"),e.sendMediaState({cam:n,mic:r})},Ue=e=>async()=>{if(e.isCallActive)return s.logger("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch(n=>{s.logger("sendRefusalToTurnOnCam: error",n)})},Le=e=>async()=>{if(e.isCallActive)return s.logger("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch(n=>{s.logger("sendRefusalToTurnOnMic: error",n)})},Ve=e=>async({mediaStream:n,isP2P:r,maxBitrate:o,contentHint:c,simulcastEncodings:a,degradationPreference:i,sendEncodings:u},g)=>{const S=I({degradationPreference:i});return s.logger("startPresentation"),e.startPresentation(n,{isP2P:r,maxBitrate:o,contentHint:c,sendEncodings:N({mediaStream:n,simulcastEncodings:a,sendEncodings:u}),onAddedTransceiver:S},g)},xe=e=>async({isP2P:n=!1}={})=>(s.logger("stopShareSipConnector"),e.stopPresentation({isP2P:n}).catch(r=>{s.logger(r)})),$e=e=>async({mediaStream:n,isP2P:r,maxBitrate:o,contentHint:c,simulcastEncodings:a,degradationPreference:i,sendEncodings:u})=>{const g=I({degradationPreference:i});return s.logger("updatePresentation"),e.updatePresentation(n,{isP2P:r,maxBitrate:o,contentHint:c,sendEncodings:N({mediaStream:n,simulcastEncodings:a,sendEncodings:u}),onAddedTransceiver:g})},qe=e=>t=>[...t].map(r=>async()=>e(r)),Xe=async({accumulatedKeys:e,sendKey:t,canRunTask:n})=>{const o=qe(t)(e);return re.sequentPromises(o,n)},je=e=>n=>(s.logger("onStartMainCam"),e.onSession("admin-start-main-cam",n)),Ge=e=>n=>(s.logger("onStartMic"),e.onSession("admin-start-mic",n)),He=e=>n=>(s.logger("onStopMainCam"),e.onSession("admin-stop-main-cam",n)),We=e=>n=>(s.logger("onStopMic"),e.onSession("admin-stop-mic",n)),Ke=({sipConnector:e})=>{const t=(d,C)=>({isSyncForced:T=!1})=>{if(T){d();return}C()},n=je(e),r=He(e),o=Ge(e),c=We(e);let a=()=>{},i=()=>{},u=()=>{},g=()=>{};const S=({onStartMainCamForced:d,onStartMainCamNotForced:C,onStopMainCamForced:T,onStopMainCamNotForced:v,onStartMicForced:y,onStartMicNotForced:_,onStopMicForced:b,onStopMicNotForced:O})=>{const A=t(d,C);a=n(A);const R=t(T,v);i=r(R);const M=t(y,_);u=o(M);const B=t(b,O);g=c(B)},f=()=>{a(),i(),u(),g()};return{start:d=>{S(d)},stop:()=>{f()}}},Ye=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:Y,createSyncMediaState:Ke,error:ye,getExtraHeaders:_e,getUserAgent:Pe,hasPurgatory:P,resolveAnswerIncomingCall:Ce,resolveAskPermissionToEnableCam:Ne,resolveCallToServer:Ee,resolveConnectToServer:Te,resolveDisconnectFromServer:Re,resolveGetRemoteStreams:L,resolveOnMoveToParticipants:Ie,resolveOnMoveToSpectators:Be,resolveOnMustStopPresentation:De,resolveOnUseLicense:we,resolveReplaceMediaStream:Fe,resolveSendMediaState:ke,resolveSendRefusalToTurnOnCam:Ue,resolveSendRefusalToTurnOnMic:Le,resolveStartPresentation:Ve,resolveStopShareSipConnector:xe,resolveUpdatePresentation:$e,resolveUpdateRemoteStreams:V,sendDTMFAccumulated:Xe},Symbol.toStringTag,{value:"Module"})),ze=e=>[...e.keys()].map(t=>e.get(t)),Qe=(e,t)=>ze(e).find(n=>n.type===t),J=async e=>e.getStats().then(t=>{const n=Qe(t,"codec");return n==null?void 0:n.mimeType}),Je=e=>e.find(t=>{var n;return((n=t==null?void 0:t.track)==null?void 0:n.kind)==="video"}),Z=se.createStackPromises(),Ze=async()=>Z().catch(e=>{s.logger("videoSendingBalancer: error",e)}),en=async e=>(Z.add(e),Ze()),$=async({sender:e,scaleResolutionDownBy:t,maxBitrate:n,onSetParameters:r})=>en(async()=>s.setEncodingsToSender(e,{scaleResolutionDownBy:t,maxBitrate:n},r)),nn=async({sender:e,codec:t},n)=>{const o=Se(t);return $({sender:e,maxBitrate:o,onSetParameters:n,scaleResolutionDownBy:200})},U=async({sender:e,videoTrack:t,codec:n},r)=>{const a=t.getSettings().width,i=W(a,n);return $({sender:e,maxBitrate:i,onSetParameters:r,scaleResolutionDownBy:1})},tn=async({sender:e,videoTrack:t,resolution:n,codec:r},o)=>{const[c,a]=n.split("x"),{maxBitrate:i,scaleResolutionDownBy:u}=K({videoTrack:t,codec:r,targetSize:{width:Number(c),height:Number(a)}});return $({sender:e,maxBitrate:i,onSetParameters:o,scaleResolutionDownBy:u})},rn=async({mainCam:e,resolutionMainCam:t,sender:n,videoTrack:r,codec:o},c)=>{switch(e){case s.EEventsMainCAM.PAUSE_MAIN_CAM:return nn({sender:n,codec:o},c);case s.EEventsMainCAM.RESUME_MAIN_CAM:return U({sender:n,videoTrack:r,codec:o},c);case s.EEventsMainCAM.MAX_MAIN_CAM_RESOLUTION:return t!==void 0?tn({sender:n,videoTrack:r,codec:o,resolution:t},c):U({sender:n,videoTrack:r,codec:o},c);default:return U({sender:n,videoTrack:r,codec:o},c)}},q={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},X=async({mainCam:e,resolutionMainCam:t,connection:n,onSetParameters:r,ignoreForCodec:o})=>{const c=n.getSenders(),a=Je(c);if(!(a!=null&&a.track))return q;const i=await J(a);return G(i,o)?q:rn({mainCam:e,resolutionMainCam:t,sender:a,codec:i,videoTrack:a.track},r)},sn=(e,{ignoreForCodec:t,onSetParameters:n}={})=>{const r=async()=>{const{connection:u}=e;if(!u)throw new Error("connection is not exist");return X({connection:u,onSetParameters:n,ignoreForCodec:t})};let o=r;const c=async u=>(o=async()=>{const{mainCam:g,resolutionMainCam:S}=u,{connection:f}=e;if(!f)throw new Error("connection is not exist");return X({mainCam:g,resolutionMainCam:S,connection:f,onSetParameters:n,ignoreForCodec:t})},o());return{subscribe:()=>{e.onSession("main-cam-control",c)},unsubscribe:()=>{e.offSession("main-cam-control",c)},balanceByTrack:r,resetMainCamControl(){o=r},async reBalance(){return o()}}};exports.EEventsMainCAM=s.EEventsMainCAM;exports.EEventsMic=s.EEventsMic;exports.EEventsSyncMediaState=s.EEventsSyncMediaState;exports.EUseLicense=s.EUseLicense;exports.causes=s.causes;exports.constants=s.constants;exports.default=s.SipConnector;exports.disableDebug=s.disableDebug;exports.enableDebug=s.enableDebug;exports.eventNames=s.eventNames;exports.hasCanceledCallError=s.hasCanceledCallError;exports.setParametersToSender=s.setParametersToSender;exports.debug=oe;exports.getCodecFromSender=J;exports.resolveVideoSendingBalancer=sn;exports.tools=Ye;
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import { l as a, s as te, B as H, N as W, P as se, a as re, E as k, b as oe, S as ln } from "./SipConnector-BGDcrO00.js";
2
- import { i as hn, j as Mn, k as yn, c as _n, d as vn, f as bn, g as pn, e as On, h as An } from "./SipConnector-BGDcrO00.js";
1
+ import { l as a, s as te, B as H, N as W, P as re, a as se, E as k, b as oe, S as dn } from "./SipConnector-DhuPlarI.js";
2
+ import { i as hn, j as yn, k as pn, c as vn, d as _n, f as bn, g as On, e as An, h as Pn } from "./SipConnector-DhuPlarI.js";
3
3
  import { debounce as ae } from "ts-debounce";
4
4
  import { isCanceledError as ce } from "@krivega/cancelable-promise";
5
5
  import { hasCanceledError as ie } from "repeated-calls";
6
6
  import { sequentPromises as ue } from "sequent-promises";
7
7
  import { createStackPromises as le } from "stack-promises";
8
- import { default as Nn } from "debug";
8
+ import { default as In } from "debug";
9
9
  const de = (e) => e.getVideoTracks()[0], Se = 1e6, T = (e) => e * Se, K = T(0.06), me = T(4), fe = (e) => e <= 64 ? K : e <= 128 ? T(0.12) : e <= 256 ? T(0.25) : e <= 384 ? T(0.32) : e <= 426 ? T(0.38) : e <= 640 ? T(0.5) : e <= 848 ? T(0.7) : e <= 1280 ? T(1) : e <= 1920 ? T(2) : me, Y = (e, t) => e !== void 0 && t !== void 0 && e.toLowerCase().includes(t.toLowerCase()), ge = "av1", Ce = (e) => Y(e, ge), Te = 0.6, z = (e, t) => Ce(t) ? e * Te : e, Ee = (e) => z(K, e), Q = (e, t) => {
10
10
  const n = fe(e);
11
11
  return z(n, t);
@@ -14,7 +14,7 @@ const de = (e) => e.getVideoTracks()[0], Se = 1e6, T = (e) => e * Se, K = T(0.06
14
14
  targetSize: t,
15
15
  codec: n
16
16
  }) => {
17
- const s = e.getSettings(), r = s.width, o = s.height, c = r / t.width, i = o / t.height, u = Math.max(c, i, Re), d = Q(t.width, n);
17
+ const r = e.getSettings(), s = r.width, o = r.height, c = s / t.width, i = o / t.height, u = Math.max(c, i, Re), d = Q(t.width, n);
18
18
  return { scaleResolutionDownBy: u, maxBitrate: d };
19
19
  }, N = ({
20
20
  mediaStream: e,
@@ -22,74 +22,74 @@ const de = (e) => e.getVideoTracks()[0], Se = 1e6, T = (e) => e * Se, K = T(0.06
22
22
  sendEncodings: n
23
23
  }) => {
24
24
  if (t && t.length > 0) {
25
- const s = n ?? [], r = de(e);
25
+ const r = n ?? [], s = de(e);
26
26
  return t.forEach((o, c) => {
27
- const i = s[c] ?? {}, { maxBitrate: u, scaleResolutionDownBy: d } = q({
28
- videoTrack: r,
27
+ const i = r[c] ?? {}, { maxBitrate: u, scaleResolutionDownBy: d } = q({
28
+ videoTrack: s,
29
29
  targetSize: {
30
30
  width: o.width,
31
31
  height: o.height
32
32
  }
33
33
  });
34
- i.maxBitrate = u, i.scaleResolutionDownBy = d, s[c] = i;
35
- }), s;
34
+ i.maxBitrate = u, i.scaleResolutionDownBy = d, r[c] = i;
35
+ }), r;
36
36
  }
37
37
  return n;
38
- }, J = "purgatory", P = (e) => e === J, V = (e) => () => (a("getRemoteStreams"), e.getRemoteStreams()), he = ({ kind: e, readyState: t }) => e === "video" && t === "live", Z = (e) => ({ track: t }) => {
39
- he(t) && e();
38
+ }, J = "purgatory", P = (e) => e === J, V = (e) => () => (a("getRemoteStreams"), e.getRemoteStreams()), Me = ({ kind: e, readyState: t }) => e === "video" && t === "live", Z = (e) => ({ track: t }) => {
39
+ Me(t) && e();
40
40
  }, x = ({
41
41
  getRemoteStreams: e,
42
42
  setRemoteStreams: t
43
43
  }) => ae(() => {
44
44
  const n = e();
45
45
  a("remoteStreams", n), n && t(n);
46
- }, 200), B = (e) => async (t) => {
46
+ }, 200), I = (e) => async (t) => {
47
47
  Object.keys(e).length > 0 && await te(t.sender, e);
48
- }, Me = (e) => async (n) => {
48
+ }, he = (e) => async (n) => {
49
49
  const {
50
- mediaStream: s,
51
- extraHeaders: r,
50
+ mediaStream: r,
51
+ extraHeaders: s,
52
52
  iceServers: o,
53
53
  contentHint: c,
54
54
  simulcastEncodings: i,
55
55
  degradationPreference: u,
56
56
  sendEncodings: d,
57
- setRemoteStreams: f,
57
+ setRemoteStreams: m,
58
58
  onBeforeProgressCall: g,
59
- onSuccessProgressCall: m,
60
- onEnterPurgatory: M,
59
+ onSuccessProgressCall: f,
60
+ onEnterPurgatory: h,
61
61
  onEnterConference: S,
62
62
  onFailProgressCall: C,
63
63
  onFinishProgressCall: E,
64
64
  onEndedCall: y
65
- } = n, _ = x({
66
- setRemoteStreams: f,
65
+ } = n, p = x({
66
+ setRemoteStreams: m,
67
67
  getRemoteStreams: V(e)
68
- }), v = Z(_), b = B({
68
+ }), v = Z(p), _ = I({
69
69
  degradationPreference: u
70
70
  });
71
71
  a("answerIncomingCall", n);
72
- const p = async () => e.answerToIncomingCall({
73
- mediaStream: s,
74
- extraHeaders: r,
72
+ const b = async () => e.answerToIncomingCall({
73
+ mediaStream: r,
74
+ extraHeaders: s,
75
75
  iceServers: o,
76
76
  contentHint: c,
77
77
  sendEncodings: N({
78
- mediaStream: s,
78
+ mediaStream: r,
79
79
  simulcastEncodings: i,
80
80
  sendEncodings: d
81
81
  }),
82
- onAddedTransceiver: b,
82
+ onAddedTransceiver: _,
83
83
  ontrack: v
84
84
  }), O = () => {
85
85
  const { remoteCallerData: l } = e;
86
86
  return l.incomingNumber;
87
87
  };
88
- let R = !1, h;
89
- const A = (a("subscribeEnterConference: onEnterConference", S), M ?? S ? e.onSession("enterRoom", (l) => {
90
- a("enterRoom", { _room: l, isSuccessProgressCall: R }), h = l, P(h) ? M && M() : S && S({ isSuccessProgressCall: R });
88
+ let R = !1, M;
89
+ const A = (a("subscribeEnterConference: onEnterConference", S), h ?? S ? e.onSession("enterRoom", (l) => {
90
+ a("enterRoom", { _room: l, isSuccessProgressCall: R }), M = l, P(M) ? h && h() : S && S({ isSuccessProgressCall: R });
91
91
  }) : () => {
92
- }), w = (l) => (a("onSuccess"), R = !0, _(), m && m({ isPurgatory: P(h) }), e.onceRaceSession(["ended", "failed"], () => {
92
+ }), w = (l) => (a("onSuccess"), R = !0, p(), f && f({ isPurgatory: P(M) }), e.onceRaceSession(["ended", "failed"], () => {
93
93
  A(), y && y();
94
94
  }), l), D = (l) => {
95
95
  throw a("onFail"), C && C(), A(), l;
@@ -100,112 +100,112 @@ const de = (e) => e.getVideoTracks()[0], Se = 1e6, T = (e) => e * Se, K = T(0.06
100
100
  const l = O();
101
101
  g(l);
102
102
  }
103
- return p().then(w).catch((l) => D(l)).finally(F);
103
+ return b().then(w).catch((l) => D(l)).finally(F);
104
104
  }, ye = (e) => async (n) => {
105
105
  const {
106
- conference: s,
107
- mediaStream: r,
106
+ conference: r,
107
+ mediaStream: s,
108
108
  extraHeaders: o,
109
109
  iceServers: c,
110
110
  contentHint: i,
111
111
  simulcastEncodings: u,
112
112
  degradationPreference: d,
113
- sendEncodings: f,
113
+ sendEncodings: m,
114
114
  setRemoteStreams: g,
115
- onBeforeProgressCall: m,
116
- onSuccessProgressCall: M,
115
+ onBeforeProgressCall: f,
116
+ onSuccessProgressCall: h,
117
117
  onEnterPurgatory: S,
118
118
  onEnterConference: C,
119
119
  onFailProgressCall: E,
120
120
  onFinishProgressCall: y,
121
- onEndedCall: _
121
+ onEndedCall: p
122
122
  } = n, v = x({
123
123
  setRemoteStreams: g,
124
124
  getRemoteStreams: V(e)
125
- }), b = Z(v), p = B({
125
+ }), _ = Z(v), b = I({
126
126
  degradationPreference: d
127
127
  });
128
128
  a("callToServer", n);
129
129
  const O = async () => (a("startCall"), e.call({
130
- mediaStream: r,
130
+ mediaStream: s,
131
131
  extraHeaders: o,
132
132
  iceServers: c,
133
133
  contentHint: i,
134
134
  sendEncodings: N({
135
- mediaStream: r,
135
+ mediaStream: s,
136
136
  simulcastEncodings: u,
137
- sendEncodings: f
137
+ sendEncodings: m
138
138
  }),
139
- number: s,
140
- onAddedTransceiver: p,
141
- ontrack: b
139
+ number: r,
140
+ onAddedTransceiver: b,
141
+ ontrack: _
142
142
  }));
143
- let R = !1, h;
143
+ let R = !1, M;
144
144
  const A = (a("subscribeEnterConference: onEnterConference", C), S ?? C ? e.onSession("enterRoom", ({ room: l }) => {
145
- a("enterRoom", { _room: l, isSuccessProgressCall: R }), h = l, P(h) ? S && S() : C && C({ isSuccessProgressCall: R });
145
+ a("enterRoom", { _room: l, isSuccessProgressCall: R }), M = l, P(M) ? S && S() : C && C({ isSuccessProgressCall: R });
146
146
  }) : () => {
147
- }), w = (l) => (a("onSuccess"), R = !0, v(), M && M({ isPurgatory: P(h) }), e.onceRaceSession(["ended", "failed"], () => {
148
- A(), _ && _();
147
+ }), w = (l) => (a("onSuccess"), R = !0, v(), h && h({ isPurgatory: P(M) }), e.onceRaceSession(["ended", "failed"], () => {
148
+ A(), p && p();
149
149
  }), l), D = (l) => {
150
150
  throw a("onFail"), E && E(), A(), l;
151
151
  }, F = () => {
152
152
  a("onFinish"), y && y();
153
153
  };
154
- return a("onBeforeProgressCall"), m && m(s), O().then(w).catch((l) => D(l)).finally(F);
154
+ return a("onBeforeProgressCall"), f && f(r), O().then(w).catch((l) => D(l)).finally(F);
155
155
  }, U = (e) => {
156
156
  if (!ce(e) && !ie(e))
157
157
  throw e;
158
158
  return { isSuccessful: !1 };
159
- }, _e = (e) => async (n) => {
159
+ }, pe = (e) => async (n) => {
160
160
  const {
161
- userAgent: s,
162
- sipWebSocketServerURL: r,
161
+ userAgent: r,
162
+ sipWebSocketServerURL: s,
163
163
  sipServerUrl: o,
164
164
  remoteAddress: c,
165
165
  displayName: i,
166
166
  name: u,
167
167
  password: d,
168
- isRegisteredUser: f,
168
+ isRegisteredUser: m,
169
169
  isDisconnectOnFail: g
170
170
  } = n;
171
171
  return a("connectToServer", n), e.connect({
172
- userAgent: s,
173
- sipWebSocketServerURL: r,
172
+ userAgent: r,
173
+ sipWebSocketServerURL: s,
174
174
  sipServerUrl: o,
175
175
  remoteAddress: c,
176
176
  displayName: i,
177
177
  password: d,
178
178
  user: u,
179
- register: f
180
- }).then((m) => (a("connectToServer then"), { ua: m, isSuccessful: !0 })).catch(async (m) => (a("connectToServer catch: error", m), g === !0 ? e.disconnect().then(() => U(m)).catch(() => U(m)) : U(m)));
179
+ register: m
180
+ }).then((f) => (a("connectToServer then"), { ua: f, isSuccessful: !0 })).catch(async (f) => (a("connectToServer catch: error", f), g === !0 ? e.disconnect().then(() => U(f)).catch(() => U(f)) : U(f)));
181
181
  }, ve = (e) => async () => (a("disconnectFromServer"), e.disconnect().then(() => (a("disconnectFromServer: then"), { isSuccessful: !0 })).catch((t) => (a("disconnectFromServer: catch", t), { isSuccessful: !1 }))), $ = (e) => {
182
182
  const { url: t, cause: n } = e;
183
- let s = t;
184
- return (n === H || n === W) && (s = `${e.message.to.uri.user}@${e.message.to.uri.host}`), s;
183
+ let r = t;
184
+ return (n === H || n === W) && (r = `${e.message.to.uri.user}@${e.message.to.uri.host}`), r;
185
185
  };
186
186
  var ee = /* @__PURE__ */ ((e) => (e.CONNECT_SERVER_FAILED = "CONNECT_SERVER_FAILED", e.WRONG_USER_OR_PASSWORD = "WRONG_USER_OR_PASSWORD", e.BAD_MEDIA_ERROR = "BAD_MEDIA_ERROR", e.NOT_FOUND_ERROR = "NOT_FOUND_ERROR", e.WS_CONNECTION_FAILED = "WS_CONNECTION_FAILED", e.CONNECT_SERVER_FAILED_BY_LINK = "CONNECT_SERVER_FAILED_BY_LINK", e))(ee || {});
187
- const be = (e = new Error()) => {
188
- var r;
187
+ const _e = (e = new Error()) => {
188
+ var s;
189
189
  const { cause: t, socket: n } = e;
190
- let s = "CONNECT_SERVER_FAILED";
190
+ let r = "CONNECT_SERVER_FAILED";
191
191
  switch (t) {
192
192
  case "Forbidden": {
193
- s = "WRONG_USER_OR_PASSWORD";
193
+ r = "WRONG_USER_OR_PASSWORD";
194
194
  break;
195
195
  }
196
196
  case H: {
197
- s = "BAD_MEDIA_ERROR";
197
+ r = "BAD_MEDIA_ERROR";
198
198
  break;
199
199
  }
200
200
  case W: {
201
- s = "NOT_FOUND_ERROR";
201
+ r = "NOT_FOUND_ERROR";
202
202
  break;
203
203
  }
204
204
  default:
205
- n && ((r = n == null ? void 0 : n._ws) == null ? void 0 : r.readyState) === 3 ? s = "WS_CONNECTION_FAILED" : $(e) && (s = "CONNECT_SERVER_FAILED_BY_LINK");
205
+ n && ((s = n == null ? void 0 : n._ws) == null ? void 0 : s.readyState) === 3 ? r = "WS_CONNECTION_FAILED" : $(e) && (r = "CONNECT_SERVER_FAILED_BY_LINK");
206
206
  }
207
- return s;
208
- }, pe = (e) => {
207
+ return r;
208
+ }, be = (e) => {
209
209
  let t = "";
210
210
  try {
211
211
  t = JSON.stringify(e);
@@ -214,106 +214,130 @@ const be = (e = new Error()) => {
214
214
  }
215
215
  return t;
216
216
  }, Oe = (e = new Error()) => {
217
- const { code: t, cause: n, message: s } = e, r = $(e), o = { code: "", cause: "", message: "" };
218
- return typeof s == "object" && s !== null ? o.message = pe(s) : s && (o.message = String(s)), r && (o.link = r), t && (o.code = t), n && (o.cause = n), o;
217
+ const { code: t, cause: n, message: r } = e, s = $(e), o = { code: "", cause: "", message: "" };
218
+ return typeof r == "object" && r !== null ? o.message = be(r) : r && (o.message = String(r)), s && (o.link = s), t && (o.code = t), n && (o.cause = n), o;
219
219
  }, Ae = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
220
220
  __proto__: null,
221
221
  EErrorTypes: ee,
222
222
  getLinkError: $,
223
- getTypeFromError: be,
223
+ getTypeFromError: _e,
224
224
  getValuesFromError: Oe
225
225
  }, Symbol.toStringTag, { value: "Module" })), Pe = ({
226
226
  sessionId: e,
227
227
  remoteAddress: t,
228
228
  isMutedAudio: n,
229
- isMutedVideo: s,
230
- isRegistered: r,
229
+ isMutedVideo: r,
230
+ isRegistered: s,
231
231
  isPresentationCall: o
232
232
  }) => {
233
- const c = [], i = n ? "0" : "1", u = s ? "0" : "1";
234
- return c.push(`X-Vinteo-Mic-State: ${i}`, `X-Vinteo-MainCam-State: ${u}`), r || c.push("X-Vinteo-Purgatory-Call: yes"), e && c.push(`X-Vinteo-Session: ${e}`), o && c.push("X-Vinteo-Presentation-Call: yes"), t && c.push(`X-Vinteo-Remote: ${t}`), c;
235
- }, Ne = "[@*!|]", Be = "_", Ie = (e) => {
233
+ const c = [], i = n ? "0" : "1", u = r ? "0" : "1";
234
+ return c.push(`X-Vinteo-Mic-State: ${i}`, `X-Vinteo-MainCam-State: ${u}`), s || c.push("X-Vinteo-Purgatory-Call: yes"), e && c.push(`X-Vinteo-Session: ${e}`), o && c.push("X-Vinteo-Presentation-Call: yes"), t && c.push(`X-Vinteo-Remote: ${t}`), c;
235
+ }, Ne = "[@*!|]", Ie = "_", Be = (e) => {
236
236
  let t = e;
237
- return t = t.replaceAll(new RegExp(Ne, "g"), Be), t;
237
+ return t = t.replaceAll(new RegExp(Ne, "g"), Ie), t;
238
238
  }, we = ({
239
239
  appName: e,
240
240
  appVersion: t,
241
241
  browserName: n,
242
- browserVersion: s
242
+ browserVersion: r
243
243
  }) => {
244
- const o = `${Ie(e)} ${t}`;
245
- return `ChromeNew - ${n ? `${n} ${s}, ${o}` : o}`;
244
+ const o = `${Be(e)} ${t}`;
245
+ return `ChromeNew - ${n ? `${n} ${r}, ${o}` : o}`;
246
246
  }, De = ({
247
247
  isUnifiedSdpSemantic: e,
248
248
  appVersion: t,
249
249
  browserName: n,
250
- browserVersion: s,
251
- appName: r
252
- }) => e ? we({ appVersion: t, browserName: n, browserVersion: s, appName: r }) : "Chrome", Fe = (e) => async () => {
250
+ browserVersion: r,
251
+ appName: s
252
+ }) => e ? we({ appVersion: t, browserName: n, browserVersion: r, appName: s }) : "Chrome", Fe = (e) => async () => {
253
253
  if (e.isCallActive)
254
254
  return a("askPermissionToEnableCam"), e.askPermissionToEnableCam();
255
- }, ke = (e) => (n) => (a("onMustStopPresentation"), e.onSession("mustStopPresentation", n)), Ue = (e) => (n) => (a("onMoveToSpectators"), e.onSession(se, n)), Le = (e) => (n) => (a("onMoveToParticipants"), e.onSession(re, n)), Ve = (e) => (n) => (a("onUseLicense"), e.onSession("useLicense", n)), xe = (e) => async ({
255
+ }, ke = (e) => (n) => (a("onMoveToParticipants"), e.onSession(re, n)), Ue = (e) => (n) => (a("onMoveToSpectators"), e.onSession(se, n)), Le = (e) => (n) => (a("onMustStopPresentation"), e.onSession("mustStopPresentation", n)), Ve = (e) => (n) => (a("onUseLicense"), e.onSession("useLicense", n)), xe = (e) => async (n, {
256
+ deleteExisting: r,
257
+ addMissing: s,
258
+ forceRenegotiation: o,
259
+ contentHint: c,
260
+ simulcastEncodings: i,
261
+ degradationPreference: u,
262
+ sendEncodings: d
263
+ } = {}) => {
264
+ const m = I({
265
+ degradationPreference: u
266
+ });
267
+ return a("replaceMediaStream"), e.replaceMediaStream(n, {
268
+ deleteExisting: r,
269
+ addMissing: s,
270
+ forceRenegotiation: o,
271
+ contentHint: c,
272
+ sendEncodings: N({
273
+ mediaStream: n,
274
+ simulcastEncodings: i,
275
+ sendEncodings: d
276
+ }),
277
+ onAddedTransceiver: m
278
+ });
279
+ }, $e = (e) => async ({
256
280
  isEnabledCam: n,
257
- isEnabledMic: s
281
+ isEnabledMic: r
258
282
  }) => {
259
283
  if (e.isCallActive)
260
- return a("sendMediaState"), e.sendMediaState({ cam: n, mic: s });
261
- }, $e = (e) => async () => {
284
+ return a("sendMediaState"), e.sendMediaState({ cam: n, mic: r });
285
+ }, Xe = (e) => async () => {
262
286
  if (e.isCallActive)
263
287
  return a("sendRefusalToTurnOnCam"), e.sendRefusalToTurnOnCam().catch((n) => {
264
288
  a("sendRefusalToTurnOnCam: error", n);
265
289
  });
266
- }, Xe = (e) => async () => {
290
+ }, je = (e) => async () => {
267
291
  if (e.isCallActive)
268
292
  return a("sendRefusalToTurnOnMic"), e.sendRefusalToTurnOnMic().catch((n) => {
269
293
  a("sendRefusalToTurnOnMic: error", n);
270
294
  });
271
- }, je = (e) => async ({
295
+ }, Ge = (e) => async ({
272
296
  mediaStream: n,
273
- isP2P: s,
274
- maxBitrate: r,
297
+ isP2P: r,
298
+ maxBitrate: s,
275
299
  contentHint: o,
276
300
  simulcastEncodings: c,
277
301
  degradationPreference: i,
278
302
  sendEncodings: u
279
303
  }, d) => {
280
- const f = B({
304
+ const m = I({
281
305
  degradationPreference: i
282
306
  });
283
307
  return a("startPresentation"), e.startPresentation(
284
308
  n,
285
309
  {
286
- isP2P: s,
287
- maxBitrate: r,
310
+ isP2P: r,
311
+ maxBitrate: s,
288
312
  contentHint: o,
289
313
  sendEncodings: N({
290
314
  mediaStream: n,
291
315
  simulcastEncodings: c,
292
316
  sendEncodings: u
293
317
  }),
294
- onAddedTransceiver: f
318
+ onAddedTransceiver: m
295
319
  },
296
320
  d
297
321
  );
298
- }, Ge = (e) => async ({ isP2P: n = !1 } = {}) => (a("stopShareSipConnector"), e.stopPresentation({
322
+ }, He = (e) => async ({ isP2P: n = !1 } = {}) => (a("stopShareSipConnector"), e.stopPresentation({
299
323
  isP2P: n
300
- }).catch((s) => {
301
- a(s);
302
- })), He = (e) => async ({
324
+ }).catch((r) => {
325
+ a(r);
326
+ })), We = (e) => async ({
303
327
  mediaStream: n,
304
- isP2P: s,
305
- maxBitrate: r,
328
+ isP2P: r,
329
+ maxBitrate: s,
306
330
  contentHint: o,
307
331
  simulcastEncodings: c,
308
332
  degradationPreference: i,
309
333
  sendEncodings: u
310
334
  }) => {
311
- const d = B({
335
+ const d = I({
312
336
  degradationPreference: i
313
337
  });
314
338
  return a("updatePresentation"), e.updatePresentation(n, {
315
- isP2P: s,
316
- maxBitrate: r,
339
+ isP2P: r,
340
+ maxBitrate: s,
317
341
  contentHint: o,
318
342
  sendEncodings: N({
319
343
  mediaStream: n,
@@ -322,35 +346,35 @@ const be = (e = new Error()) => {
322
346
  }),
323
347
  onAddedTransceiver: d
324
348
  });
325
- }, We = (e) => (t) => [...t].map((s) => async () => e(s)), Ke = async ({
349
+ }, Ke = (e) => (t) => [...t].map((r) => async () => e(r)), Ye = async ({
326
350
  accumulatedKeys: e,
327
351
  sendKey: t,
328
352
  canRunTask: n
329
353
  }) => {
330
- const r = We(t)(e);
331
- return ue(r, n);
332
- }, Ye = (e) => (n) => (a("onStartMainCam"), e.onSession("admin-start-main-cam", n)), ze = (e) => (n) => (a("onStartMic"), e.onSession("admin-start-mic", n)), Qe = (e) => (n) => (a("onStopMainCam"), e.onSession("admin-stop-main-cam", n)), qe = (e) => (n) => (a("onStopMic"), e.onSession("admin-stop-mic", n)), Je = ({ sipConnector: e }) => {
354
+ const s = Ke(t)(e);
355
+ return ue(s, n);
356
+ }, ze = (e) => (n) => (a("onStartMainCam"), e.onSession("admin-start-main-cam", n)), Qe = (e) => (n) => (a("onStartMic"), e.onSession("admin-start-mic", n)), qe = (e) => (n) => (a("onStopMainCam"), e.onSession("admin-stop-main-cam", n)), Je = (e) => (n) => (a("onStopMic"), e.onSession("admin-stop-mic", n)), Ze = ({ sipConnector: e }) => {
333
357
  const t = (S, C) => ({ isSyncForced: E = !1 }) => {
334
358
  if (E) {
335
359
  S();
336
360
  return;
337
361
  }
338
362
  C();
339
- }, n = Ye(e), s = Qe(e), r = ze(e), o = qe(e);
363
+ }, n = ze(e), r = qe(e), s = Qe(e), o = Je(e);
340
364
  let c = () => {
341
365
  }, i = () => {
342
366
  }, u = () => {
343
367
  }, d = () => {
344
368
  };
345
- const f = ({
369
+ const m = ({
346
370
  onStartMainCamForced: S,
347
371
  onStartMainCamNotForced: C,
348
372
  onStopMainCamForced: E,
349
373
  onStopMainCamNotForced: y,
350
- onStartMicForced: _,
374
+ onStartMicForced: p,
351
375
  onStartMicNotForced: v,
352
- onStopMicForced: b,
353
- onStopMicNotForced: p
376
+ onStopMicForced: _,
377
+ onStopMicNotForced: b
354
378
  }) => {
355
379
  const O = t(
356
380
  S,
@@ -361,66 +385,67 @@ const be = (e = new Error()) => {
361
385
  E,
362
386
  y
363
387
  );
364
- i = s(R);
365
- const h = t(_, v);
366
- u = r(h);
367
- const I = t(b, p);
368
- d = o(I);
388
+ i = r(R);
389
+ const M = t(p, v);
390
+ u = s(M);
391
+ const B = t(_, b);
392
+ d = o(B);
369
393
  }, g = () => {
370
394
  c(), i(), u(), d();
371
395
  };
372
396
  return {
373
397
  start: (S) => {
374
- f(S);
398
+ m(S);
375
399
  },
376
400
  stop: () => {
377
401
  g();
378
402
  }
379
403
  };
380
- }, Cn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
404
+ }, Tn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
381
405
  __proto__: null,
382
406
  PURGATORY_CONFERENCE_NUMBER: J,
383
- createSyncMediaState: Je,
407
+ createSyncMediaState: Ze,
384
408
  error: Ae,
385
409
  getExtraHeaders: Pe,
386
410
  getUserAgent: De,
387
411
  hasPurgatory: P,
388
- resolveAnswerIncomingCall: Me,
412
+ resolveAnswerIncomingCall: he,
389
413
  resolveAskPermissionToEnableCam: Fe,
390
414
  resolveCallToServer: ye,
391
- resolveConnectToServer: _e,
415
+ resolveConnectToServer: pe,
392
416
  resolveDisconnectFromServer: ve,
393
417
  resolveGetRemoteStreams: V,
394
- resolveOnMoveToParticipants: Le,
418
+ resolveOnMoveToParticipants: ke,
395
419
  resolveOnMoveToSpectators: Ue,
396
- resolveOnMustStopPresentation: ke,
420
+ resolveOnMustStopPresentation: Le,
397
421
  resolveOnUseLicense: Ve,
398
- resolveSendMediaState: xe,
399
- resolveSendRefusalToTurnOnCam: $e,
400
- resolveSendRefusalToTurnOnMic: Xe,
401
- resolveStartPresentation: je,
402
- resolveStopShareSipConnector: Ge,
403
- resolveUpdatePresentation: He,
422
+ resolveReplaceMediaStream: xe,
423
+ resolveSendMediaState: $e,
424
+ resolveSendRefusalToTurnOnCam: Xe,
425
+ resolveSendRefusalToTurnOnMic: je,
426
+ resolveStartPresentation: Ge,
427
+ resolveStopShareSipConnector: He,
428
+ resolveUpdatePresentation: We,
404
429
  resolveUpdateRemoteStreams: x,
405
- sendDTMFAccumulated: Ke
406
- }, Symbol.toStringTag, { value: "Module" })), Ze = (e) => [...e.keys()].map((t) => e.get(t)), en = (e, t) => Ze(e).find((n) => n.type === t), nn = async (e) => e.getStats().then((t) => {
407
- const n = en(t, "codec");
430
+ sendDTMFAccumulated: Ye
431
+ }, Symbol.toStringTag, { value: "Module" })), en = (e) => [...e.keys()].map((t) => e.get(t)), nn = (e, t) => en(e).find((n) => n.type === t), tn = async (e) => e.getStats().then((t) => {
432
+ const n = nn(t, "codec");
408
433
  return n == null ? void 0 : n.mimeType;
409
- }), tn = (e) => e.find((t) => {
434
+ }), rn = (e) => e.find((t) => {
410
435
  var n;
411
436
  return ((n = t == null ? void 0 : t.track) == null ? void 0 : n.kind) === "video";
412
437
  }), ne = le(), sn = async () => ne().catch((e) => {
413
438
  a("videoSendingBalancer: error", e);
414
- }), rn = async (e) => (ne.add(e), sn()), X = async ({
439
+ }), on = async (e) => (ne.add(e), sn()), X = async ({
415
440
  sender: e,
416
441
  scaleResolutionDownBy: t,
417
442
  maxBitrate: n,
418
- onSetParameters: s
419
- }) => rn(async () => oe(e, { scaleResolutionDownBy: t, maxBitrate: n }, s)), on = async ({ sender: e, codec: t }, n) => {
420
- const r = Ee(t);
443
+ onSetParameters: r
444
+ }) => on(async () => oe(e, { scaleResolutionDownBy: t, maxBitrate: n }, r)), an = async ({ sender: e, codec: t }, n) => {
445
+ const s = Ee(t);
421
446
  return X({
422
447
  sender: e,
423
- maxBitrate: r,
448
+ maxBitrate: s,
424
449
  onSetParameters: n,
425
450
  scaleResolutionDownBy: 200
426
451
  });
@@ -428,23 +453,23 @@ const be = (e = new Error()) => {
428
453
  sender: e,
429
454
  videoTrack: t,
430
455
  codec: n
431
- }, s) => {
456
+ }, r) => {
432
457
  const c = t.getSettings().width, i = Q(c, n);
433
458
  return X({
434
459
  sender: e,
435
460
  maxBitrate: i,
436
- onSetParameters: s,
461
+ onSetParameters: r,
437
462
  scaleResolutionDownBy: 1
438
463
  });
439
- }, an = async ({
464
+ }, cn = async ({
440
465
  sender: e,
441
466
  videoTrack: t,
442
467
  resolution: n,
443
- codec: s
444
- }, r) => {
468
+ codec: r
469
+ }, s) => {
445
470
  const [o, c] = n.split("x"), { maxBitrate: i, scaleResolutionDownBy: u } = q({
446
471
  videoTrack: t,
447
- codec: s,
472
+ codec: r,
448
473
  targetSize: {
449
474
  width: Number(o),
450
475
  height: Number(c)
@@ -453,28 +478,28 @@ const be = (e = new Error()) => {
453
478
  return X({
454
479
  sender: e,
455
480
  maxBitrate: i,
456
- onSetParameters: r,
481
+ onSetParameters: s,
457
482
  scaleResolutionDownBy: u
458
483
  });
459
- }, cn = async ({
484
+ }, un = async ({
460
485
  mainCam: e,
461
486
  resolutionMainCam: t,
462
487
  sender: n,
463
- videoTrack: s,
464
- codec: r
488
+ videoTrack: r,
489
+ codec: s
465
490
  }, o) => {
466
491
  switch (e) {
467
492
  case k.PAUSE_MAIN_CAM:
468
- return on({ sender: n, codec: r }, o);
493
+ return an({ sender: n, codec: s }, o);
469
494
  case k.RESUME_MAIN_CAM:
470
- return L({ sender: n, videoTrack: s, codec: r }, o);
495
+ return L({ sender: n, videoTrack: r, codec: s }, o);
471
496
  case k.MAX_MAIN_CAM_RESOLUTION:
472
- return t !== void 0 ? an(
473
- { sender: n, videoTrack: s, codec: r, resolution: t },
497
+ return t !== void 0 ? cn(
498
+ { sender: n, videoTrack: r, codec: s, resolution: t },
474
499
  o
475
- ) : L({ sender: n, videoTrack: s, codec: r }, o);
500
+ ) : L({ sender: n, videoTrack: r, codec: s }, o);
476
501
  default:
477
- return L({ sender: n, videoTrack: s, codec: r }, o);
502
+ return L({ sender: n, videoTrack: r, codec: s }, o);
478
503
  }
479
504
  }, j = {
480
505
  isChanged: !1,
@@ -489,14 +514,14 @@ const be = (e = new Error()) => {
489
514
  mainCam: e,
490
515
  resolutionMainCam: t,
491
516
  connection: n,
492
- onSetParameters: s,
493
- ignoreForCodec: r
517
+ onSetParameters: r,
518
+ ignoreForCodec: s
494
519
  }) => {
495
- const o = n.getSenders(), c = tn(o);
520
+ const o = n.getSenders(), c = rn(o);
496
521
  if (!(c != null && c.track))
497
522
  return j;
498
- const i = await nn(c);
499
- return Y(i, r) ? j : cn(
523
+ const i = await tn(c);
524
+ return Y(i, s) ? j : un(
500
525
  {
501
526
  mainCam: e,
502
527
  resolutionMainCam: t,
@@ -504,13 +529,13 @@ const be = (e = new Error()) => {
504
529
  codec: i,
505
530
  videoTrack: c.track
506
531
  },
507
- s
532
+ r
508
533
  );
509
- }, Tn = (e, {
534
+ }, En = (e, {
510
535
  ignoreForCodec: t,
511
536
  onSetParameters: n
512
537
  } = {}) => {
513
- const s = async () => {
538
+ const r = async () => {
514
539
  const { connection: u } = e;
515
540
  if (!u)
516
541
  throw new Error("connection is not exist");
@@ -520,19 +545,19 @@ const be = (e = new Error()) => {
520
545
  ignoreForCodec: t
521
546
  });
522
547
  };
523
- let r = s;
524
- const o = async (u) => (r = async () => {
525
- const { mainCam: d, resolutionMainCam: f } = u, { connection: g } = e;
548
+ let s = r;
549
+ const o = async (u) => (s = async () => {
550
+ const { mainCam: d, resolutionMainCam: m } = u, { connection: g } = e;
526
551
  if (!g)
527
552
  throw new Error("connection is not exist");
528
553
  return G({
529
554
  mainCam: d,
530
- resolutionMainCam: f,
555
+ resolutionMainCam: m,
531
556
  connection: g,
532
557
  onSetParameters: n,
533
558
  ignoreForCodec: t
534
559
  });
535
- }, r());
560
+ }, s());
536
561
  return {
537
562
  subscribe: () => {
538
563
  e.onSession("main-cam-control", o);
@@ -540,30 +565,30 @@ const be = (e = new Error()) => {
540
565
  unsubscribe: () => {
541
566
  e.offSession("main-cam-control", o);
542
567
  },
543
- balanceByTrack: s,
568
+ balanceByTrack: r,
544
569
  resetMainCamControl() {
545
- r = s;
570
+ s = r;
546
571
  },
547
572
  async reBalance() {
548
- return r();
573
+ return s();
549
574
  }
550
575
  };
551
576
  };
552
577
  export {
553
578
  k as EEventsMainCAM,
554
579
  hn as EEventsMic,
555
- Mn as EEventsSyncMediaState,
556
- yn as EUseLicense,
557
- _n as causes,
558
- vn as constants,
559
- Nn as debug,
560
- ln as default,
580
+ yn as EEventsSyncMediaState,
581
+ pn as EUseLicense,
582
+ vn as causes,
583
+ _n as constants,
584
+ In as debug,
585
+ dn as default,
561
586
  bn as disableDebug,
562
- pn as enableDebug,
563
- On as eventNames,
564
- nn as getCodecFromSender,
565
- An as hasCanceledCallError,
566
- Tn as resolveVideoSendingBalancer,
587
+ On as enableDebug,
588
+ An as eventNames,
589
+ tn as getCodecFromSender,
590
+ Pn as hasCanceledCallError,
591
+ En as resolveVideoSendingBalancer,
567
592
  te as setParametersToSender,
568
- Cn as tools
593
+ Tn as tools
569
594
  };
@@ -8,10 +8,11 @@ export { default as getUserAgent } from './getUserAgent';
8
8
  export { PURGATORY_CONFERENCE_NUMBER, default as hasPurgatory } from './hasPurgatory';
9
9
  export { default as resolveAskPermissionToEnableCam } from './resolveAskPermissionToEnableCam';
10
10
  export { default as resolveGetRemoteStreams } from './resolveGetRemoteStreams';
11
- export { default as resolveOnMustStopPresentation } from './resolveOnMustStopPresentation';
12
- export { default as resolveOnMoveToSpectators } from './resolveOnMoveToSpectators';
13
11
  export { default as resolveOnMoveToParticipants } from './resolveOnMoveToParticipants';
12
+ export { default as resolveOnMoveToSpectators } from './resolveOnMoveToSpectators';
13
+ export { default as resolveOnMustStopPresentation } from './resolveOnMustStopPresentation';
14
14
  export { default as resolveOnUseLicense } from './resolveOnUseLicense';
15
+ export { default as resolveReplaceMediaStream } from './resolveReplaceMediaStream';
15
16
  export { default as resolveSendMediaState } from './resolveSendMediaState';
16
17
  export { default as resolveSendRefusalToTurnOnCam } from './resolveSendRefusalToTurnOnCam';
17
18
  export { default as resolveSendRefusalToTurnOnMic } from './resolveSendRefusalToTurnOnMic';
@@ -0,0 +1,12 @@
1
+ import { default as SipConnector } from '../SipConnector';
2
+ import { TContentHint, TSimulcastEncodings } from '../types';
3
+ declare const resolveReplaceMediaStream: (sipConnector: SipConnector) => (mediaStream: MediaStream, { deleteExisting, addMissing, forceRenegotiation, contentHint, simulcastEncodings, degradationPreference, sendEncodings, }?: {
4
+ deleteExisting?: boolean;
5
+ addMissing?: boolean;
6
+ forceRenegotiation?: boolean;
7
+ contentHint?: TContentHint;
8
+ simulcastEncodings?: TSimulcastEncodings;
9
+ degradationPreference?: RTCDegradationPreference;
10
+ sendEncodings?: RTCRtpEncodingParameters[];
11
+ }) => Promise<void>;
12
+ export default resolveReplaceMediaStream;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "11.3.0",
3
+ "version": "11.4.0",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",