sip-connector 6.19.0 → 6.20.1

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.
@@ -4,12 +4,8 @@ import type { IncomingInfoEvent, OutgoingInfoEvent } from '@krivega/jssip/lib/RT
4
4
  import type { IncomingRequest } from '@krivega/jssip/lib/SIPMessage';
5
5
  import type { IncomingRTCSessionEvent, RegisteredEvent, UnRegisteredEvent } from '@krivega/jssip/lib/UA';
6
6
  import type { TEventSession, TEventUA } from './eventNames';
7
- import type { TCustomError } from './types';
7
+ import type { TCustomError, TJsSIP } from './types';
8
8
  export declare const hasCanceledCallError: (error?: TCustomError) => boolean;
9
- export type TJsSIP = {
10
- UA: typeof UA;
11
- WebSocketInterface: typeof WebSocketInterface;
12
- };
13
9
  type TChannels = {
14
10
  inputChannels: string;
15
11
  outputChannels: string;
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var $n=Object.defineProperty;var Ln=(e,t,n)=>t in e?$n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var c=(e,t,n)=>(Ln(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const O=require("@krivega/cancelable-promise"),we=require("events-constructor"),J=require("debug"),Un=require("sequent-promises"),Fn=require("stack-promises"),kn="Connection Error",dt="Request Timeout",Bn="SIP Failure Code",Hn="Internal Error",xn="Busy",Et="Rejected",Wn="Redirected",qn="Unavailable",Ce="Not Found",Vn="Address Incomplete",jn="Incompatible SDP",Gn="Missing SDP",Yn="Authentication Error",ht="Terminated",Xn="WebRTC Error",ft="Canceled",zn="No Answer",Jn="Expires",Kn="No ACK",Qn="Dialog Error",Zn="User Denied Media Access",me="Bad Media Description",er="RTP Timeout",tr=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:Vn,AUTHENTICATION_ERROR:Yn,BAD_MEDIA_DESCRIPTION:me,BUSY:xn,BYE:ht,CANCELED:ft,CONNECTION_ERROR:kn,DIALOG_ERROR:Qn,EXPIRES:Jn,INCOMPATIBLE_SDP:jn,INTERNAL_ERROR:Hn,MISSING_SDP:Gn,NOT_FOUND:Ce,NO_ACK:Kn,NO_ANSWER:zn,REDIRECTED:Wn,REJECTED:Et,REQUEST_TIMEOUT:dt,RTP_TIMEOUT:er,SIP_FAILURE_CODE:Bn,UNAVAILABLE:qn,USER_DENIED_MEDIA_ACCESS:Zn,WEBRTC_ERROR:Xn},Symbol.toStringTag,{value:"Module"})),St="incomingCall",gt="declinedIncomingCall",Tt="failedIncomingCall",Ct="terminatedIncomingCall",Re="connecting",ce="connected",w="disconnected",ue="newRTCSession",x="registered",mt="unregistered",W="registrationFailed",nr="newMessage",Rt="sipEvent",Nt="availableSecondRemoteStream",vt="notAvailableSecondRemoteStream",At="mustStopPresentation",le="shareState",pt="enterRoom",bt="useLicense",yt="peerconnection:confirmed",It="peerconnection:ontrack",_e="channels",Ot="channels:notify",Mt="ended:fromserver",Pt="main-cam-control",Dt="admin-stop-main-cam",wt="admin-start-main-cam",$t="admin-stop-mic",Lt="admin-start-mic",de="admin-force-sync-media-state",Ut="participant:added-to-list-moderators",Ft="participant:removed-from-list-moderators",kt="participant:move-request-to-conference",Bt="participant:move-request-to-stream",Ht="participant:canceling-word-request",xt="webcast:started",Wt="webcast:stopped",qt="account:changed",Vt="account:deleted",jt="conference:participant-token-issued",q="ended",rr="sending",sr="reinvite",or="replaces",ir="refer",ar="progress",cr="accepted",Ee="confirmed",he="peerconnection",U="failed",ur="muted",lr="unmuted",Gt="newDTMF",Yt="newInfo",_r="hold",dr="unhold",Er="update",hr="sdp",fr="icecandidate",Sr="getusermediafailed",gr="peerconnection:createofferfailed",Tr="peerconnection:createanswerfailed",Cr="peerconnection:setlocaldescriptionfailed",mr="peerconnection:setremotedescriptionfailed",Rr="presentation:start",Nr="presentation:started",vr="presentation:end",Xt="presentation:ended",fe="presentation:failed",zt=[St,gt,Ct,Tt,Ht,Bt,kt,Ot,jt,qt,Vt,xt,Wt,Ut,Ft],Ne=[Re,ce,w,ue,x,mt,W,nr,Rt],Jt=[Nt,vt,At,le,pt,bt,yt,It,_e,Mt,Pt,wt,Dt,$t,Lt,de],ve=[q,Re,rr,sr,or,ir,ar,cr,Ee,he,U,ur,lr,Gt,Yt,_r,dr,Er,hr,fr,Sr,gr,Tr,Cr,mr,Rr,Nr,vr,Xt,fe],Kt=[...Ne,...zt],Qt=[...ve,...Jt],Ar=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:Qt,SESSION_JSSIP_EVENT_NAMES:ve,SESSION_SYNTHETICS_EVENT_NAMES:Jt,UA_EVENT_NAMES:Kt,UA_JSSIP_EVENT_NAMES:Ne,UA_SYNTHETICS_EVENT_NAMES:zt},Symbol.toStringTag,{value:"Module"})),pr=e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t},br="content-type",yr="x-webrtc-enter-room",te="application/vinteo.webrtc.sharedesktop",Ir="application/vinteo.webrtc.roomname",Or="application/vinteo.webrtc.channels",Mr="application/vinteo.webrtc.mediastate",Pr="application/vinteo.webrtc.refusal",$e="application/vinteo.webrtc.maincam",Dr="application/vinteo.webrtc.mic",wr="application/vinteo.webrtc.uselic",$r="X-WEBRTC-USE-LICENSE",Le="X-WEBRTC-INPUT-CHANNELS",Ue="X-WEBRTC-OUTPUT-CHANNELS",Lr="X-WEBRTC-MAINCAM",Ur="X-WEBRTC-MIC",Fe="X-WEBRTC-SYNC",Fr="X-WEBRTC-MAINCAM-RESOLUTION",kr="X-WEBRTC-MEDIA-STATE",Br="X-Vinteo-Media-Type",Hr="X-Vinteo-MainCam-State",xr="X-Vinteo-Mic-State",Wr="application/vinteo.webrtc.notify",qr="X-VINTEO-NOTIFY",k="x-webrtc-share-state",Vr=`${k}: LETMESTARTPRESENTATION`,jr=`${k}: STOPPRESENTATION`,Zt="YOUCANRECEIVECONTENT",en="CONTENTEND",Gr="YOUMUSTSTOPSENDCONTENT",Yr=`${k}: ${Zt}`,Xr=`${k}: ${en}`,zr="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Jr=`${zr}: LETMESTARTMAINCAM`,Ae="sip-connector",_=J(Ae),Kr=()=>{J.enable(`${Ae}`)},Qr=()=>{J.enable(`-${Ae}`)};var M=(e=>(e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",e))(M||{}),V=(e=>(e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC",e))(V||{}),j=(e=>(e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0",e))(j||{}),tn=(e=>(e.AUDIO="AUDIO",e.VIDEO="VIDEO",e.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",e))(tn||{});function Zr(e){return t=>`sip:${t}@${e}`}const es=(e,t)=>()=>Math.floor(Math.random()*(t-e))+e,ke=e=>e.trim().replaceAll(" ","_"),ts=es(1e5,99999999),ne=(e,{videoMode:t,audioMode:n}={})=>{if(!e||t==="recvonly"&&n==="recvonly")return;const r=n==="recvonly"?[]:e.getAudioTracks(),s=t==="recvonly"?[]:e.getVideoTracks(),o=[...r,...s],i=new MediaStream(o);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},ns=e=>e.some(n=>{const{kind:r}=n;return r==="video"}),rs="Error decline with 603",ss=e=>e.message===rs,os=(e,t)=>e.find(n=>n.track&&t.getTracks().includes(n.track)),nn=1,rn=e=>(t,n)=>n!==void 0&&t!==n||n===void 0&&t!==e,is=rn(nn),as=(e,t)=>{const n=e===void 0?void 0:Math.max(e,nn);if(n!==void 0&&is(n,t))return n},cs=rn(),us=(e,t)=>{if(cs(e,t))return e},sn=async(e,t,n)=>{const r=e.getParameters();(r.encodings===void 0||r.encodings.length===0)&&(r.encodings=[{}]);const[s]=r.encodings,o=s.scaleResolutionDownBy,i=as(t.scaleResolutionDownBy,o);let a=!1;i!==void 0&&(r.encodings[0].scaleResolutionDownBy=i,a=!0);const u=s.maxBitrate,l=us(t.maxBitrate,u);return l!==void 0&&(r.encodings[0].maxBitrate=l,a=!0),a?(n&&n(r),e.setParameters(r).then(()=>({parameters:r,isChanged:a}))):{parameters:r,isChanged:a}},ls=async(e,t,n)=>{const r=os(e,t);if(r)return sn(r,{maxBitrate:n})},_s=486,ds=487,Se="local",Be="remote",Es=(e=new Error)=>{const{originator:t,cause:n}=e;return O.isCanceledError(e)?!0:typeof n=="string"?n===dt||n===Et||t===Se&&(n===ft||n===ht):!1},D="SipConnector",hs="channels",fs="WebcastStarted",Ss="WebcastStopped",gs="accountChanged",Ts="accountDeleted",Cs="addedToListModerators",ms="removedFromListModerators",Rs="WebcastParticipationAccepted",Ns="WebcastParticipationRejected",vs="ParticipantMovedToWebcast",As="ConferenceParticipantTokenIssued";class ps{constructor({JsSIP:t}){c(this,"_isRegisterConfig",!1);c(this,"_connectionConfiguration",{});c(this,"_remoteStreams",{});c(this,"JsSIP");c(this,"_sessionEvents");c(this,"_uaEvents");c(this,"_cancelableConnect");c(this,"_cancelableCreateUa");c(this,"_cancelableDisconnect");c(this,"_cancelableSet");c(this,"_cancelableCall");c(this,"_cancelableAnswer");c(this,"_cancelableSendDTMF");c(this,"getSipServerUrl",t=>t);c(this,"promisePendingStartPresentation");c(this,"promisePendingStopPresentation");c(this,"ua");c(this,"session");c(this,"incomingSession");c(this,"_streamPresentationCurrent");c(this,"socket");c(this,"connect",async t=>(this._cancelRequests(),this._cancelableConnect.request(t)));c(this,"createUa",async t=>this._cancelableCreateUa.request(t));c(this,"set",async t=>this._cancelableSet.request(t));c(this,"call",async t=>this._cancelableCall.request(t));c(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));c(this,"answerToIncomingCall",async t=>this._cancelableAnswer.request(t));c(this,"sendDTMF",async t=>this._cancelableSendDTMF.request(t));c(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));c(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(Re,void 0);try{await this.unregister()}catch(t){_("tryRegister",t)}return this.register()});c(this,"declineToIncomingCall",async({statusCode:t=ds}={})=>new Promise((n,r)=>{if(!this.isAvailableIncomingCall){r(new Error("no incomingSession"));return}const s=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(gt,o),n(s.terminate({status_code:t}))}));c(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:_s}));c(this,"removeIncomingSession",()=>{delete this.incomingSession});c(this,"handleNewRTCSession",({originator:t,session:n})=>{if(t===Be){this.incomingSession=n;const r=this.remoteCallerData;n.on(U,s=>{this.removeIncomingSession(),s.originator===Se?this._uaEvents.trigger(Ct,r):this._uaEvents.trigger(Tt,r)}),this._uaEvents.trigger(St,r)}});c(this,"_connect",async t=>this.createUa(t).then(async()=>this._start()));c(this,"_createUa",async({displayName:t="",user:n,password:r,register:s=!1,sipServerUrl:o,sipWebSocketServerURL:i,remoteAddress:a,extraHeaders:u=[],sdpSemantics:l="plan-b",sessionTimers:d=!1,registerExpires:E=60*5,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:S=6,userAgent:g})=>{if(!o)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(s&&!n)throw new Error("user is required for authorized connection");if(s&&!r)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:o,displayName:t,register:s,user:n,password:r},this._init({sipServerUrl:o,sipWebSocketServerURL:i});const C=s&&n?n.trim():`${ts()}`,m={password:r,register:s,display_name:ke(t),user_agent:g,sdp_semantics:l,sockets:[this.socket],uri:this.getSipServerUrl(C),session_timers:d,register_expires:E,connection_recovery_min_interval:h,connection_recovery_max_interval:S};this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!m.register,this.ua=new this.JsSIP.UA(m),this._uaEvents.eachTriggers((N,v)=>{const y=Ne.find(f=>f===v);y&&this.ua&&this.ua.on(y,N)});const b=[...pr(a),...u];return this.ua.registrator().setExtraHeaders(b),this.ua});c(this,"_start",async()=>new Promise((t,n)=>{const{ua:r}=this;if(!r){n(new Error("this.ua is not initialized"));return}const s=()=>{a(),t(r)},o=u=>{a(),n(u)},i=()=>{this.isRegisterConfig?(this.on(x,s),this.on(W,o)):this.on(ce,s),this.on(w,o)},a=()=>{this.off(x,s),this.off(W,o),this.off(ce,s),this.off(w,o)};i(),this.on(ue,this.handleNewRTCSession),r.start()}));c(this,"_set",async({displayName:t,password:n})=>new Promise((r,s)=>{const{ua:o}=this;if(!o){s(new Error("this.ua is not initialized"));return}let i=!1,a=!1;t!==void 0&&t!==this._connectionConfiguration.displayName&&(i=o.set("display_name",ke(t)),this._connectionConfiguration.displayName=t),n!==void 0&&n!==this._connectionConfiguration.password&&(a=o.set("password",n),this._connectionConfiguration.password=n);const u=i||a;a&&this.isRegisterConfig?this.register().then(()=>{r(u)}).catch(s):u?r(u):s(u)}));c(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());c(this,"_disconnect",async()=>{this.off(ue,this.handleNewRTCSession);const t=new Promise(n=>{this.once(w,()=>{delete this.ua,n()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(w,void 0)):this._uaEvents.trigger(w,void 0),t});c(this,"_call",async({number:t,mediaStream:n,extraHeaders:r=[],ontrack:s,iceServers:o,videoMode:i,audioMode:a,degradationPreference:u,offerToReceiveAudio:l=!0,offerToReceiveVideo:d=!0})=>new Promise((E,h)=>{const{ua:S}=this;if(!S){h(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=t,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:s}).then(E).catch(h),this.session=S.call(this.getSipServerUrl(t),{extraHeaders:r,mediaStream:ne(n,{videoMode:i,audioMode:a}),eventHandlers:this._sessionEvents.triggers,videoMode:i,audioMode:a,degradationPreference:u,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:d}})}));c(this,"_answer",async({mediaStream:t,ontrack:n,extraHeaders:r=[],iceServers:s,videoMode:o,audioMode:i,degradationPreference:a})=>new Promise((u,l)=>{if(!this.isAvailableIncomingCall){l(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:d}=this;if(!d){l(new Error("No session established"));return}this._sessionEvents.eachTriggers((h,S)=>{const g=ve.find(C=>C===S);g&&d.on(g,h)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:n}).then(u).catch(l);const E=ne(t,{videoMode:o,audioMode:i});d.answer({extraHeaders:r,videoMode:o,audioMode:i,degradationPreference:a,mediaStream:E,pcConfig:{iceServers:s}})}));c(this,"_handleCall",async({ontrack:t})=>new Promise((n,r)=>{const s=()=>{this.onSession(he,d),this.onSession(Ee,E)},o=()=>{this.offSession(he,d),this.offSession(Ee,E)},i=()=>{this.onSession(U,u),this.onSession(q,u)},a=()=>{this.offSession(U,u),this.offSession(q,u)},u=h=>{o(),a(),r(h)};let l;const d=({peerconnection:h})=>{l=h,l.ontrack=S=>{this._sessionEvents.trigger(It,l),t&&t(S)}},E=()=>{l&&this._sessionEvents.trigger(yt,l),o(),a(),n(l)};s(),i()}));c(this,"_restoreSession",()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});c(this,"_sendDTMF",async t=>new Promise((n,r)=>{const{session:s}=this;if(!s){r(new Error("No session established"));return}this.onceSession(Gt,({originator:o})=>{o===Se&&n()}),s.sendDTMF(t,{duration:120,interToneGap:600})}));c(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:t}=this;this._streamPresentationCurrent&&await this.stopPresentation(),this._restoreSession(),t.isEnded()||t.terminate()}});c(this,"_handleShareState",t=>{switch(t){case Zt:{this._sessionEvents.trigger(Nt,void 0);break}case en:{this._sessionEvents.trigger(vt,void 0);break}case Gr:{this._sessionEvents.trigger(At,void 0);break}}});c(this,"_maybeTriggerChannels",t=>{const n=t.getHeader(Le),r=t.getHeader(Ue);if(n&&r){const s={inputChannels:n,outputChannels:r};this._sessionEvents.trigger(_e,s)}});c(this,"_handleNotify",t=>{switch(t.cmd){case hs:{const n=t;this._triggerChannelsNotify(n);break}case fs:{const n=t;this._triggerWebcastStartedNotify(n);break}case Ss:{const n=t;this._triggerWebcastStoppedNotify(n);break}case Cs:{const n=t;this._triggerAddedToListModeratorsNotify(n);break}case ms:{const n=t;this._triggerRemovedFromListModeratorsNotify(n);break}case Rs:{const n=t;this._triggerParticipantMoveRequestToConference(n);break}case Ns:{const n=t;this._triggerParticipantCancelingWordRequest(n);break}case vs:{const n=t;this._triggerParticipantMoveRequestToStream(n);break}case gs:{this._triggerAccountChangedNotify();break}case Ts:{this._triggerAccountDeletedNotify();break}case As:{const n=t;this._triggerConferenceParticipantTokenIssued(n);break}default:_("unknown cmd",t.cmd)}});c(this,"_triggerRemovedFromListModeratorsNotify",({conference:t})=>{const n={conference:t};this._uaEvents.trigger(Ft,n)});c(this,"_triggerAddedToListModeratorsNotify",({conference:t})=>{const n={conference:t};this._uaEvents.trigger(Ut,n)});c(this,"_triggerWebcastStartedNotify",({body:{conference:t,type:n}})=>{const r={conference:t,type:n};this._uaEvents.trigger(xt,r)});c(this,"_triggerWebcastStoppedNotify",({body:{conference:t,type:n}})=>{const r={conference:t,type:n};this._uaEvents.trigger(Wt,r)});c(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(qt,void 0)});c(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(Vt,void 0)});c(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:t,participant:n,jwt:r}})=>{const s={conference:t,participant:n,jwt:r};this._uaEvents.trigger(jt,s)});c(this,"_triggerChannelsNotify",t=>{const n=t.input,r=t.output,s={inputChannels:n,outputChannels:r};this._uaEvents.trigger(Ot,s)});c(this,"_triggerParticipantMoveRequestToConference",({body:{conference:t}})=>{const n={conference:t};this._uaEvents.trigger(kt,n)});c(this,"_triggerParticipantCancelingWordRequest",({body:{conference:t}})=>{const n={conference:t};this._uaEvents.trigger(Ht,n)});c(this,"_triggerParticipantMoveRequestToStream",({body:{conference:t}})=>{const n={conference:t};this._uaEvents.trigger(Bt,n)});c(this,"_triggerEnterRoom",t=>{const n=t.getHeader(yr);this._sessionEvents.trigger(pt,n)});c(this,"_triggerShareState",t=>{const n=t.getHeader(k);this._sessionEvents.trigger(le,n)});c(this,"_triggerMainCamControl",t=>{const n=t.getHeader(Lr),r=t.getHeader(Fe),s=r===j.ADMIN_SYNC_FORCED;if(n===M.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(wt,{isSyncForced:s});else if(n===M.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(Dt,{isSyncForced:s});else if((n===M.RESUME_MAIN_CAM||n===M.PAUSE_MAIN_CAM)&&r)this._sessionEvents.trigger(de,{isSyncForced:s});else{const o=t.getHeader(Fr);this._sessionEvents.trigger(Pt,{mainCam:n,resolutionMainCam:o})}});c(this,"_triggerMicControl",t=>{const n=t.getHeader(Ur),s=t.getHeader(Fe)===j.ADMIN_SYNC_FORCED;n===V.ADMIN_START_MIC?this._sessionEvents.trigger(Lt,{isSyncForced:s}):n===V.ADMIN_STOP_MIC&&this._sessionEvents.trigger($t,{isSyncForced:s})});c(this,"_triggerUseLicense",t=>{const n=t.getHeader($r);this._sessionEvents.trigger(bt,n)});c(this,"_handleNewInfo",t=>{const{originator:n}=t;if(n!=="remote")return;const{request:r}=t,s=r.getHeader(br);if(s)switch(s){case Ir:{this._triggerEnterRoom(r),this._maybeTriggerChannels(r);break}case Wr:{this._maybeHandleNotify(r);break}case te:{this._triggerShareState(r);break}case $e:{this._triggerMainCamControl(r);break}case Dr:{this._triggerMicControl(r);break}case wr:{this._triggerUseLicense(r);break}}});c(this,"_handleSipEvent",({request:t})=>{this._maybeHandleNotify(t)});c(this,"_maybeHandleNotify",t=>{const n=t.getHeader(qr);if(n){const r=JSON.parse(n);this._handleNotify(r)}});c(this,"_handleEnded",t=>{const{originator:n}=t;n===Be&&this._sessionEvents.trigger(Mt,t),this._restoreSession()});this.JsSIP=t,this._sessionEvents=new we(Qt),this._uaEvents=new we(Kt),this._cancelableConnect=new O.CancelableRequest(this._connect,{moduleName:D,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new O.CancelableRequest(this._createUa,{moduleName:D}),this._cancelableDisconnect=new O.CancelableRequest(this._disconnect,{moduleName:D}),this._cancelableSet=new O.CancelableRequest(this._set,{moduleName:D}),this._cancelableCall=new O.CancelableRequest(this._call,{moduleName:D}),this._cancelableAnswer=new O.CancelableRequest(this._answer,{moduleName:D}),this._cancelableSendDTMF=new O.CancelableRequest(this._sendDTMF,{moduleName:D}),this.onSession(le,this._handleShareState),this.onSession(Yt,this._handleNewInfo),this.on(Rt,this._handleSipEvent),this.onSession(U,this._handleEnded),this.onSession(q,this._handleEnded)}async register(){return new Promise((t,n)=>{this.isRegisterConfig&&this.ua?(this.ua.on(x,t),this.ua.on(W,n),this.ua.register()):n(new Error("Config is not registered"))})}async unregister(){return new Promise((t,n)=>{this.isRegistered&&this.ua?(this.ua.on(mt,t),this.ua.unregister()):n(new Error("ua is not registered"))})}async sendOptions(t,n,r){if(!this.ua)throw new Error("is not connected");return new Promise((s,o)=>{try{this.ua.sendOptions(t,n,{extraHeaders:r,eventHandlers:{succeeded:()=>{s()},failed:o}})}catch(i){o(i)}})}async ping(t,n){var s;if(!((s=this.ua)!=null&&s.configuration.uri))throw new Error("is not connected");const r=this.ua.configuration.uri;return this.sendOptions(r,t,n)}async replaceMediaStream(t,n){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(t,n)}async askPermissionToEnableCam(t={}){if(!this.session)throw new Error("No session established");const n=[Jr];return this.session.sendInfo($e,void 0,{noTerminateWhenError:!0,...t,extraHeaders:n}).catch(r=>{if(ss(r))throw r})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentation(t,n,{maxBitrate:r,degradationPreference:s,isNeedReinvite:o=!0,isP2P:i=!1}){const a=ne(n);this._streamPresentationCurrent=a;const u=i?[Yr]:[Vr],l=t.sendInfo(te,void 0,{extraHeaders:u}).then(async()=>t.startPresentation(a,o,s)).then(async()=>{const{connection:d}=this;if(!d||r===void 0)return;const E=d.getSenders();return ls(E,n,r)}).then(()=>n).catch(d=>{throw this._sessionEvents.trigger(fe,d),d});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(t,{isNeedReinvite:n=!0,isP2P:r=!1,maxBitrate:s,degradationPreference:o}={}){const i=this.establishedSession;if(!i)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return this._sendPresentation(i,t,{isNeedReinvite:n,isP2P:r,maxBitrate:s,degradationPreference:o})}async stopPresentation({isP2P:t=!1}={}){const n=this._streamPresentationCurrent;let r=this.promisePendingStartPresentation??Promise.resolve();const s=t?[Xr]:[jr],o=this.establishedSession;return o&&n&&(r=r.then(async()=>o.sendInfo(te,void 0,{extraHeaders:s})).then(async()=>o.stopPresentation(n)).catch(i=>{throw this._sessionEvents.trigger(fe,i),i})),!o&&n&&this._sessionEvents.trigger(Xt,n),this.promisePendingStopPresentation=r,r.finally(()=>{this._resetPresentation()})}async updatePresentation(t,{isP2P:n=!1,maxBitrate:r,degradationPreference:s}={}){const o=this.establishedSession;if(!o)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(o,t,{isP2P:n,maxBitrate:r,degradationPreference:s,isNeedReinvite:!1})}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(t,n){return this._uaEvents.on(t,n)}once(t,n){return this._uaEvents.once(t,n)}onceRace(t,n){return this._uaEvents.onceRace(t,n)}async wait(t){return this._uaEvents.wait(t)}off(t,n){this._uaEvents.off(t,n)}onSession(t,n){return this._sessionEvents.on(t,n)}onceSession(t,n){return this._sessionEvents.once(t,n)}onceRaceSession(t,n){return this._sessionEvents.onceRace(t,n)}async waitSession(t){return this._sessionEvents.wait(t)}offSession(t,n){this._sessionEvents.off(t,n)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return{...this._connectionConfiguration}}getRemoteStreams(){if(!this.connection)return;const n=this.connection.getReceivers().map(({track:r})=>r);return ns(n)?this._generateStreams(n):this._generateAudioStreams(n)}get connection(){var n;return(n=this.session)==null?void 0:n.connection}get remoteCallerData(){var t,n,r,s,o,i;return{displayName:(n=(t=this.incomingSession)==null?void 0:t.remote_identity)==null?void 0:n.display_name,host:(s=(r=this.incomingSession)==null?void 0:r.remote_identity)==null?void 0:s.uri.host,incomingNumber:(i=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:i.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:t,sipWebSocketServerURL:n}){this.getSipServerUrl=Zr(t),this.socket=new this.JsSIP.WebSocketInterface(n)}_generateStream(t,n){const{id:r}=t,s=this._remoteStreams[r]||new MediaStream;return n&&s.addTrack(n),s.addTrack(t),this._remoteStreams[r]=s,s}_generateAudioStream(t){const{id:n}=t,r=this._remoteStreams[n]||new MediaStream;return r.addTrack(t),this._remoteStreams[n]=r,r}_generateStreams(t){const n=[];return t.forEach((r,s)=>{if(r.kind==="audio")return;const o=r,i=t[s-1];let a;i&&i.kind==="audio"&&(a=i);const u=this._generateStream(o,a);n.push(u)}),n}_generateAudioStreams(t){return t.map(r=>this._generateAudioStream(r))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession(_e)}async waitSyncMediaState(){return this.waitSession(de)}async sendChannels({inputChannels:t,outputChannels:n}){if(!this.session)throw new Error("No session established");const r=`${Le}: ${t}`,s=`${Ue}: ${n}`,o=[r,s];return this.session.sendInfo(Or,void 0,{extraHeaders:o})}async sendMediaState({cam:t,mic:n},r={}){if(!this.session)throw new Error("No session established");const s=`${kr}: currentstate`,o=`${Hr}: ${Number(t)}`,i=`${xr}: ${Number(n)}`,a=[s,o,i];return this.session.sendInfo(Mr,void 0,{noTerminateWhenError:!0,...r,extraHeaders:a})}async _sendRefusalToTurnOn(t,n={}){if(!this.session)throw new Error("No session established");const a=[`${Br}: ${t==="mic"?0:1}`];return this.session.sendInfo(Pr,void 0,{noTerminateWhenError:!0,...n,extraHeaders:a})}async sendRefusalToTurnOnMic(t={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...t})}async sendRefusalToTurnOnCam(t={}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...t})}}const on="purgatory",F=e=>e===on,pe=e=>()=>(_("getRemoteStreams"),e.getRemoteStreams()),bs=({kind:e,readyState:t})=>e==="video"&&t==="live",an=e=>({track:t})=>{bs(t)&&e()};var H=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function be(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ys(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var $=ys,Is=typeof H=="object"&&H&&H.Object===Object&&H,cn=Is,Os=cn,Ms=typeof self=="object"&&self&&self.Object===Object&&self,Ps=Os||Ms||Function("return this")(),K=Ps,Ds=K,ws=function(){return Ds.Date.now()},$s=ws,Ls=/\s/;function Us(e){for(var t=e.length;t--&&Ls.test(e.charAt(t)););return t}var Fs=Us,ks=Fs,Bs=/^\s+/;function Hs(e){return e&&e.slice(0,ks(e)+1).replace(Bs,"")}var xs=Hs,Ws=K,qs=Ws.Symbol,Q=qs,He=Q,un=Object.prototype,Vs=un.hasOwnProperty,js=un.toString,L=He?He.toStringTag:void 0;function Gs(e){var t=Vs.call(e,L),n=e[L];try{e[L]=void 0;var r=!0}catch{}var s=js.call(e);return r&&(t?e[L]=n:delete e[L]),s}var Ys=Gs,Xs=Object.prototype,zs=Xs.toString;function Js(e){return zs.call(e)}var Ks=Js,xe=Q,Qs=Ys,Zs=Ks,eo="[object Null]",to="[object Undefined]",We=xe?xe.toStringTag:void 0;function no(e){return e==null?e===void 0?to:eo:We&&We in Object(e)?Qs(e):Zs(e)}var Z=no;function ro(e){return e!=null&&typeof e=="object"}var B=ro,so=Z,oo=B,io="[object Symbol]";function ao(e){return typeof e=="symbol"||oo(e)&&so(e)==io}var ln=ao,co=xs,qe=$,uo=ln,Ve=0/0,lo=/^[-+]0x[0-9a-f]+$/i,_o=/^0b[01]+$/i,Eo=/^0o[0-7]+$/i,ho=parseInt;function fo(e){if(typeof e=="number")return e;if(uo(e))return Ve;if(qe(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=qe(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=co(e);var n=_o.test(e);return n||Eo.test(e)?ho(e.slice(2),n?2:8):lo.test(e)?Ve:+e}var So=fo,go=$,re=$s,je=So,To="Expected a function",Co=Math.max,mo=Math.min;function Ro(e,t,n){var r,s,o,i,a,u,l=0,d=!1,E=!1,h=!0;if(typeof e!="function")throw new TypeError(To);t=je(t)||0,go(n)&&(d=!!n.leading,E="maxWait"in n,o=E?Co(je(n.maxWait)||0,t):o,h="trailing"in n?!!n.trailing:h);function S(f){var R=r,p=s;return r=s=void 0,l=f,i=e.apply(p,R),i}function g(f){return l=f,a=setTimeout(A,t),d?S(f):i}function C(f){var R=f-u,p=f-l,P=t-R;return E?mo(P,o-p):P}function m(f){var R=f-u,p=f-l;return u===void 0||R>=t||R<0||E&&p>=o}function A(){var f=re();if(m(f))return b(f);a=setTimeout(A,C(f))}function b(f){return a=void 0,h&&r?S(f):(r=s=void 0,i)}function N(){a!==void 0&&clearTimeout(a),l=0,r=u=s=a=void 0}function v(){return a===void 0?i:b(re())}function y(){var f=re(),R=m(f);if(r=arguments,s=this,u=f,R){if(a===void 0)return g(u);if(E)return clearTimeout(a),a=setTimeout(A,t),S(u)}return a===void 0&&(a=setTimeout(A,t)),i}return y.cancel=N,y.flush=v,y}var No=Ro;const vo=be(No),ye=({getRemoteStreams:e,setRemoteStreams:t})=>vo(()=>{const n=e();_("remoteStreams",n),n&&t(n)},200),Ao=e=>async n=>{const{mediaStream:r,extraHeaders:s,iceServers:o,degradationPreference:i,setRemoteStreams:a,onBeforeProgressCall:u,onSuccessProgressCall:l,onEnterPurgatory:d,onEnterConference:E,onFailProgressCall:h,onFinishProgressCall:S,onEndedCall:g}=n,C=ye({setRemoteStreams:a,getRemoteStreams:pe(e)}),m=an(C);_("answerIncomingCall",n);const A=async()=>e.answerToIncomingCall({mediaStream:r,extraHeaders:s,iceServers:o,degradationPreference:i,ontrack:m}),b=()=>{const{remoteCallerData:T}=e;return T.incomingNumber};let N=!1,v;const f=(()=>(_("subscribeEnterConference: onEnterConference",E),d??E?e.onSession("enterRoom",T=>{_("enterRoom",{_room:T,isSuccessProgressCall:N}),v=T,F(v)?d&&d():E&&E({isSuccessProgressCall:N})}):()=>{}))(),R=T=>(_("onSuccess"),N=!0,C(),l&&l({isPurgatory:F(v)}),e.onceRaceSession(["ended","failed"],()=>{f(),g&&g()}),T),p=T=>{throw _("onFail"),h&&h(),f(),T},P=()=>{_("onFinish"),S&&S()};if(_("onBeforeProgressCall"),u){const T=b();u(T)}return A().then(R).catch(p).finally(P)},po=e=>async n=>{const{conference:r,mediaStream:s,extraHeaders:o,iceServers:i,degradationPreference:a,setRemoteStreams:u,onBeforeProgressCall:l,onSuccessProgressCall:d,onEnterPurgatory:E,onEnterConference:h,onFailProgressCall:S,onFinishProgressCall:g,onEndedCall:C}=n,m=ye({setRemoteStreams:u,getRemoteStreams:pe(e)}),A=an(m);_("callToServer",n);const b=async()=>(_("startCall"),e.call({mediaStream:s,extraHeaders:o,iceServers:i,degradationPreference:a,number:r,ontrack:A}));let N=!1,v;const f=(()=>(_("subscribeEnterConference: onEnterConference",h),E??h?e.onSession("enterRoom",T=>{_("enterRoom",{_room:T,isSuccessProgressCall:N}),v=T,F(v)?E&&E():h&&h({isSuccessProgressCall:N})}):()=>{}))(),R=T=>(_("onSuccess"),N=!0,m(),d&&d({isPurgatory:F(v)}),e.onceRaceSession(["ended","failed"],()=>{f(),C&&C()}),T),p=T=>{throw _("onFail"),S&&S(),f(),T},P=()=>{_("onFinish"),g&&g()};return _("onBeforeProgressCall"),l&&l(r),b().then(R).catch(p).finally(P)},se=e=>{if(!O.isCanceledError(e))throw e;return!1},bo=e=>async n=>{const{userAgent:r,sipWebSocketServerURL:s,sipServerUrl:o,remoteAddress:i,displayName:a,name:u,password:l,isRegisteredUser:d,sdpSemantics:E,isDisconnectOnFail:h}=n;return _("connectToServer",n),e.connect({userAgent:r,sdpSemantics:E,sipWebSocketServerURL:s,sipServerUrl:o,remoteAddress:i,displayName:a,password:l,user:u,register:d}).then(()=>(_("connectToServer then"),!0)).catch(async S=>(_("connectToServer catch: error",S),h===!0?e.disconnect().then(()=>se(S)).catch(()=>se(S)):se(S)))},yo=e=>async()=>(_("disconnectFromServer"),e.disconnect().then(()=>(_("disconnectFromServer: then"),!1)).catch(t=>(_("disconnectFromServer: catch",t),!1))),Ie=e=>{const{url:t,cause:n}=e;let r=t;return(n===me||n===Ce)&&(r=`${e.message.to.uri.user}@${e.message.to.uri.host}`),r};var _n=(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))(_n||{});const Io=(e=new Error)=>{var s;const{cause:t,socket:n}=e;let r="CONNECT_SERVER_FAILED";switch(t){case"Forbidden":{r="WRONG_USER_OR_PASSWORD";break}case me:{r="BAD_MEDIA_ERROR";break}case Ce:{r="NOT_FOUND_ERROR";break}default:n&&((s=n==null?void 0:n._ws)==null?void 0:s.readyState)===3?r="WS_CONNECTION_FAILED":Ie(e)&&(r="CONNECT_SERVER_FAILED_BY_LINK")}return r},Oo=(e=new Error)=>{const{code:t,cause:n,message:r}=e,s=Ie(e),o={};return r&&(o.message=r),s&&(o.link=s),t&&(o.code=t),n&&(o.cause=n),o},Mo=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:_n,getLinkError:Ie,getTypeFromError:Io,getValuesFromError:Oo},Symbol.toStringTag,{value:"Module"})),Po=({sessionId:e,remoteAddress:t,isMutedAudio:n,isMutedVideo:r,isRegistered:s,isPresentationCall:o})=>{const i=[],a=n?"0":"1",u=r?"0":"1";return i.push(`X-Vinteo-Mic-State: ${a}`,`X-Vinteo-MainCam-State: ${u}`),s||i.push("X-Vinteo-Purgatory-Call: yes"),e&&i.push(`X-Vinteo-Session: ${e}`),o&&i.push("X-Vinteo-Presentation-Call: yes"),t&&i.push(`X-Vinteo-Remote: ${t}`),i},Do=({appName:e,appVersion:t,browserName:n,browserVersion:r})=>{const s=`${e} ${t}`;return`ChromeNew - ${n?`${n} ${r}, ${s}`:s}`},wo=({isUnifiedSdpSemantic:e,appVersion:t,browserName:n,browserVersion:r,appName:s})=>e?Do({appVersion:t,browserName:n,browserVersion:r,appName:s}):"Chrome",$o=e=>async()=>{if(e.isCallActive)return _("askPermissionToEnableCam"),e.askPermissionToEnableCam()},Lo=e=>n=>(_("onMustStopPresentation"),e.onSession("mustStopPresentation",n)),Uo=e=>n=>(_("onUseLicense"),e.onSession("useLicense",n)),Fo=e=>async({isEnabledCam:n,isEnabledMic:r})=>{if(e.isCallActive)return _("sendMediaState"),e.sendMediaState({cam:n,mic:r})},ko=e=>async()=>{if(e.isCallActive)return _("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch(n=>{_("sendRefusalToTurnOnCam: error",n)})},Bo=e=>async()=>{if(e.isCallActive)return _("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch(n=>{_("sendRefusalToTurnOnMic: error",n)})},Ho=1e6,xo=({maxBitrate:e=Ho,sipConnector:t})=>async({mediaStream:r,isP2P:s=!1})=>(_("startPresentation"),t.startPresentation(r,{isP2P:s,maxBitrate:e})),Wo=({sipConnector:e})=>async({isP2P:n=!1}={})=>(_("stopShareSipConnector"),e.stopPresentation({isP2P:n}).catch(_)),qo=1e6,Vo=({sipConnector:e,maxBitrate:t=qo})=>async({mediaStream:r,isP2P:s=!1})=>(_("updatePresentation"),e.updatePresentation(r,{isP2P:s,maxBitrate:t}));var jo=$,Ge=Object.create,Go=function(){function e(){}return function(t){if(!jo(t))return{};if(Ge)return Ge(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}(),dn=Go;function Yo(){}var Oe=Yo,Xo=dn,zo=Oe;function G(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}G.prototype=Xo(zo.prototype);G.prototype.constructor=G;var Me=G;function Jo(e,t){for(var n=-1,r=t.length,s=e.length;++n<r;)e[s+n]=t[n];return e}var Ko=Jo,Qo=Z,Zo=B,ei="[object Arguments]";function ti(e){return Zo(e)&&Qo(e)==ei}var ni=ti,Ye=ni,ri=B,En=Object.prototype,si=En.hasOwnProperty,oi=En.propertyIsEnumerable,ii=Ye(function(){return arguments}())?Ye:function(e){return ri(e)&&si.call(e,"callee")&&!oi.call(e,"callee")},ai=ii,ci=Array.isArray,ee=ci,Xe=Q,ui=ai,li=ee,ze=Xe?Xe.isConcatSpreadable:void 0;function _i(e){return li(e)||ui(e)||!!(ze&&e&&e[ze])}var di=_i,Ei=Ko,hi=di;function hn(e,t,n,r,s){var o=-1,i=e.length;for(n||(n=hi),s||(s=[]);++o<i;){var a=e[o];t>0&&n(a)?t>1?hn(a,t-1,n,r,s):Ei(s,a):r||(s[s.length]=a)}return s}var fi=hn,Si=fi;function gi(e){var t=e==null?0:e.length;return t?Si(e,1):[]}var Ti=gi;function Ci(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}var mi=Ci,Ri=mi,Je=Math.max;function Ni(e,t,n){return t=Je(t===void 0?e.length-1:t,0),function(){for(var r=arguments,s=-1,o=Je(r.length-t,0),i=Array(o);++s<o;)i[s]=r[t+s];s=-1;for(var a=Array(t+1);++s<t;)a[s]=r[s];return a[t]=n(i),Ri(e,this,a)}}var vi=Ni;function Ai(e){return function(){return e}}var pi=Ai,bi=Z,yi=$,Ii="[object AsyncFunction]",Oi="[object Function]",Mi="[object GeneratorFunction]",Pi="[object Proxy]";function Di(e){if(!yi(e))return!1;var t=bi(e);return t==Oi||t==Mi||t==Ii||t==Pi}var fn=Di,wi=K,$i=wi["__core-js_shared__"],Li=$i,oe=Li,Ke=function(){var e=/[^.]+$/.exec(oe&&oe.keys&&oe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Ui(e){return!!Ke&&Ke in e}var Fi=Ui,ki=Function.prototype,Bi=ki.toString;function Hi(e){if(e!=null){try{return Bi.call(e)}catch{}try{return e+""}catch{}}return""}var xi=Hi,Wi=fn,qi=Fi,Vi=$,ji=xi,Gi=/[\\^$.*+?()[\]{}|]/g,Yi=/^\[object .+?Constructor\]$/,Xi=Function.prototype,zi=Object.prototype,Ji=Xi.toString,Ki=zi.hasOwnProperty,Qi=RegExp("^"+Ji.call(Ki).replace(Gi,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Zi(e){if(!Vi(e)||qi(e))return!1;var t=Wi(e)?Qi:Yi;return t.test(ji(e))}var ea=Zi;function ta(e,t){return e==null?void 0:e[t]}var na=ta,ra=ea,sa=na;function oa(e,t){var n=sa(e,t);return ra(n)?n:void 0}var Sn=oa,ia=Sn,aa=function(){try{var e=ia(Object,"defineProperty");return e({},"",{}),e}catch{}}(),ca=aa;function ua(e){return e}var la=ua,_a=pi,Qe=ca,da=la,Ea=Qe?function(e,t){return Qe(e,"toString",{configurable:!0,enumerable:!1,value:_a(t),writable:!0})}:da,ha=Ea,fa=800,Sa=16,ga=Date.now;function Ta(e){var t=0,n=0;return function(){var r=ga(),s=Sa-(r-n);if(n=r,s>0){if(++t>=fa)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var Ca=Ta,ma=ha,Ra=Ca,Na=Ra(ma),va=Na,Aa=Ti,pa=vi,ba=va;function ya(e){return ba(pa(e,void 0,Aa),e+"")}var Ia=ya,Oa=Sn,Ma=K,Pa=Oa(Ma,"WeakMap"),Da=Pa,Ze=Da,wa=Ze&&new Ze,$a=wa;function La(){}var Ua=La,et=$a,Fa=Ua,ka=et?function(e){return et.get(e)}:Fa,gn=ka,Ba={},Ha=Ba,tt=Ha,xa=Object.prototype,Wa=xa.hasOwnProperty;function qa(e){for(var t=e.name+"",n=tt[t],r=Wa.call(tt,t)?n.length:0;r--;){var s=n[r],o=s.func;if(o==null||o==e)return s.name}return t}var Tn=qa,Va=dn,ja=Oe,Ga=4294967295;function Y(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Ga,this.__views__=[]}Y.prototype=Va(ja.prototype);Y.prototype.constructor=Y;var Pe=Y;function Ya(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}var Xa=Ya,za=Pe,Ja=Me,Ka=Xa;function Qa(e){if(e instanceof za)return e.clone();var t=new Ja(e.__wrapped__,e.__chain__);return t.__actions__=Ka(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Za=Qa,ec=Pe,nt=Me,tc=Oe,nc=ee,rc=B,sc=Za,oc=Object.prototype,ic=oc.hasOwnProperty;function X(e){if(rc(e)&&!nc(e)&&!(e instanceof ec)){if(e instanceof nt)return e;if(ic.call(e,"__wrapped__"))return sc(e)}return new nt(e)}X.prototype=tc.prototype;X.prototype.constructor=X;var ac=X,cc=Pe,uc=gn,lc=Tn,_c=ac;function dc(e){var t=lc(e),n=_c[t];if(typeof n!="function"||!(t in cc.prototype))return!1;if(e===n)return!0;var r=uc(n);return!!r&&e===r[0]}var Ec=dc,rt=Me,hc=Ia,fc=gn,ie=Tn,Sc=ee,st=Ec,gc="Expected a function",Tc=8,Cc=32,mc=128,Rc=256;function Nc(e){return hc(function(t){var n=t.length,r=n,s=rt.prototype.thru;for(e&&t.reverse();r--;){var o=t[r];if(typeof o!="function")throw new TypeError(gc);if(s&&!i&&ie(o)=="wrapper")var i=new rt([],!0)}for(r=i?r:n;++r<n;){o=t[r];var a=ie(o),u=a=="wrapper"?fc(o):void 0;u&&st(u[0])&&u[1]==(mc|Tc|Cc|Rc)&&!u[4].length&&u[9]==1?i=i[ie(u[0])].apply(i,u[3]):i=o.length==1&&st(o)?i[a]():i.thru(o)}return function(){var l=arguments,d=l[0];if(i&&l.length==1&&Sc(d))return i.plant(d).value();for(var E=0,h=n?t[E].apply(this,l):d;++E<n;)h=t[E].call(this,h);return h}})}var vc=Nc,Ac=vc,pc=Ac(),bc=pc;const yc=be(bc);function Ic(e,t){for(var n=-1,r=e==null?0:e.length,s=Array(r);++n<r;)s[n]=t(e[n],n,e);return s}var Oc=Ic,ot=Q,Mc=Oc,Pc=ee,Dc=ln,wc=1/0,it=ot?ot.prototype:void 0,at=it?it.toString:void 0;function Cn(e){if(typeof e=="string")return e;if(Pc(e))return Mc(e,Cn)+"";if(Dc(e))return at?at.call(e):"";var t=e+"";return t=="0"&&1/e==-wc?"-0":t}var mn=Cn;function $c(e,t,n){var r=-1,s=e.length;t<0&&(t=-t>s?0:s+t),n=n>s?s:n,n<0&&(n+=s),s=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(s);++r<s;)o[r]=e[r+t];return o}var Lc=$c,Uc=Lc;function Fc(e,t,n){var r=e.length;return n=n===void 0?r:n,!t&&n>=r?e:Uc(e,t,n)}var kc=Fc,Bc="\\ud800-\\udfff",Hc="\\u0300-\\u036f",xc="\\ufe20-\\ufe2f",Wc="\\u20d0-\\u20ff",qc=Hc+xc+Wc,Vc="\\ufe0e\\ufe0f",jc="\\u200d",Gc=RegExp("["+jc+Bc+qc+Vc+"]");function Yc(e){return Gc.test(e)}var Rn=Yc;function Xc(e,t){return e===t||e!==e&&t!==t}var zc=Xc,Jc=9007199254740991;function Kc(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Jc}var Qc=Kc,Zc=fn,eu=Qc;function tu(e){return e!=null&&eu(e.length)&&!Zc(e)}var nu=tu,ru=9007199254740991,su=/^(?:0|[1-9]\d*)$/;function ou(e,t){var n=typeof e;return t=t??ru,!!t&&(n=="number"||n!="symbol"&&su.test(e))&&e>-1&&e%1==0&&e<t}var iu=ou,au=zc,cu=nu,uu=iu,lu=$;function _u(e,t,n){if(!lu(n))return!1;var r=typeof t;return(r=="number"?cu(n)&&uu(t,n.length):r=="string"&&t in n)?au(n[t],e):!1}var du=_u,Eu=Z,hu=B,fu="[object RegExp]";function Su(e){return hu(e)&&Eu(e)==fu}var gu=Su;function Tu(e){return function(t){return e(t)}}var Cu=Tu,z={exports:{}};z.exports;(function(e,t){var n=cn,r=t&&!t.nodeType&&t,s=r&&!0&&e&&!e.nodeType&&e,o=s&&s.exports===r,i=o&&n.process,a=function(){try{var u=s&&s.require&&s.require("util").types;return u||i&&i.binding&&i.binding("util")}catch{}}();e.exports=a})(z,z.exports);var mu=z.exports,Ru=gu,Nu=Cu,ct=mu,ut=ct&&ct.isRegExp,vu=ut?Nu(ut):Ru,Au=vu;function pu(e){return e.split("")}var bu=pu,Nn="\\ud800-\\udfff",yu="\\u0300-\\u036f",Iu="\\ufe20-\\ufe2f",Ou="\\u20d0-\\u20ff",Mu=yu+Iu+Ou,Pu="\\ufe0e\\ufe0f",Du="["+Nn+"]",ge="["+Mu+"]",Te="\\ud83c[\\udffb-\\udfff]",wu="(?:"+ge+"|"+Te+")",vn="[^"+Nn+"]",An="(?:\\ud83c[\\udde6-\\uddff]){2}",pn="[\\ud800-\\udbff][\\udc00-\\udfff]",$u="\\u200d",bn=wu+"?",yn="["+Pu+"]?",Lu="(?:"+$u+"(?:"+[vn,An,pn].join("|")+")"+yn+bn+")*",Uu=yn+bn+Lu,Fu="(?:"+[vn+ge+"?",ge,An,pn,Du].join("|")+")",ku=RegExp(Te+"(?="+Te+")|"+Fu+Uu,"g");function Bu(e){return e.match(ku)||[]}var Hu=Bu,xu=bu,Wu=Rn,qu=Hu;function Vu(e){return Wu(e)?qu(e):xu(e)}var ju=Vu,Gu=mn;function Yu(e){return e==null?"":Gu(e)}var Xu=Yu,zu=mn,Ju=kc,Ku=Rn,Qu=du,Zu=Au,el=ju,tl=Xu,nl=4294967295;function rl(e,t,n){return n&&typeof n!="number"&&Qu(e,t,n)&&(t=n=void 0),n=n===void 0?nl:n>>>0,n?(e=tl(e),e&&(typeof t=="string"||t!=null&&!Zu(t))&&(t=zu(t),!t&&Ku(e))?Ju(el(e),0,n):e.split(t,n)):[]}var sl=rl;const ol=be(sl),il=e=>yc(t=>ol(t,""),t=>t.map(n=>async()=>e(n))),al=async({accumulatedKeys:e,sendKey:t,canRunTask:n})=>{const s=il(t)(e);return Un(s,n)},cl=e=>n=>(_("onStartMainCam"),e.onSession("admin-start-main-cam",n)),ul=e=>n=>(_("onStartMic"),e.onSession("admin-start-mic",n)),ll=e=>n=>(_("onStopMainCam"),e.onSession("admin-stop-main-cam",n)),_l=e=>n=>(_("onStopMic"),e.onSession("admin-stop-mic",n)),dl=({sipConnector:e})=>{const t=(g,C)=>({isSyncForced:m=!1})=>{if(m){g();return}C()},n=cl(e),r=ll(e),s=ul(e),o=_l(e);let i=()=>{},a=()=>{},u=()=>{},l=()=>{};const d=({onStartMainCamForced:g,onStartMainCamNotForced:C,onStopMainCamForced:m,onStopMainCamNotForced:A,onStartMicForced:b,onStartMicNotForced:N,onStopMicForced:v,onStopMicNotForced:y})=>{const f=t(g,C);i=n(f);const R=t(m,A);a=r(R);const p=t(b,N);u=s(p);const P=t(v,y);l=o(P)},E=()=>{i(),a(),u(),l()};return{start:g=>{d(g)},stop:()=>{E()}}},El=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:on,createSyncMediaState:dl,error:Mo,getExtraHeaders:Po,getUserAgent:wo,hasPurgatory:F,resolveAnswerIncomingCall:Ao,resolveAskPermissionToEnableCam:$o,resolveCallToServer:po,resolveConnectToServer:bo,resolveDisconnectFromServer:yo,resolveGetRemoteStreams:pe,resolveOnMustStopPresentation:Lo,resolveOnUseLicense:Uo,resolveSendMediaState:Fo,resolveSendRefusalToTurnOnCam:ko,resolveSendRefusalToTurnOnMic:Bo,resolveStartPresentation:xo,resolveStopShareSipConnector:Wo,resolveUpdatePresentation:Vo,resolveUpdateRemoteStreams:ye,sendDTMFAccumulated:al},Symbol.toStringTag,{value:"Module"})),hl=e=>[...e.keys()].map(t=>e.get(t)),fl=(e,t)=>hl(e).find(n=>n.type===t),In=async e=>e.getStats().then(t=>{const n=fl(t,"codec");return n==null?void 0:n.mimeType}),Sl=e=>e.find(t=>{var n;return((n=t==null?void 0:t.track)==null?void 0:n.kind)==="video"}),On=(e,t)=>e!==void 0&&t!==void 0&&e.toLowerCase().includes(t.toLowerCase()),gl=1e6,I=e=>e*gl,Mn=I(.06),Tl=I(4),Cl=e=>e<=64?Mn:e<=128?I(.12):e<=256?I(.25):e<=384?I(.32):e<=426?I(.38):e<=640?I(.5):e<=848?I(.7):e<=1280?I(1):e<=1920?I(2):Tl,ml="av1",Rl=e=>On(e,ml),Nl=.6,Pn=(e,t)=>Rl(t)?e*Nl:e,vl=e=>Pn(Mn,e),Dn=(e,t)=>{const n=Cl(e);return Pn(n,t)},wn=Fn(),Al=async()=>wn().catch(e=>{_("videoSendingBalancer: error",e)}),pl=async e=>(wn.add(e),Al()),De=async({sender:e,scaleResolutionDownBy:t,maxBitrate:n,onSetParameters:r})=>pl(async()=>sn(e,{scaleResolutionDownBy:t,maxBitrate:n},r)),bl=async({sender:e,codec:t},n)=>{const s=vl(t);return De({sender:e,maxBitrate:s,onSetParameters:n,scaleResolutionDownBy:200})},ae=async({sender:e,track:t,codec:n},r)=>{const i=t.getSettings().width,a=Dn(i,n);return De({sender:e,maxBitrate:a,onSetParameters:r,scaleResolutionDownBy:1})},yl=async({sender:e,track:t,resolution:n,codec:r},s)=>{const o=t.getSettings(),i=o.width,a=o.height,[u,l]=n.split("x"),d=i/Number(u),E=a/Number(l),S=Math.max(d,E,1),g=Dn(Number(u),r);return De({sender:e,maxBitrate:g,onSetParameters:s,scaleResolutionDownBy:S})},Il=async({mainCam:e,resolutionMainCam:t,sender:n,track:r,codec:s},o)=>{switch(e){case M.PAUSE_MAIN_CAM:return bl({sender:n,codec:s},o);case M.RESUME_MAIN_CAM:return ae({sender:n,track:r,codec:s},o);case M.MAX_MAIN_CAM_RESOLUTION:return t!==void 0?yl({sender:n,track:r,codec:s,resolution:t},o):ae({sender:n,track:r,codec:s},o);default:return ae({sender:n,track:r,codec:s},o)}},lt={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},_t=async({mainCam:e,resolutionMainCam:t,connection:n,onSetParameters:r,ignoreForCodec:s})=>{const o=n.getSenders(),i=Sl(o);if(!(i!=null&&i.track))return lt;const a=await In(i);return On(a,s)?lt:Il({mainCam:e,resolutionMainCam:t,sender:i,codec:a,track:i.track},r)},Ol=(e,{ignoreForCodec:t,onSetParameters:n}={})=>{const r=async()=>{const{connection:u}=e;if(!u)throw new Error("connection is not exist");return _t({connection:u,onSetParameters:n,ignoreForCodec:t})};let s=r;const o=async u=>(s=async()=>{const{mainCam:l,resolutionMainCam:d}=u,{connection:E}=e;if(!E)throw new Error("connection is not exist");return _t({mainCam:l,resolutionMainCam:d,connection:E,onSetParameters:n,ignoreForCodec:t})},s());return{subscribe:()=>{e.onSession("main-cam-control",o)},unsubscribe:()=>{e.offSession("main-cam-control",o)},balanceByTrack:r,resetMainCamControl(){s=r},async reBalance(){return s()}}};exports.debug=J;exports.EEventsMainCAM=M;exports.EEventsMic=V;exports.EEventsSyncMediaState=j;exports.EUseLicense=tn;exports.causes=tr;exports.default=ps;exports.disableDebug=Qr;exports.enableDebug=Kr;exports.eventNames=Ar;exports.getCodecFromSender=In;exports.hasCanceledCallError=Es;exports.resolveVideoSendingBalancer=Ol;exports.tools=El;
1
+ "use strict";var Yt=Object.defineProperty;var Gt=(n,e,t)=>e in n?Yt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>(Gt(n,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const I=require("@krivega/cancelable-promise"),Ye=require("events-constructor"),J=require("debug"),Xt=require("ts-debounce"),zt=require("sequent-promises"),Kt=require("stack-promises"),Jt="Connection Error",et="Request Timeout",Qt="SIP Failure Code",jt="Internal Error",Zt="Busy",tt="Rejected",en="Redirected",tn="Unavailable",se="Not Found",nn="Address Incomplete",sn="Incompatible SDP",rn="Missing SDP",on="Authentication Error",nt="Terminated",an="WebRTC Error",st="Canceled",cn="No Answer",un="Expires",En="No ACK",ln="Dialog Error",_n="User Denied Media Access",re="Bad Media Description",dn="RTP Timeout",Sn=Object.freeze(Object.defineProperty({__proto__:null,ADDRESS_INCOMPLETE:nn,AUTHENTICATION_ERROR:on,BAD_MEDIA_DESCRIPTION:re,BUSY:Zt,BYE:nt,CANCELED:st,CONNECTION_ERROR:Jt,DIALOG_ERROR:ln,EXPIRES:un,INCOMPATIBLE_SDP:sn,INTERNAL_ERROR:jt,MISSING_SDP:rn,NOT_FOUND:se,NO_ACK:En,NO_ANSWER:cn,REDIRECTED:en,REJECTED:tt,REQUEST_TIMEOUT:et,RTP_TIMEOUT:dn,SIP_FAILURE_CODE:Qt,UNAVAILABLE:tn,USER_DENIED_MEDIA_ACCESS:_n,WEBRTC_ERROR:an},Symbol.toStringTag,{value:"Module"})),oe="incomingCall",ie="declinedIncomingCall",ae="failedIncomingCall",ce="terminatedIncomingCall",Q="connecting",q="connected",P="disconnected",V="newRTCSession",L="registered",ue="unregistered",B="registrationFailed",rt="newMessage",Ee="sipEvent",le="availableSecondRemoteStream",_e="notAvailableSecondRemoteStream",de="mustStopPresentation",W="shareState",Se="enterRoom",he="useLicense",Te="peerconnection:confirmed",Ce="peerconnection:ontrack",$="channels",ge="channels:notify",Ne="ended:fromserver",Re="main-cam-control",me="admin-stop-main-cam",Ae="admin-start-main-cam",fe="admin-stop-mic",Ie="admin-start-mic",x="admin-force-sync-media-state",Me="participant:added-to-list-moderators",Oe="participant:removed-from-list-moderators",De="participant:move-request-to-conference",Pe="participant:move-request-to-stream",pe="participant:canceling-word-request",ve="webcast:started",be="webcast:stopped",ye="account:changed",we="account:deleted",Ue="conference:participant-token-issued",F="ended",ot="sending",it="reinvite",at="replaces",ct="refer",ut="progress",Et="accepted",Y="confirmed",G="peerconnection",b="failed",lt="muted",_t="unmuted",Le="newDTMF",Be="newInfo",dt="hold",St="unhold",ht="update",Tt="sdp",Ct="icecandidate",gt="getusermediafailed",Nt="peerconnection:createofferfailed",Rt="peerconnection:createanswerfailed",mt="peerconnection:setlocaldescriptionfailed",At="peerconnection:setremotedescriptionfailed",ft="presentation:start",It="presentation:started",Mt="presentation:end",Fe="presentation:ended",X="presentation:failed",hn=Object.freeze(Object.defineProperty({__proto__:null,ACCEPTED:Et,ACCOUNT_CHANGED:ye,ACCOUNT_DELETED:we,ADMIN_FORCE_SYNC_MEDIA_STATE:x,ADMIN_START_MAIN_CAM:Ae,ADMIN_START_MIC:Ie,ADMIN_STOP_MAIN_CAM:me,ADMIN_STOP_MIC:fe,AVAILABLE_SECOND_REMOTE_STREAM_EVENT:le,CHANNELS:$,CHANNELS_NOTIFY:ge,CONFERENCE_PARTICIPANT_TOKEN_ISSUED:Ue,CONFIRMED:Y,CONNECTED:q,CONNECTING:Q,DECLINED_INCOMING_CALL:ie,DISCONNECTED:P,ENDED:F,ENDED_FROM_SERVER:Ne,ENTER_ROOM:Se,FAILED:b,FAILED_INCOMING_CALL:ae,GET_USER_MEDIA_FAILED:gt,HOLD:dt,ICE_CANDIDATE:Ct,INCOMING_CALL:oe,MAIN_CAM_CONTROL:Re,MUST_STOP_PRESENTATION_EVENT:de,MUTED:lt,NEW_DTMF:Le,NEW_INFO:Be,NEW_MESSAGE:rt,NEW_RTC_SESSION:V,NOT_AVAILABLE_SECOND_REMOTE_STREAM_EVENT:_e,PARTICIPANT_ADDED_TO_LIST_MODERATORS:Me,PARTICIPANT_CANCELLING_WORD_REQUEST:pe,PARTICIPANT_MOVE_REQUEST_TO_CONFERENCE:De,PARTICIPANT_MOVE_REQUEST_TO_STREAM:Pe,PARTICIPANT_REMOVED_FROM_LIST_MODERATORS:Oe,PEER_CONNECTION:G,PEER_CONNECTION_CONFIRMED:Te,PEER_CONNECTION_CREATE_ANSWER_FAILED:Rt,PEER_CONNECTION_CREATE_OFFER_FAILED:Nt,PEER_CONNECTION_ONTRACK:Ce,PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED:mt,PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED:At,PRESENTATION_END:Mt,PRESENTATION_ENDED:Fe,PRESENTATION_FAILED:X,PRESENTATION_START:ft,PRESENTATION_STARTED:It,PROGRESS:ut,REFER:ct,REGISTERED:L,REGISTRATION_FAILED:B,REINVITE:it,REPLACES:at,SDP:Tt,SENDING:ot,SHARE_STATE:W,SIP_EVENT:Ee,TERMINATED_INCOMING_CALL:ce,UNHOLD:St,UNMUTED:_t,UNREGISTERED:ue,UPDATE:ht,USE_LICENSE:he,WEBCAST_STARTED:ve,WEBCAST_STOPPED:be},Symbol.toStringTag,{value:"Module"})),Ot=[oe,ie,ce,ae,pe,Pe,De,ge,Ue,ye,we,ve,be,Me,Oe],ke=[Q,q,P,V,L,ue,B,rt,Ee],Dt=[le,_e,de,W,Se,he,Te,Ce,$,Ne,Re,Ae,me,fe,Ie,x],He=[F,Q,ot,it,at,ct,ut,Et,Y,G,b,lt,_t,Le,Be,dt,St,ht,Tt,Ct,gt,Nt,Rt,mt,At,ft,It,Mt,Fe,X],Pt=[...ke,...Ot],pt=[...He,...Dt],Tn=Object.freeze(Object.defineProperty({__proto__:null,SESSION_EVENT_NAMES:pt,SESSION_JSSIP_EVENT_NAMES:He,SESSION_SYNTHETICS_EVENT_NAMES:Dt,UA_EVENT_NAMES:Pt,UA_JSSIP_EVENT_NAMES:ke,UA_SYNTHETICS_EVENT_NAMES:Ot},Symbol.toStringTag,{value:"Module"})),Cn=n=>{const e=[];return n&&e.push(`X-Vinteo-Remote: ${n}`),e},gn="content-type",Nn="x-webrtc-enter-room",j="application/vinteo.webrtc.sharedesktop",Rn="application/vinteo.webrtc.roomname",mn="application/vinteo.webrtc.channels",An="application/vinteo.webrtc.mediastate",fn="application/vinteo.webrtc.refusal",Ge="application/vinteo.webrtc.maincam",In="application/vinteo.webrtc.mic",Mn="application/vinteo.webrtc.uselic",On="X-WEBRTC-USE-LICENSE",Xe="X-WEBRTC-INPUT-CHANNELS",ze="X-WEBRTC-OUTPUT-CHANNELS",Dn="X-WEBRTC-MAINCAM",Pn="X-WEBRTC-MIC",Ke="X-WEBRTC-SYNC",pn="X-WEBRTC-MAINCAM-RESOLUTION",vn="X-WEBRTC-MEDIA-STATE",bn="X-Vinteo-Media-Type",yn="X-Vinteo-MainCam-State",wn="X-Vinteo-Mic-State",Un="application/vinteo.webrtc.notify",Ln="X-VINTEO-NOTIFY",H="x-webrtc-share-state",Bn=`${H}: LETMESTARTPRESENTATION`,Fn=`${H}: STOPPRESENTATION`,vt="YOUCANRECEIVECONTENT",bt="CONTENTEND",kn="YOUMUSTSTOPSENDCONTENT",Hn=`${H}: ${vt}`,qn=`${H}: ${bt}`,Vn="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",Wn=`${Vn}: LETMESTARTMAINCAM`,qe="sip-connector",E=J(qe),$n=()=>{J.enable(`${qe}`)},xn=()=>{J.enable(`-${qe}`)};var M=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(M||{}),z=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(z||{}),K=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(K||{}),yt=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(yt||{});function Yn(n){return e=>`sip:${e}@${n}`}const Gn=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,Je=n=>n.trim().replaceAll(" ","_"),Xn=Gn(1e5,99999999),Z=(n,{videoMode:e,audioMode:t}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const s=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),o=[...s,...r],i=new MediaStream(o);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},zn=n=>n.some(t=>{const{kind:s}=t;return s==="video"}),Kn="Error decline with 603",Jn=n=>n.message===Kn,Qn=(n,e)=>n.find(t=>t.track&&e.getTracks().includes(t.track)),wt=1,Ut=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,jn=Ut(wt),Zn=(n,e)=>{const t=n===void 0?void 0:Math.max(n,wt);if(t!==void 0&&jn(t,e))return t},es=Ut(),ts=(n,e)=>{if(es(n,e))return n},Lt=async(n,e,t)=>{const s=n.getParameters();(s.encodings===void 0||s.encodings.length===0)&&(s.encodings=[{}]);const[r]=s.encodings,o=r.scaleResolutionDownBy,i=Zn(e.scaleResolutionDownBy,o);let c=!1;i!==void 0&&(s.encodings[0].scaleResolutionDownBy=i,c=!0);const u=r.maxBitrate,l=ts(e.maxBitrate,u);return l!==void 0&&(s.encodings[0].maxBitrate=l,c=!0),c?(t&&t(s),n.setParameters(s).then(()=>({parameters:s,isChanged:c}))):{parameters:s,isChanged:c}},ns=async(n,e,t)=>{const s=Qn(n,e);if(s)return Lt(s,{maxBitrate:t})},ss=486,rs=487,ne="local",Qe="remote",os=(n=new Error)=>{const{originator:e,cause:t}=n;return I.isCanceledError(n)?!0:typeof t=="string"?t===et||t===tt||e===ne&&(t===st||t===nt):!1},D="SipConnector",is="channels",as="WebcastStarted",cs="WebcastStopped",us="accountChanged",Es="accountDeleted",ls="addedToListModerators",_s="removedFromListModerators",ds="WebcastParticipationAccepted",Ss="WebcastParticipationRejected",hs="ParticipantMovedToWebcast",Ts="ConferenceParticipantTokenIssued";class Cs{constructor({JsSIP:e}){a(this,"_isRegisterConfig",!1);a(this,"_connectionConfiguration",{});a(this,"_remoteStreams",{});a(this,"JsSIP");a(this,"_sessionEvents");a(this,"_uaEvents");a(this,"_cancelableConnect");a(this,"_cancelableCreateUa");a(this,"_cancelableDisconnect");a(this,"_cancelableSet");a(this,"_cancelableCall");a(this,"_cancelableAnswer");a(this,"_cancelableSendDTMF");a(this,"getSipServerUrl",e=>e);a(this,"promisePendingStartPresentation");a(this,"promisePendingStopPresentation");a(this,"ua");a(this,"session");a(this,"incomingSession");a(this,"_streamPresentationCurrent");a(this,"socket");a(this,"connect",async e=>(this._cancelRequests(),this._cancelableConnect.request(e)));a(this,"createUa",async e=>this._cancelableCreateUa.request(e));a(this,"set",async e=>this._cancelableSet.request(e));a(this,"call",async e=>this._cancelableCall.request(e));a(this,"disconnect",async()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()));a(this,"answerToIncomingCall",async e=>this._cancelableAnswer.request(e));a(this,"sendDTMF",async e=>this._cancelableSendDTMF.request(e));a(this,"hangUp",async()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()));a(this,"tryRegister",async()=>{if(!this.isRegisterConfig)throw new Error("Config is not registered");this._uaEvents.trigger(Q,void 0);try{await this.unregister()}catch(e){E("tryRegister",e)}return this.register()});a(this,"declineToIncomingCall",async({statusCode:e=rs}={})=>new Promise((t,s)=>{if(!this.isAvailableIncomingCall){s(new Error("no incomingSession"));return}const r=this.incomingSession,o=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(ie,o),t(r.terminate({status_code:e}))}));a(this,"busyIncomingCall",async()=>this.declineToIncomingCall({statusCode:ss}));a(this,"removeIncomingSession",()=>{delete this.incomingSession});a(this,"handleNewRTCSession",({originator:e,session:t})=>{if(e===Qe){this.incomingSession=t;const s=this.remoteCallerData;t.on(b,r=>{this.removeIncomingSession(),r.originator===ne?this._uaEvents.trigger(ce,s):this._uaEvents.trigger(ae,s)}),this._uaEvents.trigger(oe,s)}});a(this,"_connect",async e=>this.createUa(e).then(async()=>this._start()));a(this,"_createUa",async({displayName:e="",user:t,password:s,register:r=!1,sipServerUrl:o,sipWebSocketServerURL:i,remoteAddress:c,extraHeaders:u=[],sdpSemantics:l="plan-b",sessionTimers:_=!1,registerExpires:d=60*5,connectionRecoveryMinInterval:S=2,connectionRecoveryMaxInterval:h=6,userAgent:T})=>{if(!o)throw new Error("sipServerUrl is required");if(!i)throw new Error("sipWebSocketServerURL is required");if(r&&!t)throw new Error("user is required for authorized connection");if(r&&!s)throw new Error("password is required for authorized connection");this._connectionConfiguration={sipServerUrl:o,displayName:e,register:r,user:t,password:s},this._init({sipServerUrl:o,sipWebSocketServerURL:i});const g=r&&t?t.trim():`${Xn()}`,N={password:s,register:r,display_name:Je(e),user_agent:T,sdp_semantics:l,sockets:[this.socket],uri:this.getSipServerUrl(g),session_timers:_,register_expires:d,connection_recovery_min_interval:S,connection_recovery_max_interval:h};this.ua&&await this._disconnectWithoutCancelRequests(),this._isRegisterConfig=!!N.register,this.ua=new this.JsSIP.UA(N),this._uaEvents.eachTriggers((R,m)=>{const v=ke.find(f=>f===m);v&&this.ua&&this.ua.on(v,R)});const O=[...Cn(c),...u];return this.ua.registrator().setExtraHeaders(O),this.ua});a(this,"_start",async()=>new Promise((e,t)=>{const{ua:s}=this;if(!s){t(new Error("this.ua is not initialized"));return}const r=()=>{c(),e(s)},o=u=>{c(),t(u)},i=()=>{this.isRegisterConfig?(this.on(L,r),this.on(B,o)):this.on(q,r),this.on(P,o)},c=()=>{this.off(L,r),this.off(B,o),this.off(q,r),this.off(P,o)};i(),this.on(V,this.handleNewRTCSession),s.start()}));a(this,"_set",async({displayName:e,password:t})=>new Promise((s,r)=>{const{ua:o}=this;if(!o){r(new Error("this.ua is not initialized"));return}let i=!1,c=!1;e!==void 0&&e!==this._connectionConfiguration.displayName&&(i=o.set("display_name",Je(e)),this._connectionConfiguration.displayName=e),t!==void 0&&t!==this._connectionConfiguration.password&&(c=o.set("password",t),this._connectionConfiguration.password=t);const u=i||c;c&&this.isRegisterConfig?this.register().then(()=>{s(u)}).catch(r):u?s(u):r(u)}));a(this,"_disconnectWithoutCancelRequests",async()=>this._cancelableDisconnect.request());a(this,"_disconnect",async()=>{this.off(V,this.handleNewRTCSession);const e=new Promise(t=>{this.once(P,()=>{delete this.ua,t()})});return this.ua?(await this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(P,void 0)):this._uaEvents.trigger(P,void 0),e});a(this,"_call",async({number:e,mediaStream:t,extraHeaders:s=[],ontrack:r,iceServers:o,videoMode:i,audioMode:c,degradationPreference:u,offerToReceiveAudio:l=!0,offerToReceiveVideo:_=!0})=>new Promise((d,S)=>{const{ua:h}=this;if(!h){S(new Error("this.ua is not initialized"));return}this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:r}).then(d).catch(S),this.session=h.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Z(t,{videoMode:i,audioMode:c}),eventHandlers:this._sessionEvents.triggers,videoMode:i,audioMode:c,degradationPreference:u,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:_}})}));a(this,"_answer",async({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:r,videoMode:o,audioMode:i,degradationPreference:c})=>new Promise((u,l)=>{if(!this.isAvailableIncomingCall){l(new Error("no incomingSession"));return}this.session=this.incomingSession,this.removeIncomingSession();const{session:_}=this;if(!_){l(new Error("No session established"));return}this._sessionEvents.eachTriggers((S,h)=>{const T=He.find(g=>g===h);T&&_.on(T,S)}),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=_.remote_identity.uri.user,this._handleCall({ontrack:t}).then(u).catch(l);const d=Z(e,{videoMode:o,audioMode:i});_.answer({extraHeaders:s,videoMode:o,audioMode:i,degradationPreference:c,mediaStream:d,pcConfig:{iceServers:r}})}));a(this,"_handleCall",async({ontrack:e})=>new Promise((t,s)=>{const r=()=>{this.onSession(G,_),this.onSession(Y,d)},o=()=>{this.offSession(G,_),this.offSession(Y,d)},i=()=>{this.onSession(b,u),this.onSession(F,u)},c=()=>{this.offSession(b,u),this.offSession(F,u)},u=S=>{o(),c(),s(S)};let l;const _=({peerconnection:S})=>{l=S,l.ontrack=h=>{this._sessionEvents.trigger(Ce,l),e&&e(h)}},d=()=>{l&&this._sessionEvents.trigger(Te,l),o(),c(),t(l)};r(),i()}));a(this,"_restoreSession",()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}});a(this,"_sendDTMF",async e=>new Promise((t,s)=>{const{session:r}=this;if(!r){s(new Error("No session established"));return}this.onceSession(Le,({originator:o})=>{o===ne&&t()}),r.sendDTMF(e,{duration:120,interToneGap:600})}));a(this,"_hangUpWithoutCancelRequests",async()=>{if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&await this.stopPresentation(),this._restoreSession(),e.isEnded()||e.terminate()}});a(this,"_handleShareState",e=>{switch(e){case vt:{this._sessionEvents.trigger(le,void 0);break}case bt:{this._sessionEvents.trigger(_e,void 0);break}case kn:{this._sessionEvents.trigger(de,void 0);break}}});a(this,"_maybeTriggerChannels",e=>{const t=e.getHeader(Xe),s=e.getHeader(ze);if(t&&s){const r={inputChannels:t,outputChannels:s};this._sessionEvents.trigger($,r)}});a(this,"_handleNotify",e=>{switch(e.cmd){case is:{const t=e;this._triggerChannelsNotify(t);break}case as:{const t=e;this._triggerWebcastStartedNotify(t);break}case cs:{const t=e;this._triggerWebcastStoppedNotify(t);break}case ls:{const t=e;this._triggerAddedToListModeratorsNotify(t);break}case _s:{const t=e;this._triggerRemovedFromListModeratorsNotify(t);break}case ds:{const t=e;this._triggerParticipantMoveRequestToConference(t);break}case Ss:{const t=e;this._triggerParticipantCancelingWordRequest(t);break}case hs:{const t=e;this._triggerParticipantMoveRequestToStream(t);break}case us:{this._triggerAccountChangedNotify();break}case Es:{this._triggerAccountDeletedNotify();break}case Ts:{const t=e;this._triggerConferenceParticipantTokenIssued(t);break}default:E("unknown cmd",e.cmd)}});a(this,"_triggerRemovedFromListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Oe,t)});a(this,"_triggerAddedToListModeratorsNotify",({conference:e})=>{const t={conference:e};this._uaEvents.trigger(Me,t)});a(this,"_triggerWebcastStartedNotify",({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(ve,s)});a(this,"_triggerWebcastStoppedNotify",({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(be,s)});a(this,"_triggerAccountChangedNotify",()=>{this._uaEvents.trigger(ye,void 0)});a(this,"_triggerAccountDeletedNotify",()=>{this._uaEvents.trigger(we,void 0)});a(this,"_triggerConferenceParticipantTokenIssued",({body:{conference:e,participant:t,jwt:s}})=>{const r={conference:e,participant:t,jwt:s};this._uaEvents.trigger(Ue,r)});a(this,"_triggerChannelsNotify",e=>{const t=e.input,s=e.output,r={inputChannels:t,outputChannels:s};this._uaEvents.trigger(ge,r)});a(this,"_triggerParticipantMoveRequestToConference",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(De,t)});a(this,"_triggerParticipantCancelingWordRequest",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(pe,t)});a(this,"_triggerParticipantMoveRequestToStream",({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Pe,t)});a(this,"_triggerEnterRoom",e=>{const t=e.getHeader(Nn);this._sessionEvents.trigger(Se,t)});a(this,"_triggerShareState",e=>{const t=e.getHeader(H);this._sessionEvents.trigger(W,t)});a(this,"_triggerMainCamControl",e=>{const t=e.getHeader(Dn),s=e.getHeader(Ke),r=s===K.ADMIN_SYNC_FORCED;if(t===M.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(Ae,{isSyncForced:r});else if(t===M.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(me,{isSyncForced:r});else if((t===M.RESUME_MAIN_CAM||t===M.PAUSE_MAIN_CAM)&&s)this._sessionEvents.trigger(x,{isSyncForced:r});else{const o=e.getHeader(pn);this._sessionEvents.trigger(Re,{mainCam:t,resolutionMainCam:o})}});a(this,"_triggerMicControl",e=>{const t=e.getHeader(Pn),r=e.getHeader(Ke)===K.ADMIN_SYNC_FORCED;t===z.ADMIN_START_MIC?this._sessionEvents.trigger(Ie,{isSyncForced:r}):t===z.ADMIN_STOP_MIC&&this._sessionEvents.trigger(fe,{isSyncForced:r})});a(this,"_triggerUseLicense",e=>{const t=e.getHeader(On);this._sessionEvents.trigger(he,t)});a(this,"_handleNewInfo",e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,r=s.getHeader(gn);if(r)switch(r){case Rn:{this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break}case Un:{this._maybeHandleNotify(s);break}case j:{this._triggerShareState(s);break}case Ge:{this._triggerMainCamControl(s);break}case In:{this._triggerMicControl(s);break}case Mn:{this._triggerUseLicense(s);break}}});a(this,"_handleSipEvent",({request:e})=>{this._maybeHandleNotify(e)});a(this,"_maybeHandleNotify",e=>{const t=e.getHeader(Ln);if(t){const s=JSON.parse(t);this._handleNotify(s)}});a(this,"_handleEnded",e=>{const{originator:t}=e;t===Qe&&this._sessionEvents.trigger(Ne,e),this._restoreSession()});this.JsSIP=e,this._sessionEvents=new Ye(pt),this._uaEvents=new Ye(Pt),this._cancelableConnect=new I.CancelableRequest(this._connect,{moduleName:D,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new I.CancelableRequest(this._createUa,{moduleName:D}),this._cancelableDisconnect=new I.CancelableRequest(this._disconnect,{moduleName:D}),this._cancelableSet=new I.CancelableRequest(this._set,{moduleName:D}),this._cancelableCall=new I.CancelableRequest(this._call,{moduleName:D}),this._cancelableAnswer=new I.CancelableRequest(this._answer,{moduleName:D}),this._cancelableSendDTMF=new I.CancelableRequest(this._sendDTMF,{moduleName:D}),this.onSession(W,this._handleShareState),this.onSession(Be,this._handleNewInfo),this.on(Ee,this._handleSipEvent),this.onSession(b,this._handleEnded),this.onSession(F,this._handleEnded)}async register(){return new Promise((e,t)=>{this.isRegisterConfig&&this.ua?(this.ua.on(L,e),this.ua.on(B,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(ue,e),this.ua.unregister()):t(new Error("ua is not registered"))})}async sendOptions(e,t,s){if(!this.ua)throw new Error("is not connected");return new Promise((r,o)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:o}})}catch(i){o(i)}})}async ping(e,t){var r;if(!((r=this.ua)!=null&&r.configuration.uri))throw new Error("is not connected");const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}async replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}async askPermissionToEnableCam(e={}){if(!this.session)throw new Error("No session established");const t=[Wn];return this.session.sendInfo(Ge,void 0,{noTerminateWhenError:!0,...e,extraHeaders:t}).catch(s=>{if(Jn(s))throw s})}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async _sendPresentation(e,t,{maxBitrate:s,degradationPreference:r,isNeedReinvite:o=!0,isP2P:i=!1}){const c=Z(t);this._streamPresentationCurrent=c;const u=i?[Hn]:[Bn],l=e.sendInfo(j,void 0,{extraHeaders:u}).then(async()=>e.startPresentation(c,o,r)).then(async()=>{const{connection:_}=this;if(!_||s===void 0)return;const d=_.getSenders();return ns(d,t,s)}).then(()=>t).catch(_=>{throw this._sessionEvents.trigger(X,_),_});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}async startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:r,degradationPreference:o}={}){const i=this.establishedSession;if(!i)throw new Error("No session established");if(this._streamPresentationCurrent)throw new Error("Presentation is already started");return this._sendPresentation(i,e,{isNeedReinvite:t,isP2P:s,maxBitrate:r,degradationPreference:o})}async stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve();const r=e?[qn]:[Fn],o=this.establishedSession;return o&&t&&(s=s.then(async()=>o.sendInfo(j,void 0,{extraHeaders:r})).then(async()=>o.stopPresentation(t)).catch(i=>{throw this._sessionEvents.trigger(X,i),i})),!o&&t&&this._sessionEvents.trigger(Fe,t),this.promisePendingStopPresentation=s,s.finally(()=>{this._resetPresentation()})}async updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:r}={}){const o=this.establishedSession;if(!o)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(o,e,{isP2P:t,maxBitrate:s,degradationPreference:r,isNeedReinvite:!1})}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}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:s})=>s);return zn(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,s,r,o,i;return{displayName:(t=(e=this.incomingSession)==null?void 0:e.remote_identity)==null?void 0:t.display_name,host:(r=(s=this.incomingSession)==null?void 0:s.remote_identity)==null?void 0:r.uri.host,incomingNumber:(i=(o=this.incomingSession)==null?void 0:o.remote_identity)==null?void 0:i.uri.user,session:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!!(this.ua&&this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){this.getSipServerUrl=Yn(e),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const{id:s}=e,r=this._remoteStreams[s]||new MediaStream;return t&&r.addTrack(t),r.addTrack(e),this._remoteStreams[s]=r,r}_generateAudioStream(e){const{id:t}=e,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach((s,r)=>{if(s.kind==="audio")return;const o=s,i=e[r-1];let c;i&&i.kind==="audio"&&(c=i);const u=this._generateStream(o,c);t.push(u)}),t}_generateAudioStreams(e){return e.map(s=>this._generateAudioStream(s))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}async waitChannels(){return this.waitSession($)}async waitSyncMediaState(){return this.waitSession(x)}async sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=`${Xe}: ${e}`,r=`${ze}: ${t}`,o=[s,r];return this.session.sendInfo(mn,void 0,{extraHeaders:o})}async sendMediaState({cam:e,mic:t},s={}){if(!this.session)throw new Error("No session established");const r=`${vn}: currentstate`,o=`${yn}: ${Number(e)}`,i=`${wn}: ${Number(t)}`,c=[r,o,i];return this.session.sendInfo(An,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async _sendRefusalToTurnOn(e,t={}){if(!this.session)throw new Error("No session established");const c=[`${bn}: ${e==="mic"?0:1}`];return this.session.sendInfo(fn,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})}}const Bt="purgatory",k=n=>n===Bt,Ve=n=>()=>(E("getRemoteStreams"),n.getRemoteStreams()),gs=({kind:n,readyState:e})=>n==="video"&&e==="live",Ft=n=>({track:e})=>{gs(e)&&n()},We=({getRemoteStreams:n,setRemoteStreams:e})=>Xt.debounce(()=>{const t=n();E("remoteStreams",t),t&&e(t)},200),Ns=n=>async t=>{const{mediaStream:s,extraHeaders:r,iceServers:o,degradationPreference:i,setRemoteStreams:c,onBeforeProgressCall:u,onSuccessProgressCall:l,onEnterPurgatory:_,onEnterConference:d,onFailProgressCall:S,onFinishProgressCall:h,onEndedCall:T}=t,g=We({setRemoteStreams:c,getRemoteStreams:Ve(n)}),N=Ft(g);E("answerIncomingCall",t);const p=async()=>n.answerToIncomingCall({mediaStream:s,extraHeaders:r,iceServers:o,degradationPreference:i,ontrack:N}),O=()=>{const{remoteCallerData:C}=n;return C.incomingNumber};let R=!1,m;const f=(()=>(E("subscribeEnterConference: onEnterConference",d),_??d?n.onSession("enterRoom",C=>{E("enterRoom",{_room:C,isSuccessProgressCall:R}),m=C,k(m)?_&&_():d&&d({isSuccessProgressCall:R})}):()=>{}))(),y=C=>(E("onSuccess"),R=!0,g(),l&&l({isPurgatory:k(m)}),n.onceRaceSession(["ended","failed"],()=>{f(),T&&T()}),C),w=C=>{throw E("onFail"),S&&S(),f(),C},U=()=>{E("onFinish"),h&&h()};if(E("onBeforeProgressCall"),u){const C=O();u(C)}return p().then(y).catch(w).finally(U)},Rs=n=>async t=>{const{conference:s,mediaStream:r,extraHeaders:o,iceServers:i,degradationPreference:c,setRemoteStreams:u,onBeforeProgressCall:l,onSuccessProgressCall:_,onEnterPurgatory:d,onEnterConference:S,onFailProgressCall:h,onFinishProgressCall:T,onEndedCall:g}=t,N=We({setRemoteStreams:u,getRemoteStreams:Ve(n)}),p=Ft(N);E("callToServer",t);const O=async()=>(E("startCall"),n.call({mediaStream:r,extraHeaders:o,iceServers:i,degradationPreference:c,number:s,ontrack:p}));let R=!1,m;const f=(()=>(E("subscribeEnterConference: onEnterConference",S),d??S?n.onSession("enterRoom",C=>{E("enterRoom",{_room:C,isSuccessProgressCall:R}),m=C,k(m)?d&&d():S&&S({isSuccessProgressCall:R})}):()=>{}))(),y=C=>(E("onSuccess"),R=!0,N(),_&&_({isPurgatory:k(m)}),n.onceRaceSession(["ended","failed"],()=>{f(),g&&g()}),C),w=C=>{throw E("onFail"),h&&h(),f(),C},U=()=>{E("onFinish"),T&&T()};return E("onBeforeProgressCall"),l&&l(s),O().then(y).catch(w).finally(U)},ee=n=>{if(!I.isCanceledError(n))throw n;return!1},ms=n=>async t=>{const{userAgent:s,sipWebSocketServerURL:r,sipServerUrl:o,remoteAddress:i,displayName:c,name:u,password:l,isRegisteredUser:_,sdpSemantics:d,isDisconnectOnFail:S}=t;return E("connectToServer",t),n.connect({userAgent:s,sdpSemantics:d,sipWebSocketServerURL:r,sipServerUrl:o,remoteAddress:i,displayName:c,password:l,user:u,register:_}).then(()=>(E("connectToServer then"),!0)).catch(async h=>(E("connectToServer catch: error",h),S===!0?n.disconnect().then(()=>ee(h)).catch(()=>ee(h)):ee(h)))},As=n=>async()=>(E("disconnectFromServer"),n.disconnect().then(()=>(E("disconnectFromServer: then"),!1)).catch(e=>(E("disconnectFromServer: catch",e),!1))),$e=n=>{const{url:e,cause:t}=n;let s=e;return(t===re||t===se)&&(s=`${n.message.to.uri.user}@${n.message.to.uri.host}`),s};var kt=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))(kt||{});const fs=(n=new Error)=>{var r;const{cause:e,socket:t}=n;let s="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{s="WRONG_USER_OR_PASSWORD";break}case re:{s="BAD_MEDIA_ERROR";break}case se:{s="NOT_FOUND_ERROR";break}default:t&&((r=t==null?void 0:t._ws)==null?void 0:r.readyState)===3?s="WS_CONNECTION_FAILED":$e(n)&&(s="CONNECT_SERVER_FAILED_BY_LINK")}return s},Is=(n=new Error)=>{const{code:e,cause:t,message:s}=n,r=$e(n),o={};return s&&(o.message=s),r&&(o.link=r),e&&(o.code=e),t&&(o.cause=t),o},Ms=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:kt,getLinkError:$e,getTypeFromError:fs,getValuesFromError:Is},Symbol.toStringTag,{value:"Module"})),Os=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:s,isRegistered:r,isPresentationCall:o})=>{const i=[],c=t?"0":"1",u=s?"0":"1";return i.push(`X-Vinteo-Mic-State: ${c}`,`X-Vinteo-MainCam-State: ${u}`),r||i.push("X-Vinteo-Purgatory-Call: yes"),n&&i.push(`X-Vinteo-Session: ${n}`),o&&i.push("X-Vinteo-Presentation-Call: yes"),e&&i.push(`X-Vinteo-Remote: ${e}`),i},Ds=({appName:n,appVersion:e,browserName:t,browserVersion:s})=>{const r=`${n} ${e}`;return`ChromeNew - ${t?`${t} ${s}, ${r}`:r}`},Ps=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:s,appName:r})=>n?Ds({appVersion:e,browserName:t,browserVersion:s,appName:r}):"Chrome",ps=n=>async()=>{if(n.isCallActive)return E("askPermissionToEnableCam"),n.askPermissionToEnableCam()},vs=n=>t=>(E("onMustStopPresentation"),n.onSession("mustStopPresentation",t)),bs=n=>t=>(E("onUseLicense"),n.onSession("useLicense",t)),ys=n=>async({isEnabledCam:t,isEnabledMic:s})=>{if(n.isCallActive)return E("sendMediaState"),n.sendMediaState({cam:t,mic:s})},ws=n=>async()=>{if(n.isCallActive)return E("sendRefusalToTurnOnCam"),n.sendRefusalToTurnOnCam().catch(t=>{E("sendRefusalToTurnOnCam: error",t)})},Us=n=>async()=>{if(n.isCallActive)return E("sendRefusalToTurnOnMic"),n.sendRefusalToTurnOnMic().catch(t=>{E("sendRefusalToTurnOnMic: error",t)})},Ls=1e6,Bs=({maxBitrate:n=Ls,sipConnector:e})=>async({mediaStream:s,isP2P:r=!1})=>(E("startPresentation"),e.startPresentation(s,{isP2P:r,maxBitrate:n})),Fs=({sipConnector:n})=>async({isP2P:t=!1}={})=>(E("stopShareSipConnector"),n.stopPresentation({isP2P:t}).catch(E)),ks=1e6,Hs=({sipConnector:n,maxBitrate:e=ks})=>async({mediaStream:s,isP2P:r=!1})=>(E("updatePresentation"),n.updatePresentation(s,{isP2P:r,maxBitrate:e})),qs=n=>e=>[...e].map(s=>async()=>n(s)),Vs=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const r=qs(e)(n);return zt(r,t)},Ws=n=>t=>(E("onStartMainCam"),n.onSession("admin-start-main-cam",t)),$s=n=>t=>(E("onStartMic"),n.onSession("admin-start-mic",t)),xs=n=>t=>(E("onStopMainCam"),n.onSession("admin-stop-main-cam",t)),Ys=n=>t=>(E("onStopMic"),n.onSession("admin-stop-mic",t)),Gs=({sipConnector:n})=>{const e=(T,g)=>({isSyncForced:N=!1})=>{if(N){T();return}g()},t=Ws(n),s=xs(n),r=$s(n),o=Ys(n);let i=()=>{},c=()=>{},u=()=>{},l=()=>{};const _=({onStartMainCamForced:T,onStartMainCamNotForced:g,onStopMainCamForced:N,onStopMainCamNotForced:p,onStartMicForced:O,onStartMicNotForced:R,onStopMicForced:m,onStopMicNotForced:v})=>{const f=e(T,g);i=t(f);const y=e(N,p);c=s(y);const w=e(O,R);u=r(w);const U=e(m,v);l=o(U)},d=()=>{i(),c(),u(),l()};return{start:T=>{_(T)},stop:()=>{d()}}},Xs=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:Bt,createSyncMediaState:Gs,error:Ms,getExtraHeaders:Os,getUserAgent:Ps,hasPurgatory:k,resolveAnswerIncomingCall:Ns,resolveAskPermissionToEnableCam:ps,resolveCallToServer:Rs,resolveConnectToServer:ms,resolveDisconnectFromServer:As,resolveGetRemoteStreams:Ve,resolveOnMustStopPresentation:vs,resolveOnUseLicense:bs,resolveSendMediaState:ys,resolveSendRefusalToTurnOnCam:ws,resolveSendRefusalToTurnOnMic:Us,resolveStartPresentation:Bs,resolveStopShareSipConnector:Fs,resolveUpdatePresentation:Hs,resolveUpdateRemoteStreams:We,sendDTMFAccumulated:Vs},Symbol.toStringTag,{value:"Module"})),zs=n=>[...n.keys()].map(e=>n.get(e)),Ks=(n,e)=>zs(n).find(t=>t.type===e),Ht=async n=>n.getStats().then(e=>{const t=Ks(e,"codec");return t==null?void 0:t.mimeType}),Js=n=>n.find(e=>{var t;return((t=e==null?void 0:e.track)==null?void 0:t.kind)==="video"}),qt=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Qs=1e6,A=n=>n*Qs,Vt=A(.06),js=A(4),Zs=n=>n<=64?Vt:n<=128?A(.12):n<=256?A(.25):n<=384?A(.32):n<=426?A(.38):n<=640?A(.5):n<=848?A(.7):n<=1280?A(1):n<=1920?A(2):js,er="av1",tr=n=>qt(n,er),nr=.6,Wt=(n,e)=>tr(e)?n*nr:n,sr=n=>Wt(Vt,n),$t=(n,e)=>{const t=Zs(n);return Wt(t,e)},xt=Kt(),rr=async()=>xt().catch(n=>{E("videoSendingBalancer: error",n)}),or=async n=>(xt.add(n),rr()),xe=async({sender:n,scaleResolutionDownBy:e,maxBitrate:t,onSetParameters:s})=>or(async()=>Lt(n,{scaleResolutionDownBy:e,maxBitrate:t},s)),ir=async({sender:n,codec:e},t)=>{const r=sr(e);return xe({sender:n,maxBitrate:r,onSetParameters:t,scaleResolutionDownBy:200})},te=async({sender:n,track:e,codec:t},s)=>{const i=e.getSettings().width,c=$t(i,t);return xe({sender:n,maxBitrate:c,onSetParameters:s,scaleResolutionDownBy:1})},ar=async({sender:n,track:e,resolution:t,codec:s},r)=>{const o=e.getSettings(),i=o.width,c=o.height,[u,l]=t.split("x"),_=i/Number(u),d=c/Number(l),h=Math.max(_,d,1),T=$t(Number(u),s);return xe({sender:n,maxBitrate:T,onSetParameters:r,scaleResolutionDownBy:h})},cr=async({mainCam:n,resolutionMainCam:e,sender:t,track:s,codec:r},o)=>{switch(n){case M.PAUSE_MAIN_CAM:return ir({sender:t,codec:r},o);case M.RESUME_MAIN_CAM:return te({sender:t,track:s,codec:r},o);case M.MAX_MAIN_CAM_RESOLUTION:return e!==void 0?ar({sender:t,track:s,codec:r,resolution:e},o):te({sender:t,track:s,codec:r},o);default:return te({sender:t,track:s,codec:r},o)}},je={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},Ze=async({mainCam:n,resolutionMainCam:e,connection:t,onSetParameters:s,ignoreForCodec:r})=>{const o=t.getSenders(),i=Js(o);if(!(i!=null&&i.track))return je;const c=await Ht(i);return qt(c,r)?je:cr({mainCam:n,resolutionMainCam:e,sender:i,codec:c,track:i.track},s)},ur=(n,{ignoreForCodec:e,onSetParameters:t}={})=>{const s=async()=>{const{connection:u}=n;if(!u)throw new Error("connection is not exist");return Ze({connection:u,onSetParameters:t,ignoreForCodec:e})};let r=s;const o=async u=>(r=async()=>{const{mainCam:l,resolutionMainCam:_}=u,{connection:d}=n;if(!d)throw new Error("connection is not exist");return Ze({mainCam:l,resolutionMainCam:_,connection:d,onSetParameters:t,ignoreForCodec:e})},r());return{subscribe:()=>{n.onSession("main-cam-control",o)},unsubscribe:()=>{n.offSession("main-cam-control",o)},balanceByTrack:s,resetMainCamControl(){r=s},async reBalance(){return r()}}};exports.debug=J;exports.EEventsMainCAM=M;exports.EEventsMic=z;exports.EEventsSyncMediaState=K;exports.EUseLicense=yt;exports.causes=Sn;exports.constants=hn;exports.default=Cs;exports.disableDebug=xn;exports.enableDebug=$n;exports.eventNames=Tn;exports.getCodecFromSender=Ht;exports.hasCanceledCallError=os;exports.resolveVideoSendingBalancer=ur;exports.tools=Xs;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import SipConnector from './SipConnector';
2
2
  export { hasCanceledCallError } from './SipConnector';
3
3
  export * as causes from './causes';
4
+ export * as constants from './constants';
4
5
  export * as eventNames from './eventNames';
5
6
  export { debug, disableDebug, enableDebug } from './logger';
6
7
  export * as tools from './tools';