sip-connector 16.0.1 → 16.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -168,7 +168,7 @@ unsubscribeStats();
168
168
 
169
169
  ```typescript
170
170
  // Подписка на входящие события
171
- sipConnector.on('incoming-call:incoming', () => {
171
+ sipConnector.on('incoming-call:incomingCall', () => {
172
172
  // Автоматический ответ с локальным потоком
173
173
  facade.answerToIncomingCall({
174
174
  mediaStream: localStream,
@@ -377,13 +377,15 @@ try {
377
377
 
378
378
  SDK использует **событийно-ориентированную архитектуру** с префиксами для группировки:
379
379
 
380
- | Префикс | Описание | Примеры событий |
381
- | ---------------- | ------------------- | ----------------------------- |
382
- | `connection:*` | События подключения | `connected`, `disconnected` |
383
- | `call:*` | События звонков | `accepted`, `ended`, `failed` |
384
- | `api:*` | События от сервера | `enterRoom`, `useLicense` |
385
- | `presentation:*` | События презентаций | `started`, `stopped` |
386
- | `stats:*` | События статистики | `collected` |
380
+ | Префикс | Описание | Примеры событий |
381
+ | ------------------ | ------------------------ | ----------------------------------------- |
382
+ | `connection:*` | События подключения | `connected`, `disconnected` |
383
+ | `call:*` | События звонков | `accepted`, `ended`, `failed` |
384
+ | `api:*` | События от сервера | `enterRoom`, `useLicense` |
385
+ | `incoming-call:*` | События входящих звонков | `incomingCall` |
386
+ | `presentation:*` | События презентаций | `started`, `stopped` |
387
+ | `stats:*` | События статистики | `collected` |
388
+ | `video-balancer:*` | События балансировки | `balancing-started`, `parameters-updated` |
387
389
 
388
390
  ### Основные события
389
391
 
@@ -446,14 +448,13 @@ sipConnector.on('video-balancer:balancing-stopped', () => {
446
448
  console.log('Балансировка остановлена');
447
449
  });
448
450
 
449
- sipConnector.on('video-balancer:error', (error) => {
450
- console.error('Ошибка балансировки:', error);
451
+ sipConnector.on('video-balancer:parameters-updated', (result) => {
452
+ console.log('Обновлены параметры:', result);
451
453
  });
452
454
 
453
455
  // Ручное управление балансировкой
454
- sipConnector.videoSendingBalancerManager.start(); // Принудительный запуск
455
- sipConnector.videoSendingBalancerManager.stop(); // Остановка
456
- sipConnector.videoSendingBalancerManager.restart(); // Перезапуск
456
+ sipConnector.videoSendingBalancerManager.startBalancing(); // Принудительный запуск
457
+ sipConnector.videoSendingBalancerManager.stopBalancing(); // Остановка
457
458
  ```
458
459
 
459
460
  ---
@@ -486,8 +487,11 @@ if (hasAvailableStats()) {
486
487
  console.log('Входящая статистика:', inbound);
487
488
 
488
489
  // Новая метрика availableIncomingBitrate
489
- if (inbound.availableIncomingBitrate) {
490
- console.log('Доступный входящий битрейт:', inbound.availableIncomingBitrate);
490
+ if (inbound.additional?.candidatePair?.availableIncomingBitrate) {
491
+ console.log(
492
+ 'Доступный входящий битрейт:',
493
+ inbound.additional.candidatePair.availableIncomingBitrate,
494
+ );
491
495
  }
492
496
 
493
497
  // Анализ качества соединения
@@ -586,8 +590,6 @@ const sipConnector = new SipConnector(
586
590
  {
587
591
  videoBalancerOptions: {
588
592
  ignoreForCodec: 'H264', // Игнорировать H264
589
- balancingStartDelay: 10000, // Задержка запуска (мс)
590
- pollIntervalMs: 1000, // Интервал мониторинга
591
593
  onSetParameters: (result) => {
592
594
  console.log('Параметры обновлены:', result);
593
595
  },
@@ -621,12 +623,12 @@ graph TD
621
623
 
622
624
  ### События балансировщика
623
625
 
624
- | Событие | Описание | Данные |
625
- | ------------------------------------ | -------------------------- | ------------------------------ |
626
- | `video-balancer:balancing-scheduled` | Балансировка запланирована | `{ delay: number }` |
627
- | `video-balancer:balancing-started` | Балансировка запущена | `{ delay: number }` |
628
- | `video-balancer:balancing-stopped` | Балансировка остановлена | - |
629
- | `video-balancer:parameters-updated` | Параметры обновлены | `TResultSetParametersToSender` |
626
+ | Событие | Описание | Данные |
627
+ | ------------------------------------ | -------------------------- | ---------------------- |
628
+ | `video-balancer:balancing-scheduled` | Балансировка запланирована | `{ delay: number }` |
629
+ | `video-balancer:balancing-started` | Балансировка запущена | `{ delay: number }` |
630
+ | `video-balancer:balancing-stopped` | Балансировка остановлена | - |
631
+ | `video-balancer:parameters-updated` | Параметры обновлены | `RTCRtpSendParameters` |
630
632
 
631
633
  ---
632
634
 
@@ -771,8 +773,7 @@ disableDebug();
771
773
 
772
774
  ```typescript
773
775
  // Проверка состояния подключения
774
- console.log('Подключен:', facade.connection.isConnected());
775
- console.log('Зарегистрирован:', facade.isRegistered());
776
+ console.log('Зарегистрирован:', facade.isRegistered);
776
777
 
777
778
  // Проверка конфигурации
778
779
  console.log('Настроен:', facade.isConfigured());
@@ -0,0 +1 @@
1
+ "use strict";const v=require("events-constructor"),Me=require("@krivega/cancelable-promise"),x=require("debug"),G=require("repeated-calls"),ee=require("xstate"),te=require("@krivega/timeout-requester");require("ua-parser-js");require("sequent-promises");const me=require("stack-promises");var C=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n))(C||{}),B=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(B||{});const ne=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],pe=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver"],se=[...ne,...pe],Pe=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},L=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&Pe(o,s),o};function fe(n){return e=>`sip:${e}@${n}`}const Oe=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,ie=n=>n.trim().replaceAll(" ","_"),ve=Oe(1e5,99999999),De=n=>n.some(t=>{const{kind:s}=t;return s==="video"});class ye{isPendingCall=!1;isPendingAnswer=!1;rtcSession;remoteStreams={};events;callConfiguration={};constructor(e){this.events=e}}var Q=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(Q||{});class be{remoteStreams={};reset(){this.remoteStreams={}}generateStream(e,t){const{id:s}=e,i=this.remoteStreams[s]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[s]=i,i}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,i)=>{if(s.kind==="audio")return;const r=s,a=e[i-1];let o;a?.kind==="audio"&&(o=a);const c=this.generateStream(r,o);t.push(c)}),t}generateAudioStreams(e){return e.map(t=>this.generateAudioStream(t))}}class Ue extends ye{remoteStreamsManager=new be;disposers=new Set;constructor(e){super(e),e.on(C.FAILED,this.handleEnded),e.on(C.ENDED,this.handleEnded)}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],ontrack:a,iceServers:o,directionVideo:c,directionAudio:d,contentHint:u,offerToReceiveAudio:T=!0,offerToReceiveVideo:h=!0,degradationPreference:E,sendEncodings:m,onAddedTransceiver:I})=>(this.isPendingCall=!0,new Promise((R,y)=>{this.callConfiguration.number=s,this.callConfiguration.answer=!1,this.handleCall({ontrack:a}).then(R).catch(b=>{y(b)}),this.rtcSession=e.call(t(s),{extraHeaders:r,mediaStream:L(i,{directionVideo:c,directionAudio:d,contentHint:u}),eventHandlers:this.events.triggers,directionVideo:c,directionAudio:d,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:T,offerToReceiveVideo:h},degradationPreference:E,sendEncodings:m,onAddedTransceiver:I})}).finally(()=>{this.isPendingCall=!1}));async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Q.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,ontrack:s,extraHeaders:i=[],iceServers:r,directionVideo:a,directionAudio:o,offerToReceiveAudio:c,offerToReceiveVideo:d,contentHint:u,degradationPreference:T,sendEncodings:h,onAddedTransceiver:E})=>(this.isPendingAnswer=!0,new Promise((m,I)=>{try{const R=e();this.rtcSession=R,this.subscribeToSessionEvents(R),this.callConfiguration.answer=!0,this.callConfiguration.number=R.remote_identity.uri.user,this.handleCall({ontrack:s}).then(m).catch(b=>{I(b)});const y=L(t,{directionVideo:a,directionAudio:o,contentHint:u});R.answer({extraHeaders:i,directionVideo:a,directionAudio:o,mediaStream:y,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d},degradationPreference:T,sendEncodings:h,onAddedTransceiver:E})}catch(R){I(R)}}).finally(()=>{this.isPendingAnswer=!1}));getEstablishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}getCallConfiguration(){return{...this.callConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return De(t)?this.remoteStreamsManager.generateStreams(t):this.remoteStreamsManager.generateAudioStreams(t)}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=L(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}handleCall=async({ontrack:e})=>new Promise((t,s)=>{const i=()=>{this.events.on(C.PEER_CONNECTION,u),this.events.on(C.CONFIRMED,T)},r=()=>{this.events.off(C.PEER_CONNECTION,u),this.events.off(C.CONFIRMED,T)},a=()=>{this.events.on(C.FAILED,c),this.events.on(C.ENDED,c)},o=()=>{this.events.off(C.FAILED,c),this.events.off(C.ENDED,c)},c=h=>{r(),o(),s(h)};let d;const u=({peerconnection:h})=>{d=h;const E=m=>{this.events.trigger(C.PEER_CONNECTION_ONTRACK,h),e&&e(m)};h.addEventListener("track",E),this.disposers.add(()=>{h.removeEventListener("track",E)})},T=()=>{d!==void 0&&this.events.trigger(C.PEER_CONNECTION_CONFIRMED,d),r(),o(),t(d)};i(),a()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=ne.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t===B.REMOTE&&this.events.trigger(C.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.remoteStreamsManager.reset(),this.unsubscribeFromSessionEvents(),this.callConfiguration.number=void 0,this.callConfiguration.answer=!1}}class we{events;strategy;constructor(e){this.events=new v.Events(se),this.strategy=e??new Ue(this.events)}get requested(){return this.strategy.requested}get connection(){return this.strategy.connection}get establishedRTCSession(){return this.strategy.establishedRTCSession}get isCallActive(){return this.strategy.isCallActive}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}setStrategy(e){this.strategy=e}startCall=async(...e)=>this.strategy.startCall(...e);endCall=async()=>this.strategy.endCall();answerToIncomingCall=async(...e)=>this.strategy.answerToIncomingCall(...e);getEstablishedRTCSession=()=>this.strategy.getEstablishedRTCSession();getCallConfiguration=()=>this.strategy.getCallConfiguration();getRemoteStreams=()=>this.strategy.getRemoteStreams();replaceMediaStream=async(...e)=>this.strategy.replaceMediaStream(...e)}const Y="sip-connector",A=x(Y),Le=()=>{x.enable(Y)},Be=()=>{x.enable(`-${Y}`)},ke="Error decline with 603",Fe=1006,$e=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===Fe,Ve=n=>n.message===ke;var l=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n.AVAILABLE_INCOMING_BITRATE="X-WEBRTC-AVAILABLE-INCOMING-BITRATE",n))(l||{}),F=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(F||{}),$=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n.SPECTATOR_OVER_SFU="SPECTATOROVERSFU",n))($||{}),O=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n))(O||{}),M=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.STATS="application/vinteo.webrtc.stats",n))(M||{}),P=(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))(P||{}),W=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(W||{}),H=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(H||{}),re=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(re||{}),g=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU="participant:move-request-to-spectators-over-sfu",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n))(g||{});const ae=["participation:accepting-word-request","participation:cancelling-word-request","participant:move-request-to-stream","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-spectators","participant:move-request-to-participants","participant:move-request-to-spectators-over-sfu","channels","enterRoom","shareState","main-cam-control","useLicense","admin-start-main-cam","admin-stop-main-cam","admin-start-mic","admin-stop-mic","admin-force-sync-media-state","availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","newDTMF"];var _=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(_||{});class We{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=new v.Events(ae),this.subscribe()}async waitChannels(){return this.wait(g.CHANNELS)}async waitSyncMediaState(){return this.wait(g.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let i;try{i=this.getEstablishedRTCSessionProtected()}catch(r){s(r)}i&&(this.callManager.once("newDTMF",({originator:r})=>{r===B.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${l.INPUT_CHANNELS}: ${e}`,r=`${l.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(M.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${l.MEDIA_STATE}: currentstate`,a=`${l.MAIN_CAM_STATE}: ${Number(e)}`,o=`${l.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(M.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${l.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(M.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${l.MEDIA_TYPE}: ${a}`];return s.sendInfo(M.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[l.ENABLE_MAIN_CAM];return t.sendInfo(M.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(Ve(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(l.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){A("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case _.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case _.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case _.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case _.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case _.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case _.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case _.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case _.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case _.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case _.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case _.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:A("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!==B.REMOTE)return;const{request:s}=e,i=s.getHeader(l.CONTENT_TYPE);if(i!==void 0)switch(i){case O.ENTER_ROOM:{this.triggerEnterRoom(s),this.maybeTriggerChannels(s);break}case O.NOTIFY:{this.maybeHandleNotify(s);break}case O.SHARE_STATE:{this.triggerShareState(s);break}case O.MAIN_CAM:{this.triggerMainCamControl(s);break}case O.MIC:{this.triggerMicControl(s);break}case O.USE_LICENSE:{this.triggerUseLicense(s);break}case O.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(s);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(g.ACCOUNT_CHANGED,void 0)};triggerAccountDeletedNotify=()=>{this.events.trigger(g.ACCOUNT_DELETED,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(g.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=e.getHeader(l.INPUT_CHANNELS),s=e.getHeader(l.OUTPUT_CHANNELS);if(t&&s){const i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS,i)}};triggerEnterRoom=e=>{const t=e.getHeader(l.CONTENT_ENTER_ROOM),s=e.getHeader(l.PARTICIPANT_NAME);this.events.trigger(g.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(l.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case F.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(g.AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case F.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(g.NOT_AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case F.MUST_STOP_PRESENTATION:{this.events.trigger(g.MUST_STOP_PRESENTATION,void 0);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(l.CONTENT_PARTICIPANT_STATE);t===$.SPECTATOR&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,void 0),t===$.PARTICIPANT&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,void 0),t===$.SPECTATOR_OVER_SFU&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(l.MAIN_CAM),s=e.getHeader(l.MEDIA_SYNC),i=s===H.ADMIN_SYNC_FORCED;if(t===P.ADMIN_START_MAIN_CAM){this.events.trigger(g.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===P.ADMIN_STOP_MAIN_CAM){this.events.trigger(g.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===P.RESUME_MAIN_CAM||t===P.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(g.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=e.getHeader(l.MAIN_CAM_RESOLUTION);this.events.trigger(g.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(l.MIC),i=e.getHeader(l.MEDIA_SYNC)===H.ADMIN_SYNC_FORCED;t===W.ADMIN_START_MIC?this.events.trigger(g.ADMIN_START_MIC,{isSyncForced:i}):t===W.ADMIN_STOP_MIC&&this.events.trigger(g.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(l.CONTENT_USE_LICENSE);this.events.trigger(g.USE_LICENSE,t)}}const He=(n,e)=>(n.degradationPreference=e.degradationPreference,n),qe=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},oe=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,xe=oe(),Ge=(n,e)=>{if(xe(n,e))return n},Qe=(n,e)=>{const t=n.maxBitrate,s=Ge(e,t);return s!==void 0&&(n.maxBitrate=s),n},ce=1,Ye=oe(ce),ze=(n,e)=>{const t=n===void 0?void 0:Math.max(n,ce);if(t!==void 0&&Ye(t,e))return t},Je=(n,e)=>{const t=n.scaleResolutionDownBy,s=ze(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},Xe=(n,e)=>{const t=e.encodings?.length??0;return qe(n,t),n.encodings.forEach((s,i)=>{const r=(e?.encodings??[])[i],a=r?.maxBitrate,o=r?.scaleResolutionDownBy;Qe(s,a),Je(s,o)}),n},je=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},de=async(n,e)=>{const t=n.getParameters(),s=JSON.parse(JSON.stringify(t));Xe(t,e),He(t,e);const i=je(s,t);return i&&await n.setParameters(t),{parameters:t,isChanged:i}},z=async(n,e,t)=>{const{isChanged:s,parameters:i}=await de(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(i),{isChanged:s,parameters:i}},Ke=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),Ze=async(n,e,t)=>{const s=Ke(n,e);if(s)return z(s,{maxBitrate:t})};var f=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(f||{});const he=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],et=1,tt=n=>G.hasCanceledError(n);class nt{events;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=new v.Events(he),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async startPresentation(e,t,{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:t,presentationOptions:{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{throw this.events.trigger(f.FAILED_PRESENTATION,r),r}):t&&this.events.trigger(f.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(f.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(f.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(f.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(f.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(f.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:et}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const d=L(s,{contentHint:r});if(d===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=d;const u=e().then(async()=>t.startPresentation(d,i,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(T=>{throw this.removeStreamPresentationCurrent(),this.events.trigger(f.FAILED_PRESENTATION,T),T});return this.promisePendingStartPresentation=u,u.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const i=e.getSenders();await Ze(i,t,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class st{data={};getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){return{...this.data}}set(e){this.data={...e}}update(e,t){this.data[e]=t}clear(){this.data={}}isRegister(){return this.data.register===!0}getSipServerUrl(){return this.data.sipServerUrl}getDisplayName(){return this.data.displayName}getUser(){return this.data.user}getPassword(){return this.data.password}isRegisterEnabled(){return this.data.register===!0}}var N=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n))(N||{});const ge=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],le=[...ge],it=3;class rt{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setSipServerUrl;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setSipServerUrl=e.setSipServerUrl,this.setSocket=e.setSocket}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a.displayName&&(r=i.set("display_name",ie(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{const e=new Promise(s=>{this.events.once(N.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(N.DISCONNECTED,void 0),e.finally(()=>{this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=it}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),d=r!=null&&!$e(r);return c||d};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start());initUa=async({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:d,userAgent:u,displayName:T="",register:h=!1,extraHeaders:E=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerUrl:s,displayName:T,register:h,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:I,helpers:R}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,displayName:T,register:h,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:d,userAgent:u,remoteAddress:r,extraHeaders:E},this.events);return this.setUa(I),this.setSipServerUrl(R.getSipServerUrl),this.setSocket(R.socket),I};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,d)=>{if(this.getConnectionConfiguration().register===!0)return this.registrationManager.subscribeToStartEvents(c,d);const T=N.CONNECTED,h=[N.DISCONNECTED];return this.events.on(T,c),h.forEach(E=>{this.events.on(E,d)}),()=>{this.events.off(T,c),h.forEach(E=>{this.events.off(E,d)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}}var ue=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(ue||{});const at=ee.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{A(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{A("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"idle",context:{},states:{idle:{entry:{type:"logStateChange",params:{state:"idle"}},on:{START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"idle",to:"connecting",event:"START_CONNECT"}}}}},connecting:{entry:{type:"logStateChange",params:{state:"connecting"}},on:{START_INIT_UA:{target:"initializing",actions:{type:"logTransition",params:{from:"connecting",to:"initializing",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connecting",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connecting",to:"failed",event:"CONNECTION_FAILED"}}}}},initializing:{entry:{type:"logStateChange",params:{state:"initializing"}},on:{UA_CONNECTED:{target:"connected",actions:{type:"logTransition",params:{from:"initializing",to:"connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"initializing",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"initializing",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"initializing",to:"failed",event:"CONNECTION_FAILED"}}}}},connected:{entry:{type:"logStateChange",params:{state:"connected"}},on:{UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"connected",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connected",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connected",to:"failed",event:"CONNECTION_FAILED"}}}}},registered:{entry:{type:"logStateChange",params:{state:"registered"}},on:{UA_UNREGISTERED:{target:"connected",actions:{type:"logTransition",params:{from:"registered",to:"connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"registered",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"registered",to:"failed",event:"CONNECTION_FAILED"}}}}},disconnected:{entry:{type:"logStateChange",params:{state:"disconnected"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"disconnected",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"disconnected",to:"connecting",event:"START_CONNECT"}}}}},failed:{entry:{type:"logStateChange",params:{state:"failed"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"failed",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"failed",to:"connecting",event:"START_CONNECT"}}}}}}});class ot{actor;stateChangeListeners=new Set;events;unsubscribeFromEvents;actorSubscription;constructor(e){this.events=e,this.actor=ee.createActor(at),this.actorSubscription=this.actor.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})}),this.actor.start(),this.subscribeToEvents()}get state(){return this.actor.getSnapshot().value}get isIdle(){return this.hasState("idle")}get isConnecting(){return this.hasState("connecting")}get isInitializing(){return this.hasState("initializing")}get isConnected(){return this.hasState("connected")}get isRegistered(){return this.hasState("registered")}get isDisconnected(){return this.hasState("disconnected")}get isFailed(){return this.hasState("failed")}get isPending(){return this.isConnecting||this.isInitializing}get isPendingConnect(){return this.isConnecting}get isPendingInitUa(){return this.isInitializing}get isActiveConnection(){return this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.actorSubscription?.unsubscribe(),this.actor.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return Object.values(ue).filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){const t=this.actor.getSnapshot(),s={type:e};if(!t.can(s)){A(`Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`);return}this.actor.send(s)}toStartConnect=()=>{this.sendEvent("START_CONNECT")};toStartInitUa=()=>{this.sendEvent("START_INIT_UA")};toConnected=()=>{this.sendEvent("UA_CONNECTED")};toRegistered=()=>{this.sendEvent("UA_REGISTERED")};toUnregistered=()=>{this.sendEvent("UA_UNREGISTERED")};toDisconnected=()=>{this.sendEvent("UA_DISCONNECTED")};toFailed=()=>{this.sendEvent("CONNECTION_FAILED")};toIdle=()=>{this.sendEvent("RESET")};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toFailed)}}}class ct{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(N.REGISTERED,t),e.on(N.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(N.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){A("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=N.REGISTERED,i=[N.REGISTRATION_FAILED,N.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class dt{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:d}=this.uaFactory.createConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:s}),u=this.uaFactory.createUA({...d,remoteAddress:r,extraHeaders:a}),T=()=>{const E=new Error("Telephony is not available");c(E)};u.once(N.DISCONNECTED,T);const h=()=>{u.removeAllListeners(),u.once(N.DISCONNECTED,()=>{o()}),u.stop()};u.once(N.CONNECTED,h),u.start()})}}const ht=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class D{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateConfiguration({register:e,password:t,user:s,sipServerUrl:i,sipWebSocketServerURL:r}){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${ve()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?ht(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipWebSocketServerURL:s,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:d=2,connectionRecoveryMaxInterval:u=6,userAgent:T}){D.validateConfiguration({register:a,password:t,user:e,sipServerUrl:r,sipWebSocketServerURL:s});const h=D.resolveAuthorizationUser(a,e),E=fe(r),m=E(h),I=new this.JsSIP.WebSocketInterface(s);return{configuration:{password:t,register:a,uri:m,display_name:ie(i),user_agent:T,sdpSemantics:"unified-plan",sockets:[I],session_timers:o,register_expires:c,connection_recovery_min_interval:d,connection_recovery_max_interval:u},helpers:{socket:I,getSipServerUrl:E}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=D.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=ge.find(d=>d===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}class gt{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=new v.Events(le),this.uaFactory=new D(e),this.registrationManager=new ct({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new ot(this.events),this.configurationManager=new st({getUa:this.getUa}),this.sipOperations=new dt({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new rt({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setSipServerUrl:t=>{this.getSipServerUrl=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get connectionState(){return this.stateMachine.state}get isRegistered(){return D.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.connectionFlow.connect(e,t);set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>this.connectionFlow.disconnect();async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getSipServerUrl=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua}var w=(n=>(n.INCOMING_CALL="incomingCall",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(w||{}),q=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(q||{});const Te=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],lt=486,ut=487;class Tt{events;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=new v.Events(Te),this.start()}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=ut}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(w.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:lt})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e===q.REMOTE&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator===q.LOCAL?this.events.trigger(w.TERMINATED_INCOMING_CALL,t):this.events.trigger(w.FAILED_INCOMING_CALL,t)}),this.events.trigger(w.INCOMING_CALL,t)}removeIncomingSession(){delete this.incomingRTCSession}}const U=1e3;var S=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(S||{});const Se=["collected"],X=()=>"performance"in window?performance.now():Date.now(),k=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),St=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=k(n);return{outboundRtp:e[S.OUTBOUND_RTP],codec:e[S.CODEC],mediaSource:e[S.MEDIA_SOURCE],remoteInboundRtp:e[S.REMOTE_INBOUND_RTP]}},j=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=k(n);return{outboundRtp:e[S.OUTBOUND_RTP],codec:e[S.CODEC],mediaSource:e[S.MEDIA_SOURCE],remoteInboundRtp:e[S.REMOTE_INBOUND_RTP]}},K=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=k(n);return{inboundRtp:t[S.INBOUND_RTP],codec:t[S.CODEC],synchronizationSources:e}},Et=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=k(n);return{inboundRtp:t[S.INBOUND_RTP],codec:t[S.CODEC],remoteOutboundRtp:t[S.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},Ee=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=k(n);return{candidatePair:e[S.CANDIDATE_PAIR],certificate:e[S.CERTIFICATE],localCandidate:e[S.LOCAL_CANDIDATE],remoteCandidate:e[S.REMOTE_CANDIDATE],transport:e[S.TRANSPORT]}},Ct=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:j(e),secondVideo:j(t),audio:St(n),additional:Ee(n??e??t)}),Nt=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:K({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:K({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:Et({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:Ee(n??e??t)}),At=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=Ct({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=Nt({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},Rt=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(h=>h.track?.kind===e),r=s.filter(h=>h.track?.kind===t),a=n.getReceivers(),o=a.find(h=>h.track.kind===e),c=a.filter(h=>h.track.kind===t),d={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},u={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},T={audio:d,video:u};return Promise.all([i?.getStats(),r[0]?.getStats(),r[1]?.getStats(),o?.getStats(),c[0]?.getStats(),c[1]?.getStats()]).then(h=>{const[E,m,I,R,y,b]=h;return{synchronizationSources:T,audioSenderStats:E,videoSenderFirstStats:m,videoSenderSecondStats:I,audioReceiverStats:R,videoReceiverFirstStats:y,videoReceiverSecondStats:b}})},It=n=>{A(String(n))};class Ce{events;setTimeoutRequest;requesterAllStatistics=new Me.CancelableRequest(Rt);constructor(){this.events=new v.TypedEvents(Se),this.setTimeoutRequest=new te.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=U,onError:s=It}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=X();this.requesterAllStatistics.request(e).then(i=>{this.events.trigger("collected",At(i));const a=X()-s;let o=U;a>48?o=U*4:a>32?o=U*3:a>16&&(o=U*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})}}class _t{availableIncomingBitrate;statsPeerConnection;callManager;apiManager;previousAvailableIncomingBitrate;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new Ce,this.subscribe()}get events(){return this.statsPeerConnection.events}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableIncomingBitrate=this.availableIncomingBitrate,this.availableIncomingBitrate=e.inbound.additional.candidatePair?.availableIncomingBitrate,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableIncomingBitrate=void 0,this.previousAvailableIncomingBitrate=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{A("Failed to send stats",e)})}}const Mt=(n,e)=>n.filter(s=>e.some(i=>i.clockRate===s.clockRate&&i.mimeType===s.mimeType&&i.channels===s.channels&&i.sdpFmtpLine===s.sdpFmtpLine)),mt=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,i=t===null?[]:t.codecs;return Mt(s,i)},pt=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const i=e.indexOf(t.mimeType),r=e.indexOf(s.mimeType),a=i===-1?Number.MAX_VALUE:i,o=r===-1?Number.MAX_VALUE:r;return a-o}),Pt=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),ft=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=mt("video"),i=Pt(s,t),r=pt(i,e);n.setCodecPreferences(r)}}catch(s){A("setCodecPreferences error",s)}},Ot=n=>[...n.keys()].map(e=>n.get(e)),vt=(n,e)=>Ot(n).find(t=>t?.type===e),Ne=async n=>n.getStats().then(e=>vt(e,"codec")?.mimeType);class Dt{async getCodecFromSender(e){return await Ne(e)??""}}class yt{stackPromises=me.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{A("TaskQueue: error",e)})}}class bt{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new yt}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>z(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const Ae=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Ut=1e6,p=n=>n*Ut,Re=p(.06),Ie=p(4),wt=n=>n<=64?Re:n<=128?p(.12):n<=256?p(.25):n<=384?p(.32):n<=426?p(.38):n<=640?p(.5):n<=848?p(.7):n<=1280?p(1):n<=1920?p(2):Ie,Lt="av1",Bt=n=>Ae(n,Lt),kt=.6,J=(n,e)=>Bt(e)?n*kt:n,Ft=n=>J(Re,n),$t=n=>J(Ie,n),Z=(n,e)=>{const t=wt(n);return J(t,e)},V=1,Vt=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,i=t.height,r=s===void 0?V:s/e.width,a=i===void 0?V:i/e.height;return Math.max(r,a,V)};class Wt{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},i){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=i.ignoreForCodec}async balance(e,t){const s=e.getSenders(),i=this.senderFinder.findVideoSender(s);if(!i?.track)return{...this.resultNoChanged,sender:i};const r=await this.codecProvider.getCodecFromSender(i);if(Ae(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:i};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:i,codec:r,videoTrack:i.track}).then(c=>({...c,sender:i}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:i}=e;switch(s){case P.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case P.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case P.MAX_MAIN_CAM_RESOLUTION:return i!==void 0?this.setResolutionSender(i,t):this.setBitrateByTrackResolution(t);case P.ADMIN_STOP_MAIN_CAM:case P.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,i={scaleResolutionDownBy:200,maxBitrate:Ft(s)};return this.parametersSetter.setEncodingsToSender(t,i)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:i}=e,a=s.getSettings().width,o=a===void 0?$t(i):Z(a,i);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,i]=e.split("x"),{sender:r,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(i)},d=Vt({videoTrack:a,targetSize:c}),u=Z(c.width,o),T={scaleResolutionDownBy:d,maxBitrate:u};return this.parametersSetter.setEncodingsToSender(r,T)}}const Ht=n=>n.find(e=>e.track?.kind==="video");class qt{findVideoSender(e){return Ht(e)}}class xt{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new te.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async i=>{await s(i),this.attachTrack(t,i??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:i}=t.getSettings();this.lastWidth=s,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){const s=()=>{const{width:i,height:r}=e.getSettings();i!==this.lastWidth||r!==this.lastHeight?(this.lastWidth=i,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class Gt{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}class Qt{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:i,pollIntervalMs:r}={}){this.getConnection=t,this.eventHandler=new Gt(e),this.parametersSetterWithQueue=new bt(i),this.senderBalancer=new Wt({senderFinder:new qt,codecProvider:new Dt,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new xt({pollIntervalMs:r})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{A("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{A("handleMainCamControl: error",t)})}}const _e=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"];class Yt{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=new v.TypedEvents(_e),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new Qt(t,()=>e.connection,{...s,onSetParameters:i=>{this.events.trigger("parameters-updated",i),s.onSetParameters?.(i)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{A("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const zt=1e6,Jt=le.map(n=>`connection:${n}`),Xt=se.map(n=>`call:${n}`),jt=ae.map(n=>`api:${n}`),Kt=Te.map(n=>`incoming-call:${n}`),Zt=he.map(n=>`presentation:${n}`),en=Se.map(n=>`stats:${n}`),tn=_e.map(n=>`video-balancer:${n}`),nn=[...Jt,...Xt,...jt,...Kt,...Zt,...en,...tn];class sn{events;connectionManager;callManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:i}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=new v.Events(nn),this.connectionManager=new gt({JsSIP:e}),this.callManager=new we,this.apiManager=new We({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new Tt(this.connectionManager),this.presentationManager=new nt({callManager:this.callManager,maxBitrate:zt}),this.statsManager=new _t({callManager:this.callManager,apiManager:this.apiManager}),this.videoSendingBalancerManager=new Yt(this.callManager,this.apiManager,i),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get establishedRTCSession(){return this.callManager.establishedRTCSession}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionManager.connect(...e);set=async(...e)=>this.connectionManager.set(...e);disconnect=async()=>this.connectionManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getSipServerUrl=e=>this.connectionManager.getSipServerUrl(e);call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getSipServerUrl,{...s,onAddedTransceiver:async(i,r,a)=>{this.setCodecPreferences(i),await t?.(i,r,a)}})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:async(i,r,a)=>{this.setCodecPreferences(i),await t?.(i,r,a)}})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>this.callManager.getCallConfiguration();getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:i,onAddedTransceiver:r,...a}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...a,onAddedTransceiver:async(o,c,d)=>{this.setCodecPreferences(o),await r?.(o,c,d)}},i===void 0?void 0:{callLimit:i})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{await(t===!0?this.apiManager.sendMustStopPresentationP2P():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{isP2P:s,onAddedTransceiver:i,...r}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...r,onAddedTransceiver:async(a,o,c)=>{this.setCodecPreferences(a),await i?.(a,o,c)}})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}setCodecPreferences(e){ft(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.connectionManager.events.eachTriggers((e,t)=>{this.connectionManager.on(t,s=>{this.events.trigger(`connection:${t}`,s)})}),this.callManager.events.eachTriggers((e,t)=>{this.callManager.on(t,s=>{this.events.trigger(`call:${t}`,s)})}),this.apiManager.events.eachTriggers((e,t)=>{this.apiManager.on(t,s=>{this.events.trigger(`api:${t}`,s)})}),this.incomingCallManager.events.eachTriggers((e,t)=>{this.incomingCallManager.on(t,s=>{this.events.trigger(`incoming-call:${t}`,s)})}),this.presentationManager.events.eachTriggers((e,t)=>{this.presentationManager.on(t,s=>{this.events.trigger(`presentation:${t}`,s)})}),this.statsManager.events.eachTriggers((e,t)=>{this.statsManager.on(t,s=>{this.events.trigger(`stats:${t}`,s)})}),this.videoSendingBalancerManager.events.eachTriggers((e,t)=>{this.videoSendingBalancerManager.on(t,s=>{this.events.trigger(`video-balancer:${t}`,s)})})}}exports.ECallCause=Q;exports.EStatsTypes=S;exports.EUseLicense=re;exports.Originator=B;exports.SipConnector=sn;exports.StatsPeerConnection=Ce;exports.disableDebug=Be;exports.enableDebug=Le;exports.getCodecFromSender=Ne;exports.hasCanceledStartPresentationError=tt;exports.logger=A;exports.prepareMediaStream=L;exports.setEncodingsToSender=z;exports.setParametersToSender=de;
@@ -291,7 +291,7 @@ class be extends De {
291
291
  delete this.rtcSession, this.remoteStreamsManager.reset(), this.unsubscribeFromSessionEvents(), this.callConfiguration.number = void 0, this.callConfiguration.answer = !1;
292
292
  };
293
293
  }
294
- class Ue {
294
+ class we {
295
295
  events;
296
296
  strategy;
297
297
  constructor(e) {
@@ -343,7 +343,7 @@ const G = "sip-connector", R = q(G), un = () => {
343
343
  q.enable(G);
344
344
  }, Tn = () => {
345
345
  q.enable(`-${G}`);
346
- }, we = "Error decline with 603", Le = 1006, Be = (n) => typeof n == "object" && n !== null && "code" in n && n.code === Le, ke = (n) => n.message === we;
346
+ }, Ue = "Error decline with 603", Le = 1006, Be = (n) => typeof n == "object" && n !== null && "code" in n && n.code === Le, ke = (n) => n.message === Ue;
347
347
  var l = /* @__PURE__ */ ((n) => (n.CONTENT_TYPE = "content-type", n.CONTENT_ENTER_ROOM = "x-webrtc-enter-room", n.CONTENT_USE_LICENSE = "X-WEBRTC-USE-LICENSE", n.PARTICIPANT_NAME = "X-WEBRTC-PARTICIPANT-NAME", n.INPUT_CHANNELS = "X-WEBRTC-INPUT-CHANNELS", n.OUTPUT_CHANNELS = "X-WEBRTC-OUTPUT-CHANNELS", n.MAIN_CAM = "X-WEBRTC-MAINCAM", n.MIC = "X-WEBRTC-MIC", n.MEDIA_SYNC = "X-WEBRTC-SYNC", n.MAIN_CAM_RESOLUTION = "X-WEBRTC-MAINCAM-RESOLUTION", n.MEDIA_STATE = "X-WEBRTC-MEDIA-STATE", n.MEDIA_TYPE = "X-Vinteo-Media-Type", n.MAIN_CAM_STATE = "X-Vinteo-MainCam-State", n.MIC_STATE = "X-Vinteo-Mic-State", n.CONTENT_PARTICIPANT_STATE = "X-WEBRTC-PARTSTATE", n.NOTIFY = "X-VINTEO-NOTIFY", n.CONTENT_ENABLE_MEDIA_DEVICE = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE", n.CONTENT_SHARE_STATE = "x-webrtc-share-state", n.MUST_STOP_PRESENTATION_P2P = "x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT", n.START_PRESENTATION_P2P = "x-webrtc-share-state: YOUCANRECEIVECONTENT", n.STOP_PRESENTATION_P2P = "x-webrtc-share-state: CONTENTEND", n.STOP_PRESENTATION = "x-webrtc-share-state: STOPPRESENTATION", n.START_PRESENTATION = "x-webrtc-share-state: LETMESTARTPRESENTATION", n.ENABLE_MAIN_CAM = "X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM", n.AVAILABLE_INCOMING_BITRATE = "X-WEBRTC-AVAILABLE-INCOMING-BITRATE", n))(l || {}), k = /* @__PURE__ */ ((n) => (n.AVAILABLE_SECOND_REMOTE_STREAM = "YOUCANRECEIVECONTENT", n.NOT_AVAILABLE_SECOND_REMOTE_STREAM = "CONTENTEND", n.MUST_STOP_PRESENTATION = "YOUMUSTSTOPSENDCONTENT", n))(k || {}), F = /* @__PURE__ */ ((n) => (n.SPECTATOR = "SPECTATOR", n.PARTICIPANT = "PARTICIPANT", n.SPECTATOR_OVER_SFU = "SPECTATOROVERSFU", n))(F || {}), O = /* @__PURE__ */ ((n) => (n.ENTER_ROOM = "application/vinteo.webrtc.roomname", n.MIC = "application/vinteo.webrtc.mic", n.USE_LICENSE = "application/vinteo.webrtc.uselic", n.PARTICIPANT_STATE = "application/vinteo.webrtc.partstate", n.NOTIFY = "application/vinteo.webrtc.notify", n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n))(O || {}), M = /* @__PURE__ */ ((n) => (n.CHANNELS = "application/vinteo.webrtc.channels", n.MEDIA_STATE = "application/vinteo.webrtc.mediastate", n.REFUSAL = "application/vinteo.webrtc.refusal", n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.STATS = "application/vinteo.webrtc.stats", n))(M || {}), P = /* @__PURE__ */ ((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))(P || {}), W = /* @__PURE__ */ ((n) => (n.ADMIN_STOP_MIC = "ADMINSTOPMIC", n.ADMIN_START_MIC = "ADMINSTARTMIC", n))(W || {}), H = /* @__PURE__ */ ((n) => (n.ADMIN_SYNC_FORCED = "1", n.ADMIN_SYNC_NOT_FORCED = "0", n))(H || {}), Fe = /* @__PURE__ */ ((n) => (n.AUDIO = "AUDIO", n.VIDEO = "VIDEO", n.AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION", n))(Fe || {}), g = /* @__PURE__ */ ((n) => (n.CHANNELS_NOTIFY = "channels:notify", n.PARTICIPANT_ADDED_TO_LIST_MODERATORS = "participant:added-to-list-moderators", n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS = "participant:removed-from-list-moderators", n.PARTICIPANT_MOVE_REQUEST_TO_STREAM = "participant:move-request-to-stream", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS = "participant:move-request-to-spectators", n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS = "participant:move-request-to-participants", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU = "participant:move-request-to-spectators-over-sfu", n.PARTICIPATION_ACCEPTING_WORD_REQUEST = "participation:accepting-word-request", n.PARTICIPATION_CANCELLING_WORD_REQUEST = "participation:cancelling-word-request", n.WEBCAST_STARTED = "webcast:started", n.WEBCAST_STOPPED = "webcast:stopped", n.ACCOUNT_CHANGED = "account:changed", n.ACCOUNT_DELETED = "account:deleted", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "conference:participant-token-issued", n.CHANNELS = "channels", n.ENTER_ROOM = "enterRoom", n.SHARE_STATE = "shareState", n.MAIN_CAM_CONTROL = "main-cam-control", n.USE_LICENSE = "useLicense", n.ADMIN_START_MAIN_CAM = "admin-start-main-cam", n.ADMIN_STOP_MAIN_CAM = "admin-stop-main-cam", n.ADMIN_START_MIC = "admin-start-mic", n.ADMIN_STOP_MIC = "admin-stop-mic", n.ADMIN_FORCE_SYNC_MEDIA_STATE = "admin-force-sync-media-state", n.AVAILABLE_SECOND_REMOTE_STREAM = "availableSecondRemoteStream", n.NOT_AVAILABLE_SECOND_REMOTE_STREAM = "notAvailableSecondRemoteStream", n.MUST_STOP_PRESENTATION = "mustStopPresentation", n.NEW_DTMF = "newDTMF", n))(g || {});
348
348
  const ie = [
349
349
  "participation:accepting-word-request",
@@ -900,6 +900,8 @@ class et {
900
900
  this.cancelSendPresentationWithRepeatedCalls();
901
901
  const t = this.streamPresentationCurrent;
902
902
  let s = this.promisePendingStartPresentation ?? Promise.resolve(void 0);
903
+ this.promisePendingStartPresentation && await this.promisePendingStartPresentation.catch(() => {
904
+ });
903
905
  const i = this.callManager.getEstablishedRTCSession();
904
906
  return i && t ? s = e().then(async () => i.stopPresentation(t)).catch((r) => {
905
907
  throw this.events.trigger(f.FAILED_PRESENTATION, r), r;
@@ -923,7 +925,7 @@ class et {
923
925
  }).then(async (o) => (await this.setMaxBitrate(), o));
924
926
  }
925
927
  cancelSendPresentationWithRepeatedCalls() {
926
- this.cancelableSendPresentationWithRepeatedCalls?.cancel();
928
+ this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls();
927
929
  }
928
930
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
929
931
  on(e, t) {
@@ -2033,7 +2035,7 @@ class dt {
2033
2035
  };
2034
2036
  getUa = () => this.ua;
2035
2037
  }
2036
- var w = /* @__PURE__ */ ((n) => (n.INCOMING_CALL = "incomingCall", n.DECLINED_INCOMING_CALL = "declinedIncomingCall", n.TERMINATED_INCOMING_CALL = "terminatedIncomingCall", n.FAILED_INCOMING_CALL = "failedIncomingCall", n))(w || {}), x = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))(x || {});
2038
+ var U = /* @__PURE__ */ ((n) => (n.INCOMING_CALL = "incomingCall", n.DECLINED_INCOMING_CALL = "declinedIncomingCall", n.TERMINATED_INCOMING_CALL = "terminatedIncomingCall", n.FAILED_INCOMING_CALL = "failedIncomingCall", n))(U || {}), x = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))(x || {});
2037
2039
  const le = [
2038
2040
  "incomingCall",
2039
2041
  "declinedIncomingCall",
@@ -2080,7 +2082,7 @@ class lt {
2080
2082
  return new Promise((t, s) => {
2081
2083
  try {
2082
2084
  const i = this.getIncomingRTCSession(), r = this.remoteCallerData;
2083
- this.removeIncomingSession(), this.events.trigger(w.DECLINED_INCOMING_CALL, r), i.terminate({ status_code: e }), t();
2085
+ this.removeIncomingSession(), this.events.trigger(U.DECLINED_INCOMING_CALL, r), i.terminate({ status_code: e }), t();
2084
2086
  } catch (i) {
2085
2087
  s(i);
2086
2088
  }
@@ -2124,14 +2126,14 @@ class lt {
2124
2126
  this.incomingRTCSession = e;
2125
2127
  const t = this.remoteCallerData;
2126
2128
  e.on("failed", (s) => {
2127
- this.removeIncomingSession(), s.originator === x.LOCAL ? this.events.trigger(w.TERMINATED_INCOMING_CALL, t) : this.events.trigger(w.FAILED_INCOMING_CALL, t);
2128
- }), this.events.trigger(w.INCOMING_CALL, t);
2129
+ this.removeIncomingSession(), s.originator === x.LOCAL ? this.events.trigger(U.TERMINATED_INCOMING_CALL, t) : this.events.trigger(U.FAILED_INCOMING_CALL, t);
2130
+ }), this.events.trigger(U.INCOMING_CALL, t);
2129
2131
  }
2130
2132
  removeIncomingSession() {
2131
2133
  delete this.incomingRTCSession;
2132
2134
  }
2133
2135
  }
2134
- const U = 1e3;
2136
+ const w = 1e3;
2135
2137
  var E = /* @__PURE__ */ ((n) => (n.INBOUND_RTP = "inbound-rtp", n.REMOTE_OUTBOUND_RTP = "remote-outbound-rtp", n.MEDIA_SOURCE = "media-source", n.OUTBOUND_RTP = "outbound-rtp", n.REMOTE_INBOUND_RTP = "remote-inbound-rtp", n.CODEC = "codec", n.CANDIDATE_PAIR = "candidate-pair", n.CERTIFICATE = "certificate", n.TRANSPORT = "transport", n.LOCAL_CANDIDATE = "local-candidate", n.REMOTE_CANDIDATE = "remote-candidate", n))(E || {});
2136
2138
  const ue = ["collected"], Y = () => "performance" in window ? performance.now() : Date.now(), L = (n) => [...n.keys()].reduce((e, t) => {
2137
2139
  const s = n.get(t);
@@ -2323,7 +2325,7 @@ class Rt {
2323
2325
  return this.setTimeoutRequest.requested;
2324
2326
  }
2325
2327
  start(e, {
2326
- interval: t = U,
2328
+ interval: t = w,
2327
2329
  onError: s = At
2328
2330
  } = {}) {
2329
2331
  this.stop(), this.setTimeoutRequest.request(() => {
@@ -2357,8 +2359,8 @@ class Rt {
2357
2359
  this.requesterAllStatistics.request(e).then((i) => {
2358
2360
  this.events.trigger("collected", Ct(i));
2359
2361
  const a = Y() - s;
2360
- let o = U;
2361
- a > 48 ? o = U * 4 : a > 32 ? o = U * 3 : a > 16 && (o = U * 2), this.start(e, {
2362
+ let o = w;
2363
+ a > 48 ? o = w * 4 : a > 32 ? o = w * 3 : a > 16 && (o = w * 2), this.start(e, {
2362
2364
  onError: t,
2363
2365
  interval: o
2364
2366
  });
@@ -2482,8 +2484,8 @@ class bt {
2482
2484
  this.taskQueue.stop();
2483
2485
  }
2484
2486
  }
2485
- const Se = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), Ut = 1e6, p = (n) => n * Ut, Ee = p(0.06), Ce = p(4), wt = (n) => n <= 64 ? Ee : n <= 128 ? p(0.12) : n <= 256 ? p(0.25) : n <= 384 ? p(0.32) : n <= 426 ? p(0.38) : n <= 640 ? p(0.5) : n <= 848 ? p(0.7) : n <= 1280 ? p(1) : n <= 1920 ? p(2) : Ce, Lt = "av1", Bt = (n) => Se(n, Lt), kt = 0.6, Q = (n, e) => Bt(e) ? n * kt : n, Ft = (n) => Q(Ee, n), $t = (n) => Q(Ce, n), X = (n, e) => {
2486
- const t = wt(n);
2487
+ const Se = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), wt = 1e6, p = (n) => n * wt, Ee = p(0.06), Ce = p(4), Ut = (n) => n <= 64 ? Ee : n <= 128 ? p(0.12) : n <= 256 ? p(0.25) : n <= 384 ? p(0.32) : n <= 426 ? p(0.38) : n <= 640 ? p(0.5) : n <= 848 ? p(0.7) : n <= 1280 ? p(1) : n <= 1920 ? p(2) : Ce, Lt = "av1", Bt = (n) => Se(n, Lt), kt = 0.6, Q = (n, e) => Bt(e) ? n * kt : n, Ft = (n) => Q(Ee, n), $t = (n) => Q(Ce, n), X = (n, e) => {
2488
+ const t = Ut(n);
2487
2489
  return Q(t, e);
2488
2490
  }, V = 1, Vt = ({
2489
2491
  videoTrack: n,
@@ -2869,7 +2871,7 @@ class En {
2869
2871
  excludeMimeTypesVideoCodecs: s,
2870
2872
  videoBalancerOptions: i
2871
2873
  } = {}) {
2872
- this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.events = new D(nn), this.connectionManager = new dt({ JsSIP: e }), this.callManager = new Ue(), this.apiManager = new $e({
2874
+ this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.events = new D(nn), this.connectionManager = new dt({ JsSIP: e }), this.callManager = new we(), this.apiManager = new $e({
2873
2875
  connectionManager: this.connectionManager,
2874
2876
  callManager: this.callManager
2875
2877
  }), this.incomingCallManager = new lt(this.connectionManager), this.presentationManager = new et({
@@ -105,7 +105,7 @@ declare class SipConnectorFacade implements IProxyMethods {
105
105
  directionVideo?: RTCRtpTransceiverDirection;
106
106
  directionAudio?: RTCRtpTransceiverDirection;
107
107
  setRemoteStreams: (streams: MediaStream[]) => void;
108
- onBeforeProgressCall?: (conference?: string) => void;
108
+ onBeforeProgressCall?: (conference: string) => void;
109
109
  onSuccessProgressCall?: (parameters_: {
110
110
  isPurgatory: boolean;
111
111
  }) => void;
@@ -23,10 +23,17 @@ declare class RTCSessionMock extends BaseSession {
23
23
  }], any>;
24
24
  replaceMediaStream: jest.Mock<Promise<void>, [_mediaStream: MediaStream], any>;
25
25
  private isEndedInner;
26
- constructor({ eventHandlers, originator, remoteIdentity, }: {
26
+ private readonly delayStartPresentation;
27
+ private timeoutStartPresentation?;
28
+ private timeoutConnect?;
29
+ private timeoutNewInfo?;
30
+ private timeoutAccepted?;
31
+ private timeoutConfirmed?;
32
+ constructor({ eventHandlers, originator, remoteIdentity, delayStartPresentation, }: {
27
33
  eventHandlers: TEventHandlers;
28
34
  originator: string;
29
35
  remoteIdentity?: NameAddrHeader;
36
+ delayStartPresentation?: number;
30
37
  });
31
38
  static setPresentationError(presentationError: Error): void;
32
39
  static resetPresentationError(): void;
@@ -75,5 +82,6 @@ declare class RTCSessionMock extends BaseSession {
75
82
  sendInfo(): Promise<void>;
76
83
  isEnded(): boolean;
77
84
  newInfo(data: IncomingInfoEvent): void;
85
+ clear(): void;
78
86
  }
79
87
  export default RTCSessionMock;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("node:events"),V=require("@krivega/jssip/lib/NameAddrHeader"),k=require("@krivega/jssip/lib/URI"),U=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),P=require("./@SipConnector-DcaeAFrM.cjs");class N extends U.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const H="incomingCall",q="declinedIncomingCall",G="failedIncomingCall",x="terminatedIncomingCall",v="connecting",z="connected",j="disconnected",Y="newRTCSession",B="registered",K="unregistered",J="registrationFailed",$="newMessage",Q="sipEvent",X="availableSecondRemoteStream",Z="notAvailableSecondRemoteStream",ee="mustStopPresentation",te="shareState",re="enterRoom",ne="useLicense",oe="peerconnection:confirmed",se="peerconnection:ontrack",ie="channels",ae="channels:notify",ce="ended:fromserver",de="main-cam-control",Ee="admin-stop-main-cam",he="admin-start-main-cam",ue="admin-stop-mic",me="admin-start-mic",le="admin-force-sync-media-state",pe="participant:added-to-list-moderators",ge="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",Te="participant:move-request-to-spectators",Ie="participant:move-request-to-participants",Se="participation:accepting-word-request",Ne="participation:cancelling-word-request",we="webcast:started",Ce="webcast:stopped",Re="account:changed",fe="account:deleted",Ae="conference:participant-token-issued",Me="ended",Oe="sending",Pe="reinvite",ve="replaces",De="refer",ye="progress",Le="accepted",Fe="confirmed",We="peerconnection",be="failed",Ve="muted",ke="unmuted",Ue="newDTMF",He="newInfo",qe="hold",Ge="unhold",xe="update",ze="sdp",je="icecandidate",Ye="getusermediafailed",Be="peerconnection:createofferfailed",Ke="peerconnection:createanswerfailed",Je="peerconnection:setlocaldescriptionfailed",$e="peerconnection:setremotedescriptionfailed",Qe="presentation:start",Xe="presentation:started",Ze="presentation:end",et="presentation:ended",tt="presentation:failed",rt=[H,q,x,G,Se,Ne,_e,ae,Ae,Re,fe,we,Ce,pe,ge],D=[v,z,j,Y,B,K,J,$,Q],nt=[X,Z,ee,te,re,ne,oe,se,ie,ce,de,he,Ee,ue,me,le,Te,Ie],_=[Me,v,Oe,Pe,ve,De,ye,Le,Fe,We,be,Ve,ke,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt];[...D,...rt];[..._,...nt];class ot{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),this.initEvents(t),this.remote_identity=r}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return _.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class st{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}const it=["track"];class at{senders=[];receivers=[];canTrickleIceCandidates;connectionState;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState;events;constructor(e,t){this.events=new S.Events(it),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,r){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=e=>{const t=new st({track:e});return this.senders.push(t),this.events.trigger("track",{track:e}),t}}function ct(n){const e=n.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const A=400,y="777",dt=n=>n.getVideoTracks().length>0;class i extends ot{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;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)},A)});replaceMediaStream=jest.fn(async e=>{});isEndedInner=!1;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1")}){super({originator:t,eventHandlers:e,remoteIdentity:r})}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>{if(i.countStartsPresentation+=1,i.presentationError)throw this.trigger("presentation:start",e),this.trigger("presentation:failed",e),i.presentationError;if(i.startPresentationError&&i.countStartsPresentation<i.countStartPresentationError)throw this.trigger("presentation:start",e),this.trigger("presentation:failed",e),i.startPresentationError;return super.startPresentation(e)};stopPresentation=async e=>{if(i.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),i.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(dt(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new at(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=ct(e);return this.initPeerconnection(t),setTimeout(()=>{e.includes(y)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),setTimeout(()=>{this.newInfo({originator:P.Originator.REMOTE,request:{getHeader:s=>s==="content-type"?"application/vinteo.webrtc.roomname":s==="x-webrtc-enter-room"?r:s==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),setTimeout(()=>{this.trigger("accepted")},200),setTimeout(()=>{this.trigger("confirmed")},300))},A),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t&&t.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t&&t.kind==="video"&&(t.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}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",L="NAME_INCORRECT",h=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},M={status_code:200,reason_phrase:"OK"},O={status_code:401,reason_phrase:"Unauthorized"};class o{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:s}=t;return this.session=new i({eventHandlers:s,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(o.countStarts+=1,o.startError&&o.countStarts<o.countStartError){this.trigger("disconnected",o.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},h):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new S.Events(D);const[t,r]=e.uri.split(":"),[s,c]=r.split("@"),p={...e,uri:new a.URI(t,s,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){o.startError=e,o.countStartError=t}static resetStartError(){o.startError=void 0,o.countStartError=Number.POSITIVE_INFINITY,o.countStarts=0}static setAvailableTelephony(){o.isAvailableTelephony=!0}static setNotAvailableTelephony(){o.isAvailableTelephony=!1}static reset(){o.resetStartError(),o.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(L)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:M})},h)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)),o.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:M})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ht{url;constructor(e){this.url=e}}class ut extends b.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",mt=(n,e)=>{const t=new N(e),r={originator:I,request:t,info:new ut("","")};n.newInfo(r)},lt=(n,e)=>{const r={event:"sipEvent",request:new N(e)};n.newSipEvent(r)},pt=(n,{incomingNumber:e="1234",displayName:t,host:r})=>{const s=new i({originator:I,eventHandlers:{}}),c=new k("sip",e,r);s.remote_identity=new V(c,t);const p=new N([]);n.trigger("newRTCSession",{originator:I,session:s,request:p})},gt=(n,e)=>{e?n.trigger("failed",e):n.trigger("failed",n)},w={triggerNewInfo:mt,triggerNewSipEvent:lt,triggerIncomingSession:pt,triggerFailIncomingSession:gt,WebSocketInterface:ht,UA:o,C:{INVITE:"INVITE"}},u="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",_t=new w.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},Tt={...R},F={...R,user:u,password:d,register:!0},It={...F,displayName:E},St={...R,displayName:E,register:!1},l={session_timers:!1,sockets:[_t],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"",register:!0},wt={...l,password:d,uri:new a.URI("sip",u,m),display_name:E,register:!0},Ct={...l,display_name:E,register:!1},Rt={...l,display_name:"",register:!1},W="10.10.10.10",ft=[`X-Vinteo-Remote: ${W}`],At=()=>new P.SipConnector({JsSIP:w});exports.FAILED_CONFERENCE_NUMBER=y;exports.JsSIP=w;exports.NAME_INCORRECT=L;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=F;exports.dataForConnectionWithAuthorizationWithDisplayName=It;exports.dataForConnectionWithoutAuthorization=St;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Tt;exports.displayName=E;exports.doMockSipConnector=At;exports.extraHeadersRemoteAddress=ft;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=wt;exports.uaConfigurationWithoutAuthorization=Ct;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=Rt;exports.user=u;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("node:events"),V=require("@krivega/jssip/lib/NameAddrHeader"),k=require("@krivega/jssip/lib/URI"),U=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),P=require("./@SipConnector-BjWfal-x.cjs");class N extends U.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const H="incomingCall",q="declinedIncomingCall",G="failedIncomingCall",x="terminatedIncomingCall",v="connecting",z="connected",j="disconnected",Y="newRTCSession",B="registered",K="unregistered",J="registrationFailed",$="newMessage",Q="sipEvent",X="availableSecondRemoteStream",Z="notAvailableSecondRemoteStream",ee="mustStopPresentation",te="shareState",re="enterRoom",ne="useLicense",oe="peerconnection:confirmed",ie="peerconnection:ontrack",se="channels",ae="channels:notify",ce="ended:fromserver",de="main-cam-control",Ee="admin-stop-main-cam",he="admin-start-main-cam",ue="admin-stop-mic",me="admin-start-mic",le="admin-force-sync-media-state",pe="participant:added-to-list-moderators",ge="participant:removed-from-list-moderators",_e="participant:move-request-to-stream",Te="participant:move-request-to-spectators",Ie="participant:move-request-to-participants",Se="participation:accepting-word-request",Ne="participation:cancelling-word-request",we="webcast:started",Ce="webcast:stopped",Re="account:changed",fe="account:deleted",Ae="conference:participant-token-issued",Me="ended",Oe="sending",Pe="reinvite",ve="replaces",De="refer",ye="progress",Le="accepted",Fe="confirmed",We="peerconnection",be="failed",Ve="muted",ke="unmuted",Ue="newDTMF",He="newInfo",qe="hold",Ge="unhold",xe="update",ze="sdp",je="icecandidate",Ye="getusermediafailed",Be="peerconnection:createofferfailed",Ke="peerconnection:createanswerfailed",Je="peerconnection:setlocaldescriptionfailed",$e="peerconnection:setremotedescriptionfailed",Qe="presentation:start",Xe="presentation:started",Ze="presentation:end",et="presentation:ended",tt="presentation:failed",rt=[H,q,x,G,Se,Ne,_e,ae,Ae,Re,fe,we,Ce,pe,ge],D=[v,z,j,Y,B,K,J,$,Q],nt=[X,Z,ee,te,re,ne,oe,ie,se,ce,de,he,Ee,ue,me,le,Te,Ie],_=[Me,v,Oe,Pe,ve,De,ye,Le,Fe,We,be,Ve,ke,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt];[...D,...rt];[..._,...nt];class ot{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),this.initEvents(t),this.remote_identity=r}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return _.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class it{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}const st=["track"];class at{senders=[];receivers=[];canTrickleIceCandidates;connectionState;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState;events;constructor(e,t){this.events=new S.Events(st),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,r){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=e=>{const t=new it({track:e});return this.senders.push(t),this.events.trigger("track",{track:e}),t}}function ct(n){const e=n.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const A=400,y="777",dt=n=>n.getVideoTracks().length>0;class s extends ot{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;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)},A)});replaceMediaStream=jest.fn(async e=>{});isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:i=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=i}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(dt(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new at(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=ct(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(y)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:P.Originator.REMOTE,request:{getHeader:i=>i==="content-type"?"application/vinteo.webrtc.roomname":i==="x-webrtc-enter-room"?r:i==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},A),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t&&t.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t&&t.kind==="video"&&(t.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}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",L="NAME_INCORRECT",h=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},M={status_code:200,reason_phrase:"OK"},O={status_code:401,reason_phrase:"Unauthorized"};class o{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:i}=t;return this.session=new s({eventHandlers:i,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(o.countStarts+=1,o.startError&&o.countStarts<o.countStartError){this.trigger("disconnected",o.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},h):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new S.Events(D);const[t,r]=e.uri.split(":"),[i,c]=r.split("@"),p={...e,uri:new a.URI(t,i,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){o.startError=e,o.countStartError=t}static resetStartError(){o.startError=void 0,o.countStartError=Number.POSITIVE_INFINITY,o.countStarts=0}static setAvailableTelephony(){o.isAvailableTelephony=!0}static setNotAvailableTelephony(){o.isAvailableTelephony=!1}static reset(){o.resetStartError(),o.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(L)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:M})},h)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:O,cause:a.C.causes.REJECTED})},h)),o.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:M})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ht{url;constructor(e){this.url=e}}class ut extends b.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",mt=(n,e)=>{const t=new N(e),r={originator:I,request:t,info:new ut("","")};n.newInfo(r)},lt=(n,e)=>{const r={event:"sipEvent",request:new N(e)};n.newSipEvent(r)},pt=(n,{incomingNumber:e="1234",displayName:t,host:r})=>{const i=new s({originator:I,eventHandlers:{}}),c=new k("sip",e,r);i.remote_identity=new V(c,t);const p=new N([]);n.trigger("newRTCSession",{originator:I,session:i,request:p})},gt=(n,e)=>{e?n.trigger("failed",e):n.trigger("failed",n)},w={triggerNewInfo:mt,triggerNewSipEvent:lt,triggerIncomingSession:pt,triggerFailIncomingSession:gt,WebSocketInterface:ht,UA:o,C:{INVITE:"INVITE"}},u="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",_t=new w.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},Tt={...R},F={...R,user:u,password:d,register:!0},It={...F,displayName:E},St={...R,displayName:E,register:!1},l={session_timers:!1,sockets:[_t],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"",register:!0},wt={...l,password:d,uri:new a.URI("sip",u,m),display_name:E,register:!0},Ct={...l,display_name:E,register:!1},Rt={...l,display_name:"",register:!1},W="10.10.10.10",ft=[`X-Vinteo-Remote: ${W}`],At=()=>new P.SipConnector({JsSIP:w});exports.FAILED_CONFERENCE_NUMBER=y;exports.JsSIP=w;exports.NAME_INCORRECT=L;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=F;exports.dataForConnectionWithAuthorizationWithDisplayName=It;exports.dataForConnectionWithoutAuthorization=St;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=Tt;exports.displayName=E;exports.doMockSipConnector=At;exports.extraHeadersRemoteAddress=ft;exports.remoteAddress=W;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=wt;exports.uaConfigurationWithoutAuthorization=Ct;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=Rt;exports.user=u;
package/dist/doMock.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { EventEmitter as D } from "node:events";
2
- import L from "@krivega/jssip/lib/NameAddrHeader";
3
- import y from "@krivega/jssip/lib/URI";
2
+ import y from "@krivega/jssip/lib/NameAddrHeader";
3
+ import L from "@krivega/jssip/lib/URI";
4
4
  import { IncomingRequest as F } from "@krivega/jssip/lib/SIPMessage";
5
5
  import { NameAddrHeader as b, URI as E, C as N } from "@krivega/jssip";
6
6
  import { createAudioMediaStreamTrackMock as V, createVideoMediaStreamTrackMock as k } from "webrtc-mock";
7
- import { Events as _ } from "events-constructor";
8
- import { O as W, S as U } from "./@SipConnector-uiUlVCMv.js";
9
- class T extends F {
7
+ import { Events as T } from "events-constructor";
8
+ import { O as W, S as U } from "./@SipConnector-CoBe6WQF.js";
9
+ class _ extends F {
10
10
  headers;
11
11
  constructor(e) {
12
12
  super(), this.headers = new Headers(e);
@@ -15,14 +15,14 @@ class T extends F {
15
15
  return this.headers.get(e) ?? "";
16
16
  }
17
17
  }
18
- const G = "incomingCall", H = "declinedIncomingCall", x = "failedIncomingCall", q = "terminatedIncomingCall", A = "connecting", Y = "connected", j = "disconnected", z = "newRTCSession", B = "registered", $ = "unregistered", J = "registrationFailed", K = "newMessage", Q = "sipEvent", X = "availableSecondRemoteStream", Z = "notAvailableSecondRemoteStream", ee = "mustStopPresentation", te = "shareState", re = "enterRoom", ne = "useLicense", oe = "peerconnection:confirmed", se = "peerconnection:ontrack", ie = "channels", ae = "channels:notify", ce = "ended:fromserver", de = "main-cam-control", Ee = "admin-stop-main-cam", he = "admin-start-main-cam", me = "admin-stop-mic", le = "admin-start-mic", ue = "admin-force-sync-media-state", pe = "participant:added-to-list-moderators", ge = "participant:removed-from-list-moderators", _e = "participant:move-request-to-stream", Te = "participant:move-request-to-spectators", Ie = "participant:move-request-to-participants", we = "participation:accepting-word-request", Se = "participation:cancelling-word-request", Ne = "webcast:started", fe = "webcast:stopped", Ce = "account:changed", Re = "account:deleted", Me = "conference:participant-token-issued", Ae = "ended", Oe = "sending", Pe = "reinvite", ve = "replaces", De = "refer", Le = "progress", ye = "accepted", Fe = "confirmed", be = "peerconnection", Ve = "failed", ke = "muted", We = "unmuted", Ue = "newDTMF", Ge = "newInfo", He = "hold", xe = "unhold", qe = "update", Ye = "sdp", je = "icecandidate", ze = "getusermediafailed", Be = "peerconnection:createofferfailed", $e = "peerconnection:createanswerfailed", Je = "peerconnection:setlocaldescriptionfailed", Ke = "peerconnection:setremotedescriptionfailed", Qe = "presentation:start", Xe = "presentation:started", Ze = "presentation:end", et = "presentation:ended", tt = "presentation:failed", rt = [
18
+ const G = "incomingCall", H = "declinedIncomingCall", x = "failedIncomingCall", q = "terminatedIncomingCall", A = "connecting", Y = "connected", j = "disconnected", z = "newRTCSession", B = "registered", $ = "unregistered", J = "registrationFailed", K = "newMessage", Q = "sipEvent", X = "availableSecondRemoteStream", Z = "notAvailableSecondRemoteStream", ee = "mustStopPresentation", te = "shareState", re = "enterRoom", ne = "useLicense", oe = "peerconnection:confirmed", se = "peerconnection:ontrack", ie = "channels", ae = "channels:notify", ce = "ended:fromserver", de = "main-cam-control", Ee = "admin-stop-main-cam", he = "admin-start-main-cam", me = "admin-stop-mic", ue = "admin-start-mic", le = "admin-force-sync-media-state", pe = "participant:added-to-list-moderators", ge = "participant:removed-from-list-moderators", Te = "participant:move-request-to-stream", _e = "participant:move-request-to-spectators", Ie = "participant:move-request-to-participants", Se = "participation:accepting-word-request", we = "participation:cancelling-word-request", Ne = "webcast:started", fe = "webcast:stopped", Ce = "account:changed", Re = "account:deleted", Me = "conference:participant-token-issued", Ae = "ended", Oe = "sending", Pe = "reinvite", ve = "replaces", De = "refer", ye = "progress", Le = "accepted", Fe = "confirmed", be = "peerconnection", Ve = "failed", ke = "muted", We = "unmuted", Ue = "newDTMF", Ge = "newInfo", He = "hold", xe = "unhold", qe = "update", Ye = "sdp", je = "icecandidate", ze = "getusermediafailed", Be = "peerconnection:createofferfailed", $e = "peerconnection:createanswerfailed", Je = "peerconnection:setlocaldescriptionfailed", Ke = "peerconnection:setremotedescriptionfailed", Qe = "presentation:start", Xe = "presentation:started", Ze = "presentation:end", et = "presentation:ended", tt = "presentation:failed", rt = [
19
19
  G,
20
20
  H,
21
21
  q,
22
22
  x,
23
- we,
24
23
  Se,
25
- _e,
24
+ we,
25
+ Te,
26
26
  ae,
27
27
  Me,
28
28
  Ce,
@@ -56,9 +56,9 @@ const G = "incomingCall", H = "declinedIncomingCall", x = "failedIncomingCall",
56
56
  he,
57
57
  Ee,
58
58
  me,
59
- le,
60
59
  ue,
61
- Te,
60
+ le,
61
+ _e,
62
62
  Ie
63
63
  ], p = [
64
64
  Ae,
@@ -67,8 +67,8 @@ const G = "incomingCall", H = "declinedIncomingCall", x = "failedIncomingCall",
67
67
  Pe,
68
68
  ve,
69
69
  De,
70
- Le,
71
70
  ye,
71
+ Le,
72
72
  Fe,
73
73
  be,
74
74
  Ve,
@@ -108,7 +108,7 @@ class ot {
108
108
  eventHandlers: t,
109
109
  remoteIdentity: r
110
110
  }) {
111
- this.originator = e, this.events = new _(p), this.initEvents(t), this.remote_identity = r;
111
+ this.originator = e, this.events = new T(p), this.initEvents(t), this.remote_identity = r;
112
112
  }
113
113
  get contact() {
114
114
  throw new Error("Method not implemented.");
@@ -343,7 +343,7 @@ class at {
343
343
  signalingState;
344
344
  events;
345
345
  constructor(e, t) {
346
- this.events = new _(it), this.receivers = t.map((r) => ({ track: r }));
346
+ this.events = new T(it), this.receivers = t.map((r) => ({ track: r }));
347
347
  }
348
348
  getRemoteStreams() {
349
349
  throw new Error("Method not implemented.");
@@ -446,15 +446,22 @@ class i extends ot {
446
446
  replaceMediaStream = jest.fn(async (e) => {
447
447
  });
448
448
  isEndedInner = !1;
449
+ delayStartPresentation = 0;
450
+ timeoutStartPresentation;
451
+ timeoutConnect;
452
+ timeoutNewInfo;
453
+ timeoutAccepted;
454
+ timeoutConfirmed;
449
455
  constructor({
450
456
  eventHandlers: e,
451
457
  originator: t,
452
458
  remoteIdentity: r = new b(
453
459
  new E("sip", "caller1", "test1.com", 5060),
454
460
  "Test Caller 1"
455
- )
461
+ ),
462
+ delayStartPresentation: s = 0
456
463
  }) {
457
- super({ originator: t, eventHandlers: e, remoteIdentity: r });
464
+ super({ originator: t, eventHandlers: e, remoteIdentity: r }), this.delayStartPresentation = s;
458
465
  }
459
466
  static setPresentationError(e) {
460
467
  this.presentationError = e;
@@ -468,13 +475,19 @@ class i extends ot {
468
475
  static resetStartPresentationError() {
469
476
  this.startPresentationError = void 0, this.countStartPresentationError = Number.POSITIVE_INFINITY, this.countStartsPresentation = 0;
470
477
  }
471
- startPresentation = async (e) => {
472
- if (i.countStartsPresentation += 1, i.presentationError)
473
- throw this.trigger("presentation:start", e), this.trigger("presentation:failed", e), i.presentationError;
474
- if (i.startPresentationError && i.countStartsPresentation < i.countStartPresentationError)
475
- throw this.trigger("presentation:start", e), this.trigger("presentation:failed", e), i.startPresentationError;
476
- return super.startPresentation(e);
477
- };
478
+ startPresentation = async (e) => (i.countStartsPresentation += 1, new Promise((t, r) => {
479
+ this.timeoutStartPresentation = setTimeout(() => {
480
+ if (i.presentationError) {
481
+ this.trigger("presentation:start", e), this.trigger("presentation:failed", e), r(i.presentationError);
482
+ return;
483
+ }
484
+ if (i.startPresentationError && i.countStartsPresentation < i.countStartPresentationError) {
485
+ this.trigger("presentation:start", e), this.trigger("presentation:failed", e), r(i.startPresentationError);
486
+ return;
487
+ }
488
+ t(super.startPresentation(e));
489
+ }, this.delayStartPresentation);
490
+ }));
478
491
  stopPresentation = async (e) => {
479
492
  if (i.presentationError)
480
493
  throw this.trigger("presentation:end", e), this.trigger("presentation:failed", e), i.presentationError;
@@ -495,12 +508,12 @@ class i extends ot {
495
508
  }
496
509
  connect(e, { mediaStream: t } = {}) {
497
510
  const r = ct(e);
498
- return this.initPeerconnection(t), setTimeout(() => {
511
+ return this.initPeerconnection(t), this.timeoutConnect = setTimeout(() => {
499
512
  e.includes(dt) ? this.trigger("failed", {
500
513
  originator: "remote",
501
514
  message: "IncomingResponse",
502
515
  cause: "Rejected"
503
- }) : (this.trigger("connecting"), setTimeout(() => {
516
+ }) : (this.trigger("connecting"), this.timeoutNewInfo = setTimeout(() => {
504
517
  this.newInfo({
505
518
  originator: W.REMOTE,
506
519
  // @ts-expect-error
@@ -508,9 +521,9 @@ class i extends ot {
508
521
  getHeader: (s) => s === "content-type" ? "application/vinteo.webrtc.roomname" : s === "x-webrtc-enter-room" ? r : s === "x-webrtc-participant-name" ? "Test Caller 1" : ""
509
522
  }
510
523
  });
511
- }, 100), setTimeout(() => {
524
+ }, 100), this.timeoutAccepted = setTimeout(() => {
512
525
  this.trigger("accepted");
513
- }, 200), setTimeout(() => {
526
+ }, 200), this.timeoutConfirmed = setTimeout(() => {
514
527
  this.trigger("confirmed");
515
528
  }, 300));
516
529
  }, f), this.connection;
@@ -573,6 +586,9 @@ class i extends ot {
573
586
  newInfo(e) {
574
587
  this.trigger("newInfo", e);
575
588
  }
589
+ clear() {
590
+ clearTimeout(this.timeoutStartPresentation), clearTimeout(this.timeoutConnect), clearTimeout(this.timeoutNewInfo), clearTimeout(this.timeoutAccepted), clearTimeout(this.timeoutConfirmed);
591
+ }
576
592
  /* eslint-enable no-param-reassign */
577
593
  }
578
594
  class ht {
@@ -584,7 +600,7 @@ class ht {
584
600
  setExtraContactParams() {
585
601
  }
586
602
  }
587
- const c = "PASSWORD_CORRECT", C = "PASSWORD_CORRECT_2", mt = "NAME_INCORRECT", d = 400, u = {
603
+ const c = "PASSWORD_CORRECT", C = "PASSWORD_CORRECT_2", mt = "NAME_INCORRECT", d = 400, l = {
588
604
  url: "wss://sipServerUrl/webrtc/wss/",
589
605
  sip_uri: "sip:sipServerUrl;transport=ws",
590
606
  via_transport: "WSS"
@@ -629,8 +645,8 @@ class o {
629
645
  */
630
646
  stop = jest.fn(() => {
631
647
  this.startedTimeout && clearTimeout(this.startedTimeout), this.stopedTimeout && clearTimeout(this.stopedTimeout), this.unregister(), this.isStarted() ? this.stopedTimeout = setTimeout(() => {
632
- this.trigger("disconnected", { error: !0, socket: u });
633
- }, d) : this.trigger("disconnected", { error: !0, socket: u });
648
+ this.trigger("disconnected", { error: !0, socket: l });
649
+ }, d) : this.trigger("disconnected", { error: !0, socket: l });
634
650
  });
635
651
  removeAllListeners = jest.fn(() => (this.events.removeEventHandlers(), this));
636
652
  once = jest.fn((e, t) => (this.events.once(e, t), this));
@@ -641,12 +657,12 @@ class o {
641
657
  isConnectedInner;
642
658
  configuration;
643
659
  constructor(e) {
644
- this.events = new _(O);
645
- const [t, r] = e.uri.split(":"), [s, a] = r.split("@"), l = {
660
+ this.events = new T(O);
661
+ const [t, r] = e.uri.split(":"), [s, a] = r.split("@"), u = {
646
662
  ...e,
647
663
  uri: new E(t, s, a)
648
664
  };
649
- this.configuration = l, this.registratorInner = new ht();
665
+ this.configuration = u, this.registratorInner = new ht();
650
666
  }
651
667
  static setStartError(e, { count: t = Number.POSITIVE_INFINITY } = {}) {
652
668
  o.startError = e, o.countStartError = t;
@@ -697,7 +713,7 @@ class o {
697
713
  this.trigger("registered", { response: R });
698
714
  }, d)) : t === !0 && e !== c && e !== C && (this.isRegisteredInner = !1, this.isConnectedInner = !1, this.startedTimeout = setTimeout(() => {
699
715
  this.trigger("registrationFailed", { response: M, cause: N.causes.REJECTED });
700
- }, d)), o.isAvailableTelephony ? (this.trigger("connected", { socket: u }), this.isConnectedInner = !0) : this.stop();
716
+ }, d)), o.isAvailableTelephony ? (this.trigger("connected", { socket: l }), this.isConnectedInner = !0) : this.stop();
701
717
  }
702
718
  /**
703
719
  * unregister
@@ -728,13 +744,13 @@ class o {
728
744
  return this.registratorInner;
729
745
  }
730
746
  }
731
- class lt {
747
+ class ut {
732
748
  url;
733
749
  constructor(e) {
734
750
  this.url = e;
735
751
  }
736
752
  }
737
- class ut extends D {
753
+ class lt extends D {
738
754
  contentType;
739
755
  body;
740
756
  constructor(e, t) {
@@ -742,56 +758,56 @@ class ut extends D {
742
758
  }
743
759
  }
744
760
  const g = "remote", pt = (n, e) => {
745
- const t = new T(e), r = {
761
+ const t = new _(e), r = {
746
762
  originator: g,
747
763
  request: t,
748
- info: new ut("", "")
764
+ info: new lt("", "")
749
765
  };
750
766
  n.newInfo(r);
751
767
  }, gt = (n, e) => {
752
- const r = { event: "sipEvent", request: new T(e) };
768
+ const r = { event: "sipEvent", request: new _(e) };
753
769
  n.newSipEvent(r);
754
- }, _t = (n, {
770
+ }, Tt = (n, {
755
771
  incomingNumber: e = "1234",
756
772
  displayName: t,
757
773
  host: r
758
774
  }) => {
759
- const s = new i({ originator: g, eventHandlers: {} }), a = new y("sip", e, r);
760
- s.remote_identity = new L(a, t);
761
- const l = new T([]);
775
+ const s = new i({ originator: g, eventHandlers: {} }), a = new L("sip", e, r);
776
+ s.remote_identity = new y(a, t);
777
+ const u = new _([]);
762
778
  n.trigger("newRTCSession", {
763
779
  originator: g,
764
780
  session: s,
765
- request: l
781
+ request: u
766
782
  });
767
- }, Tt = (n, e) => {
783
+ }, _t = (n, e) => {
768
784
  e ? n.trigger("failed", e) : n.trigger("failed", n);
769
785
  }, P = {
770
786
  triggerNewInfo: pt,
771
787
  triggerNewSipEvent: gt,
772
- triggerIncomingSession: _t,
773
- triggerFailIncomingSession: Tt,
774
- WebSocketInterface: lt,
788
+ triggerIncomingSession: Tt,
789
+ triggerFailIncomingSession: _t,
790
+ WebSocketInterface: ut,
775
791
  UA: o,
776
792
  C: {
777
793
  INVITE: "INVITE"
778
794
  }
779
- }, I = "user", h = "displayName", w = "SIP_SERVER_URL", v = "SIP_WEB_SOCKET_SERVER_URL", It = new P.WebSocketInterface(v), S = {
795
+ }, I = "user", h = "displayName", S = "SIP_SERVER_URL", v = "SIP_WEB_SOCKET_SERVER_URL", It = new P.WebSocketInterface(v), w = {
780
796
  userAgent: "Chrome",
781
- sipServerUrl: w,
797
+ sipServerUrl: S,
782
798
  sipWebSocketServerURL: v
783
799
  }, vt = {
784
- ...S
785
- }, wt = {
786
- ...S,
800
+ ...w
801
+ }, St = {
802
+ ...w,
787
803
  user: I,
788
804
  password: c,
789
805
  register: !0
790
806
  }, Dt = {
791
- ...wt,
807
+ ...St,
792
808
  displayName: h
793
- }, Lt = {
794
- ...S,
809
+ }, yt = {
810
+ ...w,
795
811
  displayName: h,
796
812
  register: !1
797
813
  }, m = {
@@ -802,16 +818,16 @@ const g = "remote", pt = (n, e) => {
802
818
  register_expires: 300,
803
819
  connection_recovery_max_interval: 6,
804
820
  connection_recovery_min_interval: 2
805
- }, yt = {
821
+ }, Lt = {
806
822
  ...m,
807
823
  password: c,
808
- uri: new E("sip", I, w),
824
+ uri: new E("sip", I, S),
809
825
  display_name: "",
810
826
  register: !0
811
827
  }, Ft = {
812
828
  ...m,
813
829
  password: c,
814
- uri: new E("sip", I, w),
830
+ uri: new E("sip", I, S),
815
831
  display_name: h,
816
832
  register: !0
817
833
  }, bt = {
@@ -822,7 +838,7 @@ const g = "remote", pt = (n, e) => {
822
838
  ...m,
823
839
  display_name: "",
824
840
  register: !1
825
- }, St = "10.10.10.10", kt = [`X-Vinteo-Remote: ${St}`], Wt = () => new U({
841
+ }, wt = "10.10.10.10", kt = [`X-Vinteo-Remote: ${wt}`], Wt = () => new U({
826
842
  JsSIP: P
827
843
  });
828
844
  export {
@@ -831,17 +847,17 @@ export {
831
847
  mt as NAME_INCORRECT,
832
848
  c as PASSWORD_CORRECT,
833
849
  C as PASSWORD_CORRECT_2,
834
- w as SIP_SERVER_URL,
850
+ S as SIP_SERVER_URL,
835
851
  v as SIP_WEB_SOCKET_SERVER_URL,
836
- wt as dataForConnectionWithAuthorization,
852
+ St as dataForConnectionWithAuthorization,
837
853
  Dt as dataForConnectionWithAuthorizationWithDisplayName,
838
- Lt as dataForConnectionWithoutAuthorization,
854
+ yt as dataForConnectionWithoutAuthorization,
839
855
  vt as dataForConnectionWithoutAuthorizationWithoutDisplayName,
840
856
  h as displayName,
841
857
  Wt as doMockSipConnector,
842
858
  kt as extraHeadersRemoteAddress,
843
- St as remoteAddress,
844
- yt as uaConfigurationWithAuthorization,
859
+ wt as remoteAddress,
860
+ Lt as uaConfigurationWithAuthorization,
845
861
  Ft as uaConfigurationWithAuthorizationWithDisplayName,
846
862
  bt as uaConfigurationWithoutAuthorization,
847
863
  Vt as uaConfigurationWithoutAuthorizationWithoutDisplayName,
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("events-constructor");const r=require("./@SipConnector-DcaeAFrM.cjs"),x=require("@krivega/cancelable-promise"),j=require("repeated-calls"),K=require("ts-debounce"),X=require("ua-parser-js"),Y=require("sequent-promises"),G=n=>n instanceof Object&&("originator"in n||"cause"in n),J=n=>{if(x.isCanceledError(n))return!0;if(!G(n))return!1;const{originator:e,cause:t}=n;return typeof t=="string"?t===r.ECallCause.REQUEST_TIMEOUT||t===r.ECallCause.REJECTED||e===r.Originator.LOCAL&&(t===r.ECallCause.CANCELED||t===r.ECallCause.BYE):!1},z=()=>globalThis.process?.versions?.electron!==void 0,B=()=>{const n=new X.UAParser,{name:e}=n.getBrowser(),t=z();return{isChrome:e==="Chrome"||t}},A=n=>{const{url:e,cause:t}=n;let o=e;return(t===r.ECallCause.BAD_MEDIA_DESCRIPTION||t===r.ECallCause.NOT_FOUND)&&(o=`${n.message.to.uri.user}@${n.message.to.uri.host}`),o};var $=(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))($||{});const Q=new Error("Unknown error"),Z=(n=Q)=>{const{cause:e,socket:t}=n;let o="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case r.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case r.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:t!==void 0&&t._ws?.readyState===3?o="WS_CONNECTION_FAILED":A(n)!==void 0&&A(n)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},ee=n=>{let e="";try{e=JSON.stringify(n)}catch(t){r.logger("failed to stringify message",t)}return e},ne=new Error("Unknown error"),te=(n=ne)=>{const{code:e,cause:t,message:o}=n,a=A(n),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=ee(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),e!==void 0&&e!==""&&(s.code=e),t!==void 0&&t!==""&&(s.cause=t),s},re=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:$,getLinkError:A,getTypeFromError:Z,getValuesFromError:te},Symbol.toStringTag,{value:"Module"})),oe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=t?"0":"1",u=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},se="[@*!|]",ae="_",ce=n=>{let e=n;return e=e.replaceAll(new RegExp(se,"g"),ae),e},ie=({appName:n,appVersion:e,browserName:t,browserVersion:o})=>{const s=`${ce(n)} ${e}`;return`ChromeNew - ${t===void 0?s:`${t} ${o}, ${s}`}`},le=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:o,appName:a})=>n?ie({appVersion:e,browserName:t,browserVersion:o,appName:a}):"Chrome",H="purgatory",D=n=>n===H,ue=n=>e=>[...e].map(o=>async()=>n(o)),de=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const a=ue(e)(n);return Y.sequentPromises(a,t)},ge=n=>t=>(r.logger("onStartMainCam"),n.on("api:admin-start-main-cam",t)),Se=n=>t=>(r.logger("onStartMic"),n.on("api:admin-start-mic",t)),Ce=n=>t=>(r.logger("onStopMainCam"),n.on("api:admin-stop-main-cam",t)),me=n=>t=>(r.logger("onStopMic"),n.on("api:admin-stop-mic",t)),fe=({sipConnector:n})=>{const e=(g,C)=>({isSyncForced:S})=>{if(S===!0){g();return}C()},t=ge(n),o=Ce(n),a=Se(n),s=me(n);let c,l,u,f;const h=({onStartMainCamForced:g,onStartMainCamNotForced:C,onStopMainCamForced:S,onStopMainCamNotForced:p,onStartMicForced:E,onStartMicNotForced:b,onStopMicForced:O,onStopMicNotForced:v})=>{const T=e(g,C);c=t(T);const P=e(S,p);l=o(P);const _=e(E,b);u=a(_);const m=e(O,v);f=s(m)},d=()=>{c?.(),l?.(),u?.(),f?.()};return{start:g=>{h(g)},stop:()=>{d()}}},he=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:H,createSyncMediaState:fe,createUaParser:B,error:re,getExtraHeaders:oe,getUserAgent:le,hasPurgatory:D,prepareMediaStream:r.prepareMediaStream,sendDtmfAccumulated:de,setEncodingsToSender:r.setEncodingsToSender,setParametersToSender:r.setParametersToSender},Symbol.toStringTag,{value:"Module"})),pe=()=>B().isChrome,U=n=>{if(!x.isCanceledError(n)&&!j.hasCanceledError(n))throw n;return{isSuccessful:!1}},Re=({kind:n,readyState:e})=>n==="video"&&e==="live",k=(n,e,{onEnterPurgatory:t,onEnterConference:o})=>{D(n)?t&&t():o&&o({isSuccessProgressCall:e})},L=(n,e)=>{n(),e&&e()},V=(n,e,t)=>{throw n&&n(),e(),t},Ee=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class be{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;connection;isConfigured;isRegistered;sipConnector;constructor(e){return this.sipConnector=e,new Proxy(this,{get:(t,o,a)=>{if(typeof o=="string"&&Ee.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(t,o,a);return typeof s=="function"?s.bind(t):s}})}connectToServer=async e=>{const{userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,name:l,password:u,isRegisteredUser:f,isDisconnectOnFail:h}=e;return r.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,password:u,user:l,register:f}).then(d=>(r.logger("connectToServer then"),{ua:d,isSuccessful:!0})).catch(async d=>(r.logger("connectToServer catch: error",d),h===!0?this.sipConnector.disconnect().then(()=>U(d)).catch(()=>U(d)):U(d)))};callToServer=async e=>{const{conference:t,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,setRemoteStreams:y,onBeforeProgressCall:g,onSuccessProgressCall:C,onEnterPurgatory:S,onEnterConference:p,onFailProgressCall:E,onFinishProgressCall:b,onEndedCall:O,onAddedTransceiver:v}=e,T=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:y}),P=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{T().catch(r.logger)}});r.logger("callToServer",e);const _=async()=>(r.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,degradationPreference:l,onAddedTransceiver:v,sendEncodings:u,number:t,ontrack:P}));let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",p),this.sipConnector.on("api:enterRoom",({room:i})=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(S??p)&&k(R,m,{onEnterPurgatory:S,onEnterConference:p})})),F=i=>(r.logger("onSuccess"),m=!0,T().catch(r.logger),C&&C({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,O)}),i),w=i=>(r.logger("onFail"),V(E,M,i)),I=()=>{r.logger("onFinish"),b&&b()};return r.logger("onBeforeProgressCall"),g&&g(t),_().then(F).catch(i=>w(i)).finally(I)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(r.logger("disconnectFromServer: catch",e),{isSuccessful:!1}));answerToIncomingCall=async e=>{const{mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,setRemoteStreams:N,onBeforeProgressCall:y,onSuccessProgressCall:g,onEnterPurgatory:C,onEnterConference:S,onFailProgressCall:p,onFinishProgressCall:E,onEndedCall:b,onAddedTransceiver:O}=e,v=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:N}),T=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{v().catch(r.logger)}});r.logger("answerToIncomingCall",e);const P=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,degradationPreference:c,onAddedTransceiver:O,sendEncodings:l,ontrack:T}),_=()=>{const{remoteCallerData:i}=this.sipConnector;return i.incomingNumber};let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",S),this.sipConnector.on("api:enterRoom",i=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(C??S)&&k(R,m,{onEnterPurgatory:C,onEnterConference:S})})),F=i=>(r.logger("onSuccess"),m=!0,v().catch(r.logger),g&&g({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,b)}),i),w=i=>(r.logger("onFail"),V(p,M,i)),I=()=>{r.logger("onFinish"),E&&E()};if(r.logger("onBeforeProgressCall"),y){const i=_();y(i)}return P().then(F).catch(i=>w(i)).finally(I)};updatePresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,onAddedTransceiver:c})=>(r.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,contentHint:o,degradationPreference:a,onAddedTransceiver:c,sendEncodings:s}));startPresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,callLimit:c,onAddedTransceiver:l})=>(r.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,contentHint:o,callLimit:c,degradationPreference:a,onAddedTransceiver:l,sendEncodings:s}));stopShareSipConnector=async({isP2P:e=!1}={})=>(r.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{r.logger(t)}));sendRefusalToTurnOnMic=async()=>{r.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{r.logger("sendRefusalToTurnOnMic: error",e)})};sendRefusalToTurnOnCam=async()=>{r.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{r.logger("sendRefusalToTurnOnCam: error",e)})};sendMediaState=async({isEnabledCam:e,isEnabledMic:t})=>{r.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t})};replaceMediaStream=async(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:u})=>(r.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:u,sendEncodings:l}));askPermissionToEnableCam=async()=>{r.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:e})=>K.debounce(()=>{const t=this.sipConnector.getRemoteStreams();r.logger("remoteStreams",t),t&&e(t)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:e})=>({track:t})=>{Re(t)&&e()};getRemoteStreams=()=>(r.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=e=>(r.logger("onUseLicense"),this.sipConnector.on("api:useLicense",e));onMustStopPresentation=e=>(r.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",e));onMoveToSpectators=e=>(r.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",e));onMoveToParticipants=e=>(r.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",e));onStats=e=>(r.logger("onStats"),this.sipConnector.on("stats:collected",e));offStats=e=>{r.logger("offStats"),this.sipConnector.off("stats:collected",e)}}var W=(n=>(n.VP8="video/VP8",n.VP9="video/VP9",n.H264="video/H264",n.AV1="video/AV1",n.rtx="video/rtx",n.red="video/red",n.flexfec03="video/flexfec-03",n))(W||{});exports.ECallCause=r.ECallCause;exports.EStatsTypes=r.EStatsTypes;exports.EUseLicense=r.EUseLicense;exports.SipConnector=r.SipConnector;exports.StatsPeerConnection=r.StatsPeerConnection;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.getCodecFromSender=r.getCodecFromSender;exports.hasCanceledStartPresentationError=r.hasCanceledStartPresentationError;exports.EMimeTypesVideoCodecs=W;exports.SipConnectorFacade=be;exports.hasAvailableStats=pe;exports.hasCanceledCallError=J;exports.tools=he;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("events-constructor");const r=require("./@SipConnector-BjWfal-x.cjs"),x=require("@krivega/cancelable-promise"),j=require("repeated-calls"),K=require("ts-debounce"),X=require("ua-parser-js"),Y=require("sequent-promises"),G=n=>n instanceof Object&&("originator"in n||"cause"in n),J=n=>{if(x.isCanceledError(n))return!0;if(!G(n))return!1;const{originator:e,cause:t}=n;return typeof t=="string"?t===r.ECallCause.REQUEST_TIMEOUT||t===r.ECallCause.REJECTED||e===r.Originator.LOCAL&&(t===r.ECallCause.CANCELED||t===r.ECallCause.BYE):!1},z=()=>globalThis.process?.versions?.electron!==void 0,B=()=>{const n=new X.UAParser,{name:e}=n.getBrowser(),t=z();return{isChrome:e==="Chrome"||t}},A=n=>{const{url:e,cause:t}=n;let o=e;return(t===r.ECallCause.BAD_MEDIA_DESCRIPTION||t===r.ECallCause.NOT_FOUND)&&(o=`${n.message.to.uri.user}@${n.message.to.uri.host}`),o};var $=(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))($||{});const Q=new Error("Unknown error"),Z=(n=Q)=>{const{cause:e,socket:t}=n;let o="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case r.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case r.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:t!==void 0&&t._ws?.readyState===3?o="WS_CONNECTION_FAILED":A(n)!==void 0&&A(n)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},ee=n=>{let e="";try{e=JSON.stringify(n)}catch(t){r.logger("failed to stringify message",t)}return e},ne=new Error("Unknown error"),te=(n=ne)=>{const{code:e,cause:t,message:o}=n,a=A(n),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=ee(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),e!==void 0&&e!==""&&(s.code=e),t!==void 0&&t!==""&&(s.cause=t),s},re=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:$,getLinkError:A,getTypeFromError:Z,getValuesFromError:te},Symbol.toStringTag,{value:"Module"})),oe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=t?"0":"1",u=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},se="[@*!|]",ae="_",ce=n=>{let e=n;return e=e.replaceAll(new RegExp(se,"g"),ae),e},ie=({appName:n,appVersion:e,browserName:t,browserVersion:o})=>{const s=`${ce(n)} ${e}`;return`ChromeNew - ${t===void 0?s:`${t} ${o}, ${s}`}`},le=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:o,appName:a})=>n?ie({appVersion:e,browserName:t,browserVersion:o,appName:a}):"Chrome",H="purgatory",D=n=>n===H,ue=n=>e=>[...e].map(o=>async()=>n(o)),de=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const a=ue(e)(n);return Y.sequentPromises(a,t)},ge=n=>t=>(r.logger("onStartMainCam"),n.on("api:admin-start-main-cam",t)),Se=n=>t=>(r.logger("onStartMic"),n.on("api:admin-start-mic",t)),Ce=n=>t=>(r.logger("onStopMainCam"),n.on("api:admin-stop-main-cam",t)),me=n=>t=>(r.logger("onStopMic"),n.on("api:admin-stop-mic",t)),fe=({sipConnector:n})=>{const e=(g,C)=>({isSyncForced:S})=>{if(S===!0){g();return}C()},t=ge(n),o=Ce(n),a=Se(n),s=me(n);let c,l,u,f;const h=({onStartMainCamForced:g,onStartMainCamNotForced:C,onStopMainCamForced:S,onStopMainCamNotForced:p,onStartMicForced:E,onStartMicNotForced:b,onStopMicForced:O,onStopMicNotForced:v})=>{const T=e(g,C);c=t(T);const P=e(S,p);l=o(P);const _=e(E,b);u=a(_);const m=e(O,v);f=s(m)},d=()=>{c?.(),l?.(),u?.(),f?.()};return{start:g=>{h(g)},stop:()=>{d()}}},he=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:H,createSyncMediaState:fe,createUaParser:B,error:re,getExtraHeaders:oe,getUserAgent:le,hasPurgatory:D,prepareMediaStream:r.prepareMediaStream,sendDtmfAccumulated:de,setEncodingsToSender:r.setEncodingsToSender,setParametersToSender:r.setParametersToSender},Symbol.toStringTag,{value:"Module"})),pe=()=>B().isChrome,U=n=>{if(!x.isCanceledError(n)&&!j.hasCanceledError(n))throw n;return{isSuccessful:!1}},Re=({kind:n,readyState:e})=>n==="video"&&e==="live",k=(n,e,{onEnterPurgatory:t,onEnterConference:o})=>{D(n)?t&&t():o&&o({isSuccessProgressCall:e})},L=(n,e)=>{n(),e&&e()},V=(n,e,t)=>{throw n&&n(),e(),t},Ee=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class be{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;connection;isConfigured;isRegistered;sipConnector;constructor(e){return this.sipConnector=e,new Proxy(this,{get:(t,o,a)=>{if(typeof o=="string"&&Ee.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(t,o,a);return typeof s=="function"?s.bind(t):s}})}connectToServer=async e=>{const{userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,name:l,password:u,isRegisteredUser:f,isDisconnectOnFail:h}=e;return r.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,password:u,user:l,register:f}).then(d=>(r.logger("connectToServer then"),{ua:d,isSuccessful:!0})).catch(async d=>(r.logger("connectToServer catch: error",d),h===!0?this.sipConnector.disconnect().then(()=>U(d)).catch(()=>U(d)):U(d)))};callToServer=async e=>{const{conference:t,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,setRemoteStreams:y,onBeforeProgressCall:g,onSuccessProgressCall:C,onEnterPurgatory:S,onEnterConference:p,onFailProgressCall:E,onFinishProgressCall:b,onEndedCall:O,onAddedTransceiver:v}=e,T=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:y}),P=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{T().catch(r.logger)}});r.logger("callToServer",e);const _=async()=>(r.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,degradationPreference:l,onAddedTransceiver:v,sendEncodings:u,number:t,ontrack:P}));let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",p),this.sipConnector.on("api:enterRoom",({room:i})=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(S??p)&&k(R,m,{onEnterPurgatory:S,onEnterConference:p})})),F=i=>(r.logger("onSuccess"),m=!0,T().catch(r.logger),C&&C({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,O)}),i),w=i=>(r.logger("onFail"),V(E,M,i)),I=()=>{r.logger("onFinish"),b&&b()};return r.logger("onBeforeProgressCall"),g&&g(t),_().then(F).catch(i=>w(i)).finally(I)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(r.logger("disconnectFromServer: catch",e),{isSuccessful:!1}));answerToIncomingCall=async e=>{const{mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,setRemoteStreams:N,onBeforeProgressCall:y,onSuccessProgressCall:g,onEnterPurgatory:C,onEnterConference:S,onFailProgressCall:p,onFinishProgressCall:E,onEndedCall:b,onAddedTransceiver:O}=e,v=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:N}),T=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{v().catch(r.logger)}});r.logger("answerToIncomingCall",e);const P=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,degradationPreference:c,onAddedTransceiver:O,sendEncodings:l,ontrack:T}),_=()=>{const{remoteCallerData:i}=this.sipConnector;return i.incomingNumber};let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",S),this.sipConnector.on("api:enterRoom",i=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(C??S)&&k(R,m,{onEnterPurgatory:C,onEnterConference:S})})),F=i=>(r.logger("onSuccess"),m=!0,v().catch(r.logger),g&&g({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,b)}),i),w=i=>(r.logger("onFail"),V(p,M,i)),I=()=>{r.logger("onFinish"),E&&E()};if(r.logger("onBeforeProgressCall"),y){const i=_();y(i)}return P().then(F).catch(i=>w(i)).finally(I)};updatePresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,onAddedTransceiver:c})=>(r.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,contentHint:o,degradationPreference:a,onAddedTransceiver:c,sendEncodings:s}));startPresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,callLimit:c,onAddedTransceiver:l})=>(r.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,contentHint:o,callLimit:c,degradationPreference:a,onAddedTransceiver:l,sendEncodings:s}));stopShareSipConnector=async({isP2P:e=!1}={})=>(r.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{r.logger(t)}));sendRefusalToTurnOnMic=async()=>{r.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{r.logger("sendRefusalToTurnOnMic: error",e)})};sendRefusalToTurnOnCam=async()=>{r.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{r.logger("sendRefusalToTurnOnCam: error",e)})};sendMediaState=async({isEnabledCam:e,isEnabledMic:t})=>{r.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t})};replaceMediaStream=async(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:u})=>(r.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:u,sendEncodings:l}));askPermissionToEnableCam=async()=>{r.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:e})=>K.debounce(()=>{const t=this.sipConnector.getRemoteStreams();r.logger("remoteStreams",t),t&&e(t)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:e})=>({track:t})=>{Re(t)&&e()};getRemoteStreams=()=>(r.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=e=>(r.logger("onUseLicense"),this.sipConnector.on("api:useLicense",e));onMustStopPresentation=e=>(r.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",e));onMoveToSpectators=e=>(r.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",e));onMoveToParticipants=e=>(r.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",e));onStats=e=>(r.logger("onStats"),this.sipConnector.on("stats:collected",e));offStats=e=>{r.logger("offStats"),this.sipConnector.off("stats:collected",e)}}var W=(n=>(n.VP8="video/VP8",n.VP9="video/VP9",n.H264="video/H264",n.AV1="video/AV1",n.rtx="video/rtx",n.red="video/red",n.flexfec03="video/flexfec-03",n))(W||{});exports.ECallCause=r.ECallCause;exports.EStatsTypes=r.EStatsTypes;exports.EUseLicense=r.EUseLicense;exports.SipConnector=r.SipConnector;exports.StatsPeerConnection=r.StatsPeerConnection;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.getCodecFromSender=r.getCodecFromSender;exports.hasCanceledStartPresentationError=r.hasCanceledStartPresentationError;exports.EMimeTypesVideoCodecs=W;exports.SipConnectorFacade=be;exports.hasAvailableStats=pe;exports.hasCanceledCallError=J;exports.tools=he;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import "events-constructor";
2
- import { E as h, O as K, l as o, p as X, s as Y, a as G } from "./@SipConnector-uiUlVCMv.js";
3
- import { c as ke, b as Le, S as xe, f as Ve, d as Be, e as $e, g as He, h as We } from "./@SipConnector-uiUlVCMv.js";
2
+ import { E as h, O as K, l as o, p as X, s as Y, a as G } from "./@SipConnector-CoBe6WQF.js";
3
+ import { c as ke, b as Le, S as xe, f as Ve, d as Be, e as $e, g as He, h as We } from "./@SipConnector-CoBe6WQF.js";
4
4
  import { isCanceledError as B } from "@krivega/cancelable-promise";
5
5
  import { hasCanceledError as q } from "repeated-calls";
6
6
  import { debounce as z } from "ts-debounce";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "16.0.1",
3
+ "version": "16.0.3",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -61,7 +61,7 @@
61
61
  "@krivega/timeout-requester": "^1.0.0",
62
62
  "debug": "^4.4.1",
63
63
  "events-constructor": "^2.0.0",
64
- "repeated-calls": "^2.3.5",
64
+ "repeated-calls": "^2.4.0",
65
65
  "sequent-promises": "^2.0.1",
66
66
  "stack-promises": "^2.0.3",
67
67
  "ts-debounce": "^4.0.0",
@@ -80,8 +80,8 @@
80
80
  "@types/jest": "^30.0.0",
81
81
  "cross-env": "^10.0.0",
82
82
  "husky": "^9.1.7",
83
- "jest": "^30.0.5",
84
- "jest-environment-jsdom": "^30.0.5",
83
+ "jest": "^30.1.1",
84
+ "jest-environment-jsdom": "^30.1.1",
85
85
  "jest-extended": "^6.0.0",
86
86
  "jest-junit": "^16.0.0",
87
87
  "lint-staged": "^16.1.5",
@@ -101,7 +101,7 @@
101
101
  "@krivega/timeout-requester": "^1.0.0",
102
102
  "debug": "^4.4.1",
103
103
  "events-constructor": "^2.0.0",
104
- "repeated-calls": "^2.3.5",
104
+ "repeated-calls": "^2.4.0",
105
105
  "sequent-promises": "^2.0.1",
106
106
  "stack-promises": "^2.0.3",
107
107
  "ts-debounce": "^4.0.0",
@@ -1 +0,0 @@
1
- "use strict";const v=require("events-constructor"),Me=require("@krivega/cancelable-promise"),x=require("debug"),G=require("repeated-calls"),ee=require("xstate"),te=require("@krivega/timeout-requester");require("ua-parser-js");require("sequent-promises");const me=require("stack-promises");var C=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n))(C||{}),B=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(B||{});const ne=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],pe=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver"],se=[...ne,...pe],Pe=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},L=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&Pe(o,s),o};function fe(n){return e=>`sip:${e}@${n}`}const Oe=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,ie=n=>n.trim().replaceAll(" ","_"),ve=Oe(1e5,99999999),De=n=>n.some(t=>{const{kind:s}=t;return s==="video"});class ye{isPendingCall=!1;isPendingAnswer=!1;rtcSession;remoteStreams={};events;callConfiguration={};constructor(e){this.events=e}}var Q=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(Q||{});class be{remoteStreams={};reset(){this.remoteStreams={}}generateStream(e,t){const{id:s}=e,i=this.remoteStreams[s]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[s]=i,i}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,i)=>{if(s.kind==="audio")return;const r=s,a=e[i-1];let o;a?.kind==="audio"&&(o=a);const c=this.generateStream(r,o);t.push(c)}),t}generateAudioStreams(e){return e.map(t=>this.generateAudioStream(t))}}class Ue extends ye{remoteStreamsManager=new be;disposers=new Set;constructor(e){super(e),e.on(C.FAILED,this.handleEnded),e.on(C.ENDED,this.handleEnded)}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],ontrack:a,iceServers:o,directionVideo:c,directionAudio:d,contentHint:u,offerToReceiveAudio:T=!0,offerToReceiveVideo:h=!0,degradationPreference:E,sendEncodings:m,onAddedTransceiver:I})=>(this.isPendingCall=!0,new Promise((R,y)=>{this.callConfiguration.number=s,this.callConfiguration.answer=!1,this.handleCall({ontrack:a}).then(R).catch(b=>{y(b)}),this.rtcSession=e.call(t(s),{extraHeaders:r,mediaStream:L(i,{directionVideo:c,directionAudio:d,contentHint:u}),eventHandlers:this.events.triggers,directionVideo:c,directionAudio:d,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:T,offerToReceiveVideo:h},degradationPreference:E,sendEncodings:m,onAddedTransceiver:I})}).finally(()=>{this.isPendingCall=!1}));async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Q.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,ontrack:s,extraHeaders:i=[],iceServers:r,directionVideo:a,directionAudio:o,offerToReceiveAudio:c,offerToReceiveVideo:d,contentHint:u,degradationPreference:T,sendEncodings:h,onAddedTransceiver:E})=>(this.isPendingAnswer=!0,new Promise((m,I)=>{try{const R=e();this.rtcSession=R,this.subscribeToSessionEvents(R),this.callConfiguration.answer=!0,this.callConfiguration.number=R.remote_identity.uri.user,this.handleCall({ontrack:s}).then(m).catch(b=>{I(b)});const y=L(t,{directionVideo:a,directionAudio:o,contentHint:u});R.answer({extraHeaders:i,directionVideo:a,directionAudio:o,mediaStream:y,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d},degradationPreference:T,sendEncodings:h,onAddedTransceiver:E})}catch(R){I(R)}}).finally(()=>{this.isPendingAnswer=!1}));getEstablishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}getCallConfiguration(){return{...this.callConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return De(t)?this.remoteStreamsManager.generateStreams(t):this.remoteStreamsManager.generateAudioStreams(t)}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=L(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}handleCall=async({ontrack:e})=>new Promise((t,s)=>{const i=()=>{this.events.on(C.PEER_CONNECTION,u),this.events.on(C.CONFIRMED,T)},r=()=>{this.events.off(C.PEER_CONNECTION,u),this.events.off(C.CONFIRMED,T)},a=()=>{this.events.on(C.FAILED,c),this.events.on(C.ENDED,c)},o=()=>{this.events.off(C.FAILED,c),this.events.off(C.ENDED,c)},c=h=>{r(),o(),s(h)};let d;const u=({peerconnection:h})=>{d=h;const E=m=>{this.events.trigger(C.PEER_CONNECTION_ONTRACK,h),e&&e(m)};h.addEventListener("track",E),this.disposers.add(()=>{h.removeEventListener("track",E)})},T=()=>{d!==void 0&&this.events.trigger(C.PEER_CONNECTION_CONFIRMED,d),r(),o(),t(d)};i(),a()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=ne.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t===B.REMOTE&&this.events.trigger(C.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.remoteStreamsManager.reset(),this.unsubscribeFromSessionEvents(),this.callConfiguration.number=void 0,this.callConfiguration.answer=!1}}class we{events;strategy;constructor(e){this.events=new v.Events(se),this.strategy=e??new Ue(this.events)}get requested(){return this.strategy.requested}get connection(){return this.strategy.connection}get establishedRTCSession(){return this.strategy.establishedRTCSession}get isCallActive(){return this.strategy.isCallActive}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}setStrategy(e){this.strategy=e}startCall=async(...e)=>this.strategy.startCall(...e);endCall=async()=>this.strategy.endCall();answerToIncomingCall=async(...e)=>this.strategy.answerToIncomingCall(...e);getEstablishedRTCSession=()=>this.strategy.getEstablishedRTCSession();getCallConfiguration=()=>this.strategy.getCallConfiguration();getRemoteStreams=()=>this.strategy.getRemoteStreams();replaceMediaStream=async(...e)=>this.strategy.replaceMediaStream(...e)}const Y="sip-connector",A=x(Y),Le=()=>{x.enable(Y)},Be=()=>{x.enable(`-${Y}`)},ke="Error decline with 603",Fe=1006,$e=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===Fe,Ve=n=>n.message===ke;var l=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n.AVAILABLE_INCOMING_BITRATE="X-WEBRTC-AVAILABLE-INCOMING-BITRATE",n))(l||{}),F=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(F||{}),$=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n.SPECTATOR_OVER_SFU="SPECTATOROVERSFU",n))($||{}),O=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n))(O||{}),M=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.STATS="application/vinteo.webrtc.stats",n))(M||{}),P=(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))(P||{}),W=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(W||{}),H=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(H||{}),re=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(re||{}),g=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU="participant:move-request-to-spectators-over-sfu",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n))(g||{});const ae=["participation:accepting-word-request","participation:cancelling-word-request","participant:move-request-to-stream","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-spectators","participant:move-request-to-participants","participant:move-request-to-spectators-over-sfu","channels","enterRoom","shareState","main-cam-control","useLicense","admin-start-main-cam","admin-stop-main-cam","admin-start-mic","admin-stop-mic","admin-force-sync-media-state","availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","newDTMF"];var _=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(_||{});class We{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=new v.Events(ae),this.subscribe()}async waitChannels(){return this.wait(g.CHANNELS)}async waitSyncMediaState(){return this.wait(g.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let i;try{i=this.getEstablishedRTCSessionProtected()}catch(r){s(r)}i&&(this.callManager.once("newDTMF",({originator:r})=>{r===B.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${l.INPUT_CHANNELS}: ${e}`,r=`${l.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(M.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${l.MEDIA_STATE}: currentstate`,a=`${l.MAIN_CAM_STATE}: ${Number(e)}`,o=`${l.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(M.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${l.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(M.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${l.MEDIA_TYPE}: ${a}`];return s.sendInfo(M.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(M.SHARE_STATE,void 0,{extraHeaders:[l.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[l.ENABLE_MAIN_CAM];return t.sendInfo(M.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(Ve(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(l.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){A("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case _.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case _.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case _.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case _.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case _.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case _.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case _.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case _.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case _.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case _.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case _.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:A("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!==B.REMOTE)return;const{request:s}=e,i=s.getHeader(l.CONTENT_TYPE);if(i!==void 0)switch(i){case O.ENTER_ROOM:{this.triggerEnterRoom(s),this.maybeTriggerChannels(s);break}case O.NOTIFY:{this.maybeHandleNotify(s);break}case O.SHARE_STATE:{this.triggerShareState(s);break}case O.MAIN_CAM:{this.triggerMainCamControl(s);break}case O.MIC:{this.triggerMicControl(s);break}case O.USE_LICENSE:{this.triggerUseLicense(s);break}case O.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(s);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(g.ACCOUNT_CHANGED,void 0)};triggerAccountDeletedNotify=()=>{this.events.trigger(g.ACCOUNT_DELETED,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(g.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=e.getHeader(l.INPUT_CHANNELS),s=e.getHeader(l.OUTPUT_CHANNELS);if(t&&s){const i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS,i)}};triggerEnterRoom=e=>{const t=e.getHeader(l.CONTENT_ENTER_ROOM),s=e.getHeader(l.PARTICIPANT_NAME);this.events.trigger(g.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(l.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case F.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(g.AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case F.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(g.NOT_AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case F.MUST_STOP_PRESENTATION:{this.events.trigger(g.MUST_STOP_PRESENTATION,void 0);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(l.CONTENT_PARTICIPANT_STATE);t===$.SPECTATOR&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,void 0),t===$.PARTICIPANT&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,void 0),t===$.SPECTATOR_OVER_SFU&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(l.MAIN_CAM),s=e.getHeader(l.MEDIA_SYNC),i=s===H.ADMIN_SYNC_FORCED;if(t===P.ADMIN_START_MAIN_CAM){this.events.trigger(g.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===P.ADMIN_STOP_MAIN_CAM){this.events.trigger(g.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===P.RESUME_MAIN_CAM||t===P.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(g.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=e.getHeader(l.MAIN_CAM_RESOLUTION);this.events.trigger(g.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(l.MIC),i=e.getHeader(l.MEDIA_SYNC)===H.ADMIN_SYNC_FORCED;t===W.ADMIN_START_MIC?this.events.trigger(g.ADMIN_START_MIC,{isSyncForced:i}):t===W.ADMIN_STOP_MIC&&this.events.trigger(g.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(l.CONTENT_USE_LICENSE);this.events.trigger(g.USE_LICENSE,t)}}const He=(n,e)=>(n.degradationPreference=e.degradationPreference,n),qe=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},oe=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,xe=oe(),Ge=(n,e)=>{if(xe(n,e))return n},Qe=(n,e)=>{const t=n.maxBitrate,s=Ge(e,t);return s!==void 0&&(n.maxBitrate=s),n},ce=1,Ye=oe(ce),ze=(n,e)=>{const t=n===void 0?void 0:Math.max(n,ce);if(t!==void 0&&Ye(t,e))return t},Je=(n,e)=>{const t=n.scaleResolutionDownBy,s=ze(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},Xe=(n,e)=>{const t=e.encodings?.length??0;return qe(n,t),n.encodings.forEach((s,i)=>{const r=(e?.encodings??[])[i],a=r?.maxBitrate,o=r?.scaleResolutionDownBy;Qe(s,a),Je(s,o)}),n},je=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},de=async(n,e)=>{const t=n.getParameters(),s=JSON.parse(JSON.stringify(t));Xe(t,e),He(t,e);const i=je(s,t);return i&&await n.setParameters(t),{parameters:t,isChanged:i}},z=async(n,e,t)=>{const{isChanged:s,parameters:i}=await de(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(i),{isChanged:s,parameters:i}},Ke=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),Ze=async(n,e,t)=>{const s=Ke(n,e);if(s)return z(s,{maxBitrate:t})};var f=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(f||{});const he=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],et=1,tt=n=>G.hasCanceledError(n);class nt{events;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=new v.Events(he),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async startPresentation(e,t,{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:t,presentationOptions:{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{throw this.events.trigger(f.FAILED_PRESENTATION,r),r}):t&&this.events.trigger(f.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.cancel()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(f.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(f.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(f.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(f.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(f.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:et}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const d=L(s,{contentHint:r});if(d===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=d;const u=e().then(async()=>t.startPresentation(d,i,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(T=>{throw this.removeStreamPresentationCurrent(),this.events.trigger(f.FAILED_PRESENTATION,T),T});return this.promisePendingStartPresentation=u,u.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const i=e.getSenders();await Ze(i,t,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class st{data={};getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){return{...this.data}}set(e){this.data={...e}}update(e,t){this.data[e]=t}clear(){this.data={}}isRegister(){return this.data.register===!0}getSipServerUrl(){return this.data.sipServerUrl}getDisplayName(){return this.data.displayName}getUser(){return this.data.user}getPassword(){return this.data.password}isRegisterEnabled(){return this.data.register===!0}}var N=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n))(N||{});const ge=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],le=[...ge],it=3;class rt{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setSipServerUrl;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setSipServerUrl=e.setSipServerUrl,this.setSocket=e.setSocket}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a.displayName&&(r=i.set("display_name",ie(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{const e=new Promise(s=>{this.events.once(N.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(N.DISCONNECTED,void 0),e.finally(()=>{this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=it}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),d=r!=null&&!$e(r);return c||d};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=G.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start());initUa=async({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:d,userAgent:u,displayName:T="",register:h=!1,extraHeaders:E=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerUrl:s,displayName:T,register:h,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:I,helpers:R}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,displayName:T,register:h,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:d,userAgent:u,remoteAddress:r,extraHeaders:E},this.events);return this.setUa(I),this.setSipServerUrl(R.getSipServerUrl),this.setSocket(R.socket),I};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,d)=>{if(this.getConnectionConfiguration().register===!0)return this.registrationManager.subscribeToStartEvents(c,d);const T=N.CONNECTED,h=[N.DISCONNECTED];return this.events.on(T,c),h.forEach(E=>{this.events.on(E,d)}),()=>{this.events.off(T,c),h.forEach(E=>{this.events.off(E,d)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}}var ue=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(ue||{});const at=ee.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{A(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{A("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"idle",context:{},states:{idle:{entry:{type:"logStateChange",params:{state:"idle"}},on:{START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"idle",to:"connecting",event:"START_CONNECT"}}}}},connecting:{entry:{type:"logStateChange",params:{state:"connecting"}},on:{START_INIT_UA:{target:"initializing",actions:{type:"logTransition",params:{from:"connecting",to:"initializing",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connecting",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connecting",to:"failed",event:"CONNECTION_FAILED"}}}}},initializing:{entry:{type:"logStateChange",params:{state:"initializing"}},on:{UA_CONNECTED:{target:"connected",actions:{type:"logTransition",params:{from:"initializing",to:"connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"initializing",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"initializing",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"initializing",to:"failed",event:"CONNECTION_FAILED"}}}}},connected:{entry:{type:"logStateChange",params:{state:"connected"}},on:{UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"connected",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connected",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connected",to:"failed",event:"CONNECTION_FAILED"}}}}},registered:{entry:{type:"logStateChange",params:{state:"registered"}},on:{UA_UNREGISTERED:{target:"connected",actions:{type:"logTransition",params:{from:"registered",to:"connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"registered",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"registered",to:"failed",event:"CONNECTION_FAILED"}}}}},disconnected:{entry:{type:"logStateChange",params:{state:"disconnected"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"disconnected",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"disconnected",to:"connecting",event:"START_CONNECT"}}}}},failed:{entry:{type:"logStateChange",params:{state:"failed"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"failed",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"failed",to:"connecting",event:"START_CONNECT"}}}}}}});class ot{actor;stateChangeListeners=new Set;events;unsubscribeFromEvents;actorSubscription;constructor(e){this.events=e,this.actor=ee.createActor(at),this.actorSubscription=this.actor.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})}),this.actor.start(),this.subscribeToEvents()}get state(){return this.actor.getSnapshot().value}get isIdle(){return this.hasState("idle")}get isConnecting(){return this.hasState("connecting")}get isInitializing(){return this.hasState("initializing")}get isConnected(){return this.hasState("connected")}get isRegistered(){return this.hasState("registered")}get isDisconnected(){return this.hasState("disconnected")}get isFailed(){return this.hasState("failed")}get isPending(){return this.isConnecting||this.isInitializing}get isPendingConnect(){return this.isConnecting}get isPendingInitUa(){return this.isInitializing}get isActiveConnection(){return this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.actorSubscription?.unsubscribe(),this.actor.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return Object.values(ue).filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){const t=this.actor.getSnapshot(),s={type:e};if(!t.can(s)){A(`Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`);return}this.actor.send(s)}toStartConnect=()=>{this.sendEvent("START_CONNECT")};toStartInitUa=()=>{this.sendEvent("START_INIT_UA")};toConnected=()=>{this.sendEvent("UA_CONNECTED")};toRegistered=()=>{this.sendEvent("UA_REGISTERED")};toUnregistered=()=>{this.sendEvent("UA_UNREGISTERED")};toDisconnected=()=>{this.sendEvent("UA_DISCONNECTED")};toFailed=()=>{this.sendEvent("CONNECTION_FAILED")};toIdle=()=>{this.sendEvent("RESET")};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toFailed)}}}class ct{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(N.REGISTERED,t),e.on(N.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(N.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){A("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=N.REGISTERED,i=[N.REGISTRATION_FAILED,N.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class dt{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:d}=this.uaFactory.createConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:s}),u=this.uaFactory.createUA({...d,remoteAddress:r,extraHeaders:a}),T=()=>{const E=new Error("Telephony is not available");c(E)};u.once(N.DISCONNECTED,T);const h=()=>{u.removeAllListeners(),u.once(N.DISCONNECTED,()=>{o()}),u.stop()};u.once(N.CONNECTED,h),u.start()})}}const ht=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class D{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateConfiguration({register:e,password:t,user:s,sipServerUrl:i,sipWebSocketServerURL:r}){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${ve()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?ht(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipWebSocketServerURL:s,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:d=2,connectionRecoveryMaxInterval:u=6,userAgent:T}){D.validateConfiguration({register:a,password:t,user:e,sipServerUrl:r,sipWebSocketServerURL:s});const h=D.resolveAuthorizationUser(a,e),E=fe(r),m=E(h),I=new this.JsSIP.WebSocketInterface(s);return{configuration:{password:t,register:a,uri:m,display_name:ie(i),user_agent:T,sdpSemantics:"unified-plan",sockets:[I],session_timers:o,register_expires:c,connection_recovery_min_interval:d,connection_recovery_max_interval:u},helpers:{socket:I,getSipServerUrl:E}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=D.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=ge.find(d=>d===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}class gt{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=new v.Events(le),this.uaFactory=new D(e),this.registrationManager=new ct({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new ot(this.events),this.configurationManager=new st({getUa:this.getUa}),this.sipOperations=new dt({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new rt({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setSipServerUrl:t=>{this.getSipServerUrl=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get connectionState(){return this.stateMachine.state}get isRegistered(){return D.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.connectionFlow.connect(e,t);set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>this.connectionFlow.disconnect();async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getSipServerUrl=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua}var w=(n=>(n.INCOMING_CALL="incomingCall",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(w||{}),q=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(q||{});const Te=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],lt=486,ut=487;class Tt{events;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=new v.Events(Te),this.start()}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=ut}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(w.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:lt})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e===q.REMOTE&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator===q.LOCAL?this.events.trigger(w.TERMINATED_INCOMING_CALL,t):this.events.trigger(w.FAILED_INCOMING_CALL,t)}),this.events.trigger(w.INCOMING_CALL,t)}removeIncomingSession(){delete this.incomingRTCSession}}const U=1e3;var S=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(S||{});const Se=["collected"],X=()=>"performance"in window?performance.now():Date.now(),k=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),St=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=k(n);return{outboundRtp:e[S.OUTBOUND_RTP],codec:e[S.CODEC],mediaSource:e[S.MEDIA_SOURCE],remoteInboundRtp:e[S.REMOTE_INBOUND_RTP]}},j=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=k(n);return{outboundRtp:e[S.OUTBOUND_RTP],codec:e[S.CODEC],mediaSource:e[S.MEDIA_SOURCE],remoteInboundRtp:e[S.REMOTE_INBOUND_RTP]}},K=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=k(n);return{inboundRtp:t[S.INBOUND_RTP],codec:t[S.CODEC],synchronizationSources:e}},Et=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=k(n);return{inboundRtp:t[S.INBOUND_RTP],codec:t[S.CODEC],remoteOutboundRtp:t[S.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},Ee=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=k(n);return{candidatePair:e[S.CANDIDATE_PAIR],certificate:e[S.CERTIFICATE],localCandidate:e[S.LOCAL_CANDIDATE],remoteCandidate:e[S.REMOTE_CANDIDATE],transport:e[S.TRANSPORT]}},Ct=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:j(e),secondVideo:j(t),audio:St(n),additional:Ee(n??e??t)}),Nt=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:K({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:K({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:Et({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:Ee(n??e??t)}),At=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=Ct({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=Nt({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},Rt=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(h=>h.track?.kind===e),r=s.filter(h=>h.track?.kind===t),a=n.getReceivers(),o=a.find(h=>h.track.kind===e),c=a.filter(h=>h.track.kind===t),d={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},u={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},T={audio:d,video:u};return Promise.all([i?.getStats(),r[0]?.getStats(),r[1]?.getStats(),o?.getStats(),c[0]?.getStats(),c[1]?.getStats()]).then(h=>{const[E,m,I,R,y,b]=h;return{synchronizationSources:T,audioSenderStats:E,videoSenderFirstStats:m,videoSenderSecondStats:I,audioReceiverStats:R,videoReceiverFirstStats:y,videoReceiverSecondStats:b}})},It=n=>{A(String(n))};class Ce{events;setTimeoutRequest;requesterAllStatistics=new Me.CancelableRequest(Rt);constructor(){this.events=new v.TypedEvents(Se),this.setTimeoutRequest=new te.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=U,onError:s=It}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=X();this.requesterAllStatistics.request(e).then(i=>{this.events.trigger("collected",At(i));const a=X()-s;let o=U;a>48?o=U*4:a>32?o=U*3:a>16&&(o=U*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})}}class _t{availableIncomingBitrate;statsPeerConnection;callManager;apiManager;previousAvailableIncomingBitrate;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new Ce,this.subscribe()}get events(){return this.statsPeerConnection.events}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableIncomingBitrate=this.availableIncomingBitrate,this.availableIncomingBitrate=e.inbound.additional.candidatePair?.availableIncomingBitrate,this.maybeSendStats()};handleStarted=e=>{this.statsPeerConnection.start(e)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableIncomingBitrate=void 0,this.previousAvailableIncomingBitrate=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{A("Failed to send stats",e)})}}const Mt=(n,e)=>n.filter(s=>e.some(i=>i.clockRate===s.clockRate&&i.mimeType===s.mimeType&&i.channels===s.channels&&i.sdpFmtpLine===s.sdpFmtpLine)),mt=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,i=t===null?[]:t.codecs;return Mt(s,i)},pt=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const i=e.indexOf(t.mimeType),r=e.indexOf(s.mimeType),a=i===-1?Number.MAX_VALUE:i,o=r===-1?Number.MAX_VALUE:r;return a-o}),Pt=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),ft=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=mt("video"),i=Pt(s,t),r=pt(i,e);n.setCodecPreferences(r)}}catch(s){A("setCodecPreferences error",s)}},Ot=n=>[...n.keys()].map(e=>n.get(e)),vt=(n,e)=>Ot(n).find(t=>t?.type===e),Ne=async n=>n.getStats().then(e=>vt(e,"codec")?.mimeType);class Dt{async getCodecFromSender(e){return await Ne(e)??""}}class yt{stackPromises=me.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{A("TaskQueue: error",e)})}}class bt{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new yt}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>z(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const Ae=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Ut=1e6,p=n=>n*Ut,Re=p(.06),Ie=p(4),wt=n=>n<=64?Re:n<=128?p(.12):n<=256?p(.25):n<=384?p(.32):n<=426?p(.38):n<=640?p(.5):n<=848?p(.7):n<=1280?p(1):n<=1920?p(2):Ie,Lt="av1",Bt=n=>Ae(n,Lt),kt=.6,J=(n,e)=>Bt(e)?n*kt:n,Ft=n=>J(Re,n),$t=n=>J(Ie,n),Z=(n,e)=>{const t=wt(n);return J(t,e)},V=1,Vt=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,i=t.height,r=s===void 0?V:s/e.width,a=i===void 0?V:i/e.height;return Math.max(r,a,V)};class Wt{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},i){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=i.ignoreForCodec}async balance(e,t){const s=e.getSenders(),i=this.senderFinder.findVideoSender(s);if(!i?.track)return{...this.resultNoChanged,sender:i};const r=await this.codecProvider.getCodecFromSender(i);if(Ae(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:i};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:i,codec:r,videoTrack:i.track}).then(c=>({...c,sender:i}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:i}=e;switch(s){case P.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case P.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case P.MAX_MAIN_CAM_RESOLUTION:return i!==void 0?this.setResolutionSender(i,t):this.setBitrateByTrackResolution(t);case P.ADMIN_STOP_MAIN_CAM:case P.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,i={scaleResolutionDownBy:200,maxBitrate:Ft(s)};return this.parametersSetter.setEncodingsToSender(t,i)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:i}=e,a=s.getSettings().width,o=a===void 0?$t(i):Z(a,i);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,i]=e.split("x"),{sender:r,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(i)},d=Vt({videoTrack:a,targetSize:c}),u=Z(c.width,o),T={scaleResolutionDownBy:d,maxBitrate:u};return this.parametersSetter.setEncodingsToSender(r,T)}}const Ht=n=>n.find(e=>e.track?.kind==="video");class qt{findVideoSender(e){return Ht(e)}}class xt{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new te.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async i=>{await s(i),this.attachTrack(t,i??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:i}=t.getSettings();this.lastWidth=s,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){const s=()=>{const{width:i,height:r}=e.getSettings();i!==this.lastWidth||r!==this.lastHeight?(this.lastWidth=i,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class Gt{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}class Qt{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:i,pollIntervalMs:r}={}){this.getConnection=t,this.eventHandler=new Gt(e),this.parametersSetterWithQueue=new bt(i),this.senderBalancer=new Wt({senderFinder:new qt,codecProvider:new Dt,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new xt({pollIntervalMs:r})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{A("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{A("handleMainCamControl: error",t)})}}const _e=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"];class Yt{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=new v.TypedEvents(_e),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new Qt(t,()=>e.connection,{...s,onSetParameters:i=>{this.events.trigger("parameters-updated",i),s.onSetParameters?.(i)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{A("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const zt=1e6,Jt=le.map(n=>`connection:${n}`),Xt=se.map(n=>`call:${n}`),jt=ae.map(n=>`api:${n}`),Kt=Te.map(n=>`incoming-call:${n}`),Zt=he.map(n=>`presentation:${n}`),en=Se.map(n=>`stats:${n}`),tn=_e.map(n=>`video-balancer:${n}`),nn=[...Jt,...Xt,...jt,...Kt,...Zt,...en,...tn];class sn{events;connectionManager;callManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:i}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=new v.Events(nn),this.connectionManager=new gt({JsSIP:e}),this.callManager=new we,this.apiManager=new We({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new Tt(this.connectionManager),this.presentationManager=new nt({callManager:this.callManager,maxBitrate:zt}),this.statsManager=new _t({callManager:this.callManager,apiManager:this.apiManager}),this.videoSendingBalancerManager=new Yt(this.callManager,this.apiManager,i),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get establishedRTCSession(){return this.callManager.establishedRTCSession}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionManager.connect(...e);set=async(...e)=>this.connectionManager.set(...e);disconnect=async()=>this.connectionManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getSipServerUrl=e=>this.connectionManager.getSipServerUrl(e);call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getSipServerUrl,{...s,onAddedTransceiver:async(i,r,a)=>{this.setCodecPreferences(i),await t?.(i,r,a)}})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:async(i,r,a)=>{this.setCodecPreferences(i),await t?.(i,r,a)}})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>this.callManager.getCallConfiguration();getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:i,onAddedTransceiver:r,...a}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...a,onAddedTransceiver:async(o,c,d)=>{this.setCodecPreferences(o),await r?.(o,c,d)}},i===void 0?void 0:{callLimit:i})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{await(t===!0?this.apiManager.sendMustStopPresentationP2P():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{isP2P:s,onAddedTransceiver:i,...r}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,{...r,onAddedTransceiver:async(a,o,c)=>{this.setCodecPreferences(a),await i?.(a,o,c)}})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}setCodecPreferences(e){ft(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.connectionManager.events.eachTriggers((e,t)=>{this.connectionManager.on(t,s=>{this.events.trigger(`connection:${t}`,s)})}),this.callManager.events.eachTriggers((e,t)=>{this.callManager.on(t,s=>{this.events.trigger(`call:${t}`,s)})}),this.apiManager.events.eachTriggers((e,t)=>{this.apiManager.on(t,s=>{this.events.trigger(`api:${t}`,s)})}),this.incomingCallManager.events.eachTriggers((e,t)=>{this.incomingCallManager.on(t,s=>{this.events.trigger(`incoming-call:${t}`,s)})}),this.presentationManager.events.eachTriggers((e,t)=>{this.presentationManager.on(t,s=>{this.events.trigger(`presentation:${t}`,s)})}),this.statsManager.events.eachTriggers((e,t)=>{this.statsManager.on(t,s=>{this.events.trigger(`stats:${t}`,s)})}),this.videoSendingBalancerManager.events.eachTriggers((e,t)=>{this.videoSendingBalancerManager.on(t,s=>{this.events.trigger(`video-balancer:${t}`,s)})})}}exports.ECallCause=Q;exports.EStatsTypes=S;exports.EUseLicense=re;exports.Originator=B;exports.SipConnector=sn;exports.StatsPeerConnection=Ce;exports.disableDebug=Be;exports.enableDebug=Le;exports.getCodecFromSender=Ne;exports.hasCanceledStartPresentationError=tt;exports.logger=A;exports.prepareMediaStream=L;exports.setEncodingsToSender=z;exports.setParametersToSender=de;