sip-connector 6.13.4 → 6.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/dist/index.d.ts +3 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.es5.js +1 -1
  4. package/dist/index.es5.js.map +1 -1
  5. package/dist/index.js +7 -1
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.umd.js +1 -1
  8. package/dist/index.umd.js.map +1 -1
  9. package/dist/logger.d.ts +7 -0
  10. package/dist/logger.d.ts.map +1 -0
  11. package/dist/logger.js +21 -0
  12. package/dist/logger.js.map +1 -0
  13. package/dist/tools/__fixtures__/call.d.ts +11 -0
  14. package/dist/tools/__fixtures__/call.d.ts.map +1 -0
  15. package/dist/tools/__fixtures__/call.js +38 -0
  16. package/dist/tools/__fixtures__/call.js.map +1 -0
  17. package/dist/tools/__fixtures__/connectToServer.d.ts +151 -0
  18. package/dist/tools/__fixtures__/connectToServer.d.ts.map +1 -0
  19. package/dist/tools/__fixtures__/connectToServer.js +35 -0
  20. package/dist/tools/__fixtures__/connectToServer.js.map +1 -0
  21. package/dist/tools/__fixtures__/hasValidUri.d.ts +10 -0
  22. package/dist/tools/__fixtures__/hasValidUri.d.ts.map +1 -0
  23. package/dist/tools/__fixtures__/hasValidUri.js +14 -0
  24. package/dist/tools/__fixtures__/hasValidUri.js.map +1 -0
  25. package/dist/tools/__fixtures__/permissions.d.ts +9 -0
  26. package/dist/tools/__fixtures__/permissions.d.ts.map +1 -0
  27. package/dist/tools/__fixtures__/permissions.js +15 -0
  28. package/dist/tools/__fixtures__/permissions.js.map +1 -0
  29. package/dist/tools/__fixtures__/processRequest.d.ts +4 -0
  30. package/dist/tools/__fixtures__/processRequest.d.ts.map +1 -0
  31. package/dist/tools/__fixtures__/processRequest.js +71 -0
  32. package/dist/tools/__fixtures__/processRequest.js.map +1 -0
  33. package/dist/tools/__tests-utils__/parseObject.d.ts +4 -0
  34. package/dist/tools/__tests-utils__/parseObject.d.ts.map +1 -0
  35. package/dist/tools/__tests-utils__/parseObject.js +27 -0
  36. package/dist/tools/__tests-utils__/parseObject.js.map +1 -0
  37. package/dist/tools/__tests-utils__/resolveParseArray.d.ts +3 -0
  38. package/dist/tools/__tests-utils__/resolveParseArray.d.ts.map +1 -0
  39. package/dist/tools/__tests-utils__/resolveParseArray.js +17 -0
  40. package/dist/tools/__tests-utils__/resolveParseArray.js.map +1 -0
  41. package/dist/tools/answerIncomingCall.d.ts +22 -0
  42. package/dist/tools/answerIncomingCall.d.ts.map +1 -0
  43. package/dist/tools/answerIncomingCall.js +94 -0
  44. package/dist/tools/answerIncomingCall.js.map +1 -0
  45. package/dist/tools/callToServer.d.ts +23 -0
  46. package/dist/tools/callToServer.d.ts.map +1 -0
  47. package/dist/tools/callToServer.js +90 -0
  48. package/dist/tools/callToServer.js.map +1 -0
  49. package/dist/tools/connectToServer.d.ts +15 -0
  50. package/dist/tools/connectToServer.d.ts.map +1 -0
  51. package/dist/tools/connectToServer.js +52 -0
  52. package/dist/tools/connectToServer.js.map +1 -0
  53. package/dist/tools/disconnectFromServer.d.ts +4 -0
  54. package/dist/tools/disconnectFromServer.d.ts.map +1 -0
  55. package/dist/tools/disconnectFromServer.js +23 -0
  56. package/dist/tools/disconnectFromServer.js.map +1 -0
  57. package/dist/tools/error/getLinkError.d.ts +4 -0
  58. package/dist/tools/error/getLinkError.d.ts.map +1 -0
  59. package/dist/tools/error/getLinkError.js +36 -0
  60. package/dist/tools/error/getLinkError.js.map +1 -0
  61. package/dist/tools/error/getTypeFromError.d.ts +12 -0
  62. package/dist/tools/error/getTypeFromError.d.ts.map +1 -0
  63. package/dist/tools/error/getTypeFromError.js +63 -0
  64. package/dist/tools/error/getTypeFromError.js.map +1 -0
  65. package/dist/tools/error/getValuesFromError.d.ts +10 -0
  66. package/dist/tools/error/getValuesFromError.d.ts.map +1 -0
  67. package/dist/tools/error/getValuesFromError.js +26 -0
  68. package/dist/tools/error/getValuesFromError.js.map +1 -0
  69. package/dist/tools/error/index.d.ts +5 -0
  70. package/dist/tools/error/index.d.ts.map +1 -0
  71. package/dist/tools/error/index.js +13 -0
  72. package/dist/tools/error/index.js.map +1 -0
  73. package/dist/tools/hasPurgatory.d.ts +4 -0
  74. package/dist/tools/hasPurgatory.d.ts.map +1 -0
  75. package/dist/tools/hasPurgatory.js +9 -0
  76. package/dist/tools/hasPurgatory.js.map +1 -0
  77. package/dist/tools/index.d.ts +21 -0
  78. package/dist/tools/index.d.ts.map +1 -0
  79. package/dist/tools/index.js +68 -0
  80. package/dist/tools/index.js.map +1 -0
  81. package/dist/tools/resolveAskPermissionToEnableCam.d.ts +4 -0
  82. package/dist/tools/resolveAskPermissionToEnableCam.d.ts.map +1 -0
  83. package/dist/tools/resolveAskPermissionToEnableCam.js +18 -0
  84. package/dist/tools/resolveAskPermissionToEnableCam.js.map +1 -0
  85. package/dist/tools/resolveGetRemoteStreams.d.ts +4 -0
  86. package/dist/tools/resolveGetRemoteStreams.d.ts.map +1 -0
  87. package/dist/tools/resolveGetRemoteStreams.js +15 -0
  88. package/dist/tools/resolveGetRemoteStreams.js.map +1 -0
  89. package/dist/tools/resolveHandleChangeTracks.d.ts +5 -0
  90. package/dist/tools/resolveHandleChangeTracks.d.ts.map +1 -0
  91. package/dist/tools/resolveHandleChangeTracks.js +14 -0
  92. package/dist/tools/resolveHandleChangeTracks.js.map +1 -0
  93. package/dist/tools/resolveOnMustStopPresentation.d.ts +4 -0
  94. package/dist/tools/resolveOnMustStopPresentation.d.ts.map +1 -0
  95. package/dist/tools/resolveOnMustStopPresentation.js +15 -0
  96. package/dist/tools/resolveOnMustStopPresentation.js.map +1 -0
  97. package/dist/tools/resolveOnUseLicense.d.ts +5 -0
  98. package/dist/tools/resolveOnUseLicense.d.ts.map +1 -0
  99. package/dist/tools/resolveOnUseLicense.js +15 -0
  100. package/dist/tools/resolveOnUseLicense.js.map +1 -0
  101. package/dist/tools/resolveSendMediaState.d.ts +7 -0
  102. package/dist/tools/resolveSendMediaState.d.ts.map +1 -0
  103. package/dist/tools/resolveSendMediaState.js +18 -0
  104. package/dist/tools/resolveSendMediaState.js.map +1 -0
  105. package/dist/tools/resolveSendRefusalToTurnOnCam.d.ts +4 -0
  106. package/dist/tools/resolveSendRefusalToTurnOnCam.d.ts.map +1 -0
  107. package/dist/tools/resolveSendRefusalToTurnOnCam.js +20 -0
  108. package/dist/tools/resolveSendRefusalToTurnOnCam.js.map +1 -0
  109. package/dist/tools/resolveSendRefusalToTurnOnMic.d.ts +4 -0
  110. package/dist/tools/resolveSendRefusalToTurnOnMic.d.ts.map +1 -0
  111. package/dist/tools/resolveSendRefusalToTurnOnMic.js +20 -0
  112. package/dist/tools/resolveSendRefusalToTurnOnMic.js.map +1 -0
  113. package/dist/tools/resolveStartPresentation.d.ts +10 -0
  114. package/dist/tools/resolveStartPresentation.d.ts.map +1 -0
  115. package/dist/tools/resolveStartPresentation.js +19 -0
  116. package/dist/tools/resolveStartPresentation.js.map +1 -0
  117. package/dist/tools/resolveStopShareSipConnector.d.ts +8 -0
  118. package/dist/tools/resolveStopShareSipConnector.d.ts.map +1 -0
  119. package/dist/tools/resolveStopShareSipConnector.js +19 -0
  120. package/dist/tools/resolveStopShareSipConnector.js.map +1 -0
  121. package/dist/tools/resolveUpdatePresentation.d.ts +10 -0
  122. package/dist/tools/resolveUpdatePresentation.d.ts.map +1 -0
  123. package/dist/tools/resolveUpdatePresentation.js +19 -0
  124. package/dist/tools/resolveUpdatePresentation.js.map +1 -0
  125. package/dist/tools/resolveUpdateRemoteStreams.d.ts +6 -0
  126. package/dist/tools/resolveUpdateRemoteStreams.d.ts.map +1 -0
  127. package/dist/tools/resolveUpdateRemoteStreams.js +18 -0
  128. package/dist/tools/resolveUpdateRemoteStreams.js.map +1 -0
  129. package/dist/tools/sendDTMFAccumulated.d.ts +10 -0
  130. package/dist/tools/sendDTMFAccumulated.d.ts.map +1 -0
  131. package/dist/tools/sendDTMFAccumulated.js +26 -0
  132. package/dist/tools/sendDTMFAccumulated.js.map +1 -0
  133. package/dist/tools/syncMediaState/index.d.ts +19 -0
  134. package/dist/tools/syncMediaState/index.d.ts.map +1 -0
  135. package/dist/tools/syncMediaState/index.js +55 -0
  136. package/dist/tools/syncMediaState/index.js.map +1 -0
  137. package/dist/tools/syncMediaState/resolveOnStartMainCam.d.ts +6 -0
  138. package/dist/tools/syncMediaState/resolveOnStartMainCam.d.ts.map +1 -0
  139. package/dist/tools/syncMediaState/resolveOnStartMainCam.js +15 -0
  140. package/dist/tools/syncMediaState/resolveOnStartMainCam.js.map +1 -0
  141. package/dist/tools/syncMediaState/resolveOnStartMic.d.ts +6 -0
  142. package/dist/tools/syncMediaState/resolveOnStartMic.d.ts.map +1 -0
  143. package/dist/tools/syncMediaState/resolveOnStartMic.js +15 -0
  144. package/dist/tools/syncMediaState/resolveOnStartMic.js.map +1 -0
  145. package/dist/tools/syncMediaState/resolveOnStopMainCam.d.ts +6 -0
  146. package/dist/tools/syncMediaState/resolveOnStopMainCam.d.ts.map +1 -0
  147. package/dist/tools/syncMediaState/resolveOnStopMainCam.js +15 -0
  148. package/dist/tools/syncMediaState/resolveOnStopMainCam.js.map +1 -0
  149. package/dist/tools/syncMediaState/resolveOnStopMic.d.ts +6 -0
  150. package/dist/tools/syncMediaState/resolveOnStopMic.d.ts.map +1 -0
  151. package/dist/tools/syncMediaState/resolveOnStopMic.js +15 -0
  152. package/dist/tools/syncMediaState/resolveOnStopMic.js.map +1 -0
  153. package/package.json +8 -7
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.getCodecFromSender = exports.resolveVideoSendingBalancer = exports.EUseLicense = exports.hasCanceledCallError = exports.eventNames = exports.causes = void 0;
29
+ exports.getCodecFromSender = exports.resolveVideoSendingBalancer = exports.EUseLicense = exports.hasCanceledCallError = exports.eventNames = exports.tools = exports.causes = exports.enableDebug = exports.disableDebug = exports.debug = void 0;
30
30
  const getCodecFromSender_1 = __importDefault(require("./utils/getCodecFromSender"));
31
31
  exports.getCodecFromSender = getCodecFromSender_1.default;
32
32
  const SipConnector_1 = __importStar(require("./SipConnector"));
@@ -36,7 +36,13 @@ const videoSendingBalancer_1 = __importDefault(require("./videoSendingBalancer")
36
36
  exports.resolveVideoSendingBalancer = videoSendingBalancer_1.default;
37
37
  const causes = __importStar(require("./causes"));
38
38
  exports.causes = causes;
39
+ const tools = __importStar(require("./tools"));
40
+ exports.tools = tools;
39
41
  const eventNames = __importStar(require("./eventNames"));
40
42
  exports.eventNames = eventNames;
43
+ var logger_1 = require("./logger");
44
+ Object.defineProperty(exports, "debug", { enumerable: true, get: function () { return logger_1.debug; } });
45
+ Object.defineProperty(exports, "disableDebug", { enumerable: true, get: function () { return logger_1.disableDebug; } });
46
+ Object.defineProperty(exports, "enableDebug", { enumerable: true, get: function () { return logger_1.enableDebug; } });
41
47
  exports.default = SipConnector_1.default;
42
48
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oFAA4D;AAY1D,6BAZK,4BAAkB,CAYL;AAXpB,+DAAiF;AAQ/E,qGARqB,mCAAoB,OAQrB;AACpB,4FAT2C,0BAAW,OAS3C;AARb,kFAAiE;AAS/D,sCATK,8BAA2B,CASL;AAR7B,iDAAmC;AAIjC,wBAAM;AAHR,yDAA2C;AAIzC,gCAAU;AAOZ,kBAAe,sBAAY,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oFAA4D;AAgB1D,6BAhBK,4BAAkB,CAgBL;AAfpB,+DAAiF;AAY/E,qGAZqB,mCAAoB,OAYrB;AACpB,4FAb2C,0BAAW,OAa3C;AAZb,kFAAiE;AAa/D,sCAbK,8BAA2B,CAaL;AAZ7B,iDAAmC;AAOjC,wBAAM;AANR,+CAAiC;AAO/B,sBAAK;AANP,yDAA2C;AAOzC,gCAAU;AALZ,mCAA4D;AAAnD,+FAAA,KAAK,OAAA;AAAE,sGAAA,YAAY,OAAA;AAAE,qGAAA,WAAW,OAAA;AAYzC,kBAAe,sBAAY,CAAC"}
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@krivega/cancelable-promise"),require("events-constructor"),require("stack-promises")):"function"==typeof define&&define.amd?define(["exports","@krivega/cancelable-promise","events-constructor","stack-promises"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sipConnector={},e.cancelablePromise,e.Events,e.createStackPromises)}(this,(function(e,t,s,n){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=i(s),o=i(n);const a=e=>e.getStats().then((e=>{const t=(s="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===s)));var s;return null==t?void 0:t.mimeType}));function c(e,t,s,n){return new(s||(s=Promise))((function(i,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}const d="Request Timeout",h="Rejected",l="Terminated",u="Canceled";var g=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:d,SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:h,REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:l,WEBRTC_ERROR:"WebRTC Error",CANCELED:u,NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"});const _="incomingCall",m="declinedIncomingCall",S="failedIncomingCall",f="terminatedIncomingCall",E="connecting",C="connected",v="disconnected",p="newRTCSession",N="registered",T="unregistered",R="registrationFailed",M="sipEvent",P="availableSecondRemoteStream",A="notAvailableSecondRemoteStream",w="mustStopPresentation",b="shareState",I="enterRoom",y="useLicense",O="peerconnection:confirmed",D="peerconnection:ontrack",U="channels",q="channels:notify",k="ended:fromserver",x="main-cam-control",B="admin-stop-main-cam",W="admin-start-main-cam",L="admin-stop-mic",H="admin-start-mic",F="admin-force-sync-media-state",j="participant:added-to-list-moderators",V="participant:removed-from-list-moderators",X="participant:move-request-to-conference",Y="participant:move-request-to-stream",J="participant:canceling-word-request",$="webcast:started",z="webcast:stopped",G="account:changed",K="account:deleted",Q="conference:participant-token-issued",Z="ended",ee="confirmed",te="peerconnection",se="failed",ne="newDTMF",ie="newInfo",re="presentation:ended",oe="presentation:failed",ae=[_,m,f,S,J,Y,X,q,Q,G,K,$,z,j,V],ce=[E,C,v,p,N,T,R,"newMessage",M],de=[P,A,w,b,I,y,O,D,U,k,x,W,B,L,H,F],he=[Z,E,"sending","reinvite","replaces","refer","progress","accepted",ee,te,se,"muted","unmuted",ne,ie,"hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end",re,oe],le=[...ce,...ae],ue=[...he,...de];var ge=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:ae,UA_JSSIP_EVENT_NAMES:ce,SESSION_SYNTHETICS_EVENT_NAMES:de,SESSION_JSSIP_EVENT_NAMES:he,UA_EVENT_NAMES:le,SESSION_EVENT_NAMES:ue});const _e="application/vinteo.webrtc.sharedesktop",me="application/vinteo.webrtc.maincam",Se="X-WEBRTC-INPUT-CHANNELS",fe="X-WEBRTC-OUTPUT-CHANNELS",Ee="X-WEBRTC-SYNC",Ce="x-webrtc-share-state",ve="YOUCANRECEIVECONTENT",pe="CONTENTEND";const Ne=e=>e.trim().replace(/ /g,"_"),Te=(Re=1e5,Me=99999999,()=>Math.floor(Math.random()*(Me-Re))+Re);var Re,Me;const Pe=(e,{videoMode:t,audioMode:s}={})=>{if(!e||"recvonly"===t&&"recvonly"===s)return;const n=[..."recvonly"===s?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],i=new MediaStream(n);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},Ae=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,we=Ae(1),be=Ae(void 0),Ie=(e,t,s)=>{const n=e.getParameters();n.encodings&&0!==n.encodings.length||(n.encodings=[{}]);const[i]=n.encodings,r=i.scaleResolutionDownBy,o=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&we(s,t))return s})(t.scaleResolutionDownBy,r);let a=!1;void 0!==o&&(n.encodings[0].scaleResolutionDownBy=o,a=!0);const c=i.maxBitrate,d=((e,t)=>{if(be(e,t))return e})(t.maxBitrate,c);return void 0!==d&&(n.encodings[0].maxBitrate=d,a=!0),a?(s&&s(n),e.setParameters(n).then((()=>({parameters:n,isChanged:a})))):Promise.resolve({parameters:n,isChanged:a})},ye="local",Oe="remote";var De,Ue,qe,ke;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(De||(De={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(Ue||(Ue={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}(qe||(qe={})),e.EUseLicense=void 0,(ke=e.EUseLicense||(e.EUseLicense={})).AUDIO="AUDIO",ke.VIDEO="VIDEO",ke.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION";const xe="SipConnector";const Be=(e,t)=>!!e&&!!t&&e.toLowerCase().includes(t.toLowerCase()),We=e=>1e6*e,Le=We(.06),He=We(4),Fe=(e,t)=>(e=>Be(e,"av1"))(t)?.6*e:e,je=(e,t)=>{const s=(e=>e<=64?Le:e<=128?We(.12):e<=256?We(.25):e<=384?We(.32):e<=426?We(.38):e<=640?We(.5):e<=848?We(.7):e<=1280?We(1):e<=1920?We(2):He)(e);return Fe(s,t)},Ve=o.default(),Xe=e=>(Ve.add(e),Ve().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),Ye=({sender:e,scaleResolutionDownBy:t,maxBitrate:s,onSetParameters:n})=>Xe((()=>Ie(e,{scaleResolutionDownBy:t,maxBitrate:s},n))),Je=({sender:e,codec:t},s)=>{const n=(e=>Fe(Le,e))(t);return Ye({sender:e,maxBitrate:n,onSetParameters:s,scaleResolutionDownBy:200})},$e=({sender:e,track:t,codec:s},n)=>{const i=t.getSettings().width,r=je(i,s);return Ye({sender:e,maxBitrate:r,onSetParameters:n,scaleResolutionDownBy:1})},ze=({mainCam:e,resolutionMainCam:t,sender:s,track:n,codec:i},r)=>{switch(e){case De.PAUSE_MAIN_CAM:return Je({sender:s,codec:i},r);case De.RESUME_MAIN_CAM:return $e({sender:s,track:n,codec:i},r);case De.MAX_MAIN_CAM_RESOLUTION:return t?(({sender:e,track:t,resolution:s,codec:n},i)=>{const r=t.getSettings(),o=r.width,a=r.height,[c,d]=s.split("x"),h=o/+c,l=a/+d,u=Math.max(h,l,1),g=je(+c,n);return Ye({sender:e,maxBitrate:g,onSetParameters:i,scaleResolutionDownBy:u})})({sender:s,track:n,codec:i,resolution:t},r):$e({sender:s,track:n,codec:i},r);default:return $e({sender:s,track:n,codec:i},r)}},Ge={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},Ke=({mainCam:e,resolutionMainCam:t,connection:s,onSetParameters:n,ignoreForCodec:i})=>c(void 0,void 0,void 0,(function*(){const r=(e=>e.find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)})))(s.getSenders());if(!r||!r.track)return Ge;const o=yield a(r);return Be(o,i)?Ge:ze({mainCam:e,resolutionMainCam:t,sender:r,codec:o,track:r.track},n)}));e.causes=g,e.default=class{constructor({JsSIP:e}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger(E,void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const n=this.incomingSession,i=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(m,i),t(n.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if(e===Oe){this.incomingSession=t;const e=this.remoteCallerData;t.on(se,(({originator:t})=>{this.removeIncomingSession(),t!==ye?this._uaEvents.trigger(S,e):this._uaEvents.trigger(f,e)})),this._uaEvents.trigger(_,e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:n=!1,sipServerUrl:i,sipWebSocketServerURL:r,remoteAddress:o,extraHeaders:a=[],sdpSemantics:d="plan-b",sessionTimers:h=!1,registerExpires:l=300,connectionRecoveryMinInterval:u=2,connectionRecoveryMaxInterval:g=6,userAgent:_})=>c(this,void 0,void 0,(function*(){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!s)throw new Error("password is required for authorized connection");let c;this._connectionConfiguration={sipServerUrl:i,displayName:e,register:n,user:t,password:s},this._init({sipServerUrl:i,sipWebSocketServerURL:r}),c=n&&t?t.trim():Te();const m={password:s,register:n,display_name:Ne(e),user_agent:_,sdp_semantics:d,sockets:[this.socket],uri:this.getSipServerUrl(c),session_timers:h,register_expires:l,connection_recovery_min_interval:u,connection_recovery_max_interval:g};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!m.register,this.ua=new this.JsSIP.UA(m),this._uaEvents.eachTriggers(((e,t)=>{const s=ce.find((e=>e===t));s&&this.ua.on(s,e)}));const S=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(o),f=[...S,...a];return this.ua.registrator().setExtraHeaders(f),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{i(),e(this.ua)},n=e=>{i(),t(e)},i=()=>{this.off(N,s),this.off(R,n),this.off(C,s),this.off(v,n)};(()=>{this.isRegisterConfig?(this.on(N,s),this.on(R,n)):this.on(C,s),this.on(v,n)})(),this.on(p,this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,n)=>{let i=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(i=this.ua.set("display_name",Ne(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=i||r;r&&this.isRegisterConfig?this.register().then((()=>s(o))).catch(n):o?s(o):n(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>c(this,void 0,void 0,(function*(){this.off(p,this.handleNewRTCSession);const e=new Promise((e=>{this.once(v,(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(v,void 0)):this._uaEvents.trigger(v,void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:n,iceServers:i,videoMode:r,audioMode:o,degradationPreference:a,offerToReceiveAudio:c=!0,offerToReceiveVideo:d=!0})=>new Promise(((h,l)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(h).catch(l),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Pe(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:n,videoMode:i,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const s=he.find((e=>e===t));s&&d.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const h=Pe(e,{videoMode:i,audioMode:r});d.answer({extraHeaders:s,videoMode:i,audioMode:r,degradationPreference:o,mediaStream:h,pcConfig:{iceServers:n}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const n=()=>{this.offSession(te,a),this.offSession(ee,c)},i=()=>{this.offSession(se,r),this.offSession(Z,r)},r=e=>{n(),i(),s(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger(D,o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger(O,o),n(),i(),t(o)};(()=>{this.onSession(te,a),this.onSession(ee,c)})(),(()=>{this.onSession(se,r),this.onSession(Z,r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{const n=this.session;n?(this.onceSession(ne,(({originator:e})=>{e===ye&&t()})),n.sendDTMF(e,{duration:120,interToneGap:600})):s(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>c(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case ve:this._sessionEvents.trigger(P,void 0);break;case pe:this._sessionEvents.trigger(A,void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger(w,void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader(Se),s=e.getHeader(fe);if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger(U,e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(V,t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(j,t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger($,s)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(z,s)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger(G,void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger(K,void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const n={conference:e,participant:t,jwt:s};this._uaEvents.trigger(Q,n)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger(q,t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(X,t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(J,t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(Y,t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger(I,t)},this._triggerShareState=e=>{const t=e.getHeader(Ce);this._sessionEvents.trigger(b,t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader(Ee),n=s===qe.ADMIN_SYNC_FORCED;if(t===De.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(W,{isSyncForced:n});else if(t===De.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(B,{isSyncForced:n});else if(t!==De.RESUME_MAIN_CAM&&t!==De.PAUSE_MAIN_CAM||!s){const s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger(x,{mainCam:t,resolutionMainCam:s})}else this._sessionEvents.trigger(F,{isSyncForced:n})},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC"),s=e.getHeader(Ee)===qe.ADMIN_SYNC_FORCED;t===Ue.ADMIN_START_MIC?this._sessionEvents.trigger(H,{isSyncForced:s}):t===Ue.ADMIN_STOP_MIC&&this._sessionEvents.trigger(L,{isSyncForced:s})},this._triggerUseLicense=e=>{const t=e.getHeader("X-WEBRTC-USE-LICENSE");this._sessionEvents.trigger(y,t)},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,n=s.getHeader("content-type");if(n)switch(n){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case _e:this._triggerShareState(s);break;case me:this._triggerMainCamControl(s);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(s);break;case"application/vinteo.webrtc.uselic":this._triggerUseLicense(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;t===Oe&&this._sessionEvents.trigger(k,e),this._restoreSession()},this.JsSIP=e,this._sessionEvents=new r.default(ue),this._uaEvents=new r.default(le),this._cancelableConnect=new t.CancelableRequest(this._connect,{moduleName:xe,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new t.CancelableRequest(this._createUa,{moduleName:xe}),this._cancelableDisconnect=new t.CancelableRequest(this._disconnect,{moduleName:xe}),this._cancelableSet=new t.CancelableRequest(this._set,{moduleName:xe}),this._cancelableCall=new t.CancelableRequest(this._call,{moduleName:xe}),this._cancelableAnswer=new t.CancelableRequest(this._answer,{moduleName:xe}),this._cancelableSendDTMF=new t.CancelableRequest(this._sendDTMF,{moduleName:xe}),this.onSession(b,this._handleShareState),this.onSession(ie,this._handleNewInfo),this.on(M,this._handleSipEvent),this.onSession(se,this._handleEnded),this.onSession(Z,this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on(N,e),this.ua.on(R,t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on(T,e),this.ua.unregister()):t(new Error("ua is not registered"))}))}sendOptions(e,t,s){return this.ua?new Promise(((n,i)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{n()},failed:e=>{i(e)}}})}catch(e){i(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo(me,void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}_sendPresentation(e,t,{maxBitrate:s,degradationPreference:n,isNeedReinvite:i=!0,isP2P:r=!1}){const o=Pe(t);this._streamPresentationCurrent=o;const a=r?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"],c=e.sendInfo(_e,void 0,{extraHeaders:a}).then((()=>e.startPresentation(o,i,n))).then((()=>{const{connection:e}=this;if(!e||void 0===s)return;return((e,t,s)=>{const n=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return n?Ie(n,{maxBitrate:s}):Promise.resolve()})(e.getSenders(),t,s)})).then((()=>t)).catch((e=>{throw this._sessionEvents.trigger(oe,e),e}));return this.promisePendingStartPresentation=c,c.finally((()=>{this.promisePendingStartPresentation=void 0}))}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:n,degradationPreference:i}={}){const r=this.establishedSession;return r?this._streamPresentationCurrent?Promise.reject(new Error("Presentation is already started")):this._sendPresentation(r,e,{isNeedReinvite:t,isP2P:s,maxBitrate:n,degradationPreference:i}):Promise.reject(new Error("No session established"))}stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation||Promise.resolve();const n=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],i=this.establishedSession;return i&&t&&(s=s.then((()=>i.sendInfo(_e,void 0,{extraHeaders:n}))).then((()=>i.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger(oe,e),e}))),!i&&t&&this._sessionEvents.trigger(re,t),this.promisePendingStopPresentation=s,s.finally((()=>{this._resetPresentation()}))}updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:n}={}){return c(this,void 0,void 0,(function*(){const i=this.establishedSession;return i?this._streamPresentationCurrent?(this.promisePendingStartPresentation&&(yield this.promisePendingStartPresentation),this._sendPresentation(i,e,{isP2P:t,maxBitrate:s,degradationPreference:n,isNeedReinvite:!1})):Promise.reject(new Error("Presentation has not started yet")):Promise.reject(new Error("No session established"))}))}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,n,i,r;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(n=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===n?void 0:n.uri.host,incomingNumber:null===(r=null===(i=null==this?void 0:this.incomingSession)||void 0===i?void 0:i.remote_identity)||void 0===r?void 0:r.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!(!this.ua||!this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,n=this._remoteStreams[s]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[s]=n,n}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,n)=>{if("audio"===s.kind)return;const i=s,r=e[n-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(i,o);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession(U)}waitSyncMediaState(){return this.waitSession(F)}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}sendMediaState({cam:e,mic:t},s={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const n=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},s),{extraHeaders:n}))}_sendRefusalToTurnOn(e,t={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const s=[`X-Vinteo-Media-Type: ${"mic"==e?0:1}`];return this.session.sendInfo("application/vinteo.webrtc.refusal",void 0,Object.assign(Object.assign({},t),{extraHeaders:s}))}sendRefusalToTurnOnMic(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",e)}sendRefusalToTurnOnCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",e)}},e.eventNames=ge,e.getCodecFromSender=a,e.hasCanceledCallError=(e=new Error)=>{const{originator:s,cause:n}=e;return!!t.isCanceledError(e)||"string"==typeof n&&(n===d||n===h||s===ye&&(n===u||n===l))},e.resolveVideoSendingBalancer=(e,{ignoreForCodec:t,onSetParameters:s}={})=>{const n=()=>{const{connection:n}=e;return n?Ke({connection:n,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))};let i=n;const r=n=>{i=()=>{const{mainCam:i,resolutionMainCam:r}=n,{connection:o}=e;return o?Ke({mainCam:i,resolutionMainCam:r,connection:o,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))},i()};return{subscribe:()=>{e.onSession("main-cam-control",r)},unsubscribe:()=>{e.offSession("main-cam-control",r)},balanceByTrack:n,resetMainCamControl(){i=n},reBalance:()=>i()}},Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@krivega/cancelable-promise"),require("events-constructor"),require("stack-promises"),require("debug"),require("lodash/debounce"),require("sequent-promises"),require("lodash/flow"),require("lodash/split")):"function"==typeof define&&define.amd?define(["exports","@krivega/cancelable-promise","events-constructor","stack-promises","debug","lodash/debounce","sequent-promises","lodash/flow","lodash/split"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sipConnector={},e.cancelablePromise,e.Events,e.createStackPromises,e.debug,e.debounce,e.sequentPromises,e.flow,e.split)}(this,(function(e,t,s,n,i,r,o,a,c){"use strict";function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=d(s),h=d(n),u=d(i),m=d(r),g=d(o),_=d(a),S=d(c);const E=e=>e.getStats().then((e=>{const t=(s="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===s)));var s;return null==t?void 0:t.mimeType}));function C(e,t,s,n){return new(s||(s=Promise))((function(i,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}const f="Request Timeout",v="Rejected",p="Not Found",R="Terminated",N="Canceled",P="Bad Media Description";var T=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:f,SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:v,REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:p,ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:R,WEBRTC_ERROR:"WebRTC Error",CANCELED:N,NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:P,RTP_TIMEOUT:"RTP Timeout"});const M="incomingCall",A="declinedIncomingCall",b="failedIncomingCall",w="terminatedIncomingCall",I="connecting",O="connected",y="disconnected",D="newRTCSession",U="registered",k="unregistered",q="registrationFailed",F="sipEvent",B="availableSecondRemoteStream",L="notAvailableSecondRemoteStream",x="mustStopPresentation",W="shareState",H="enterRoom",V="useLicense",j="peerconnection:confirmed",X="peerconnection:ontrack",Y="channels",$="channels:notify",J="ended:fromserver",G="main-cam-control",K="admin-stop-main-cam",z="admin-start-main-cam",Q="admin-stop-mic",Z="admin-start-mic",ee="admin-force-sync-media-state",te="participant:added-to-list-moderators",se="participant:removed-from-list-moderators",ne="participant:move-request-to-conference",ie="participant:move-request-to-stream",re="participant:canceling-word-request",oe="webcast:started",ae="webcast:stopped",ce="account:changed",de="account:deleted",le="conference:participant-token-issued",he="ended",ue="confirmed",me="peerconnection",ge="failed",_e="newDTMF",Se="newInfo",Ee="presentation:ended",Ce="presentation:failed",fe=[M,A,w,b,re,ie,ne,$,le,ce,de,oe,ae,te,se],ve=[I,O,y,D,U,k,q,"newMessage",F],pe=[B,L,x,W,H,V,j,X,Y,J,G,z,K,Q,Z,ee],Re=[he,I,"sending","reinvite","replaces","refer","progress","accepted",ue,me,ge,"muted","unmuted",_e,Se,"hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end",Ee,Ce],Ne=[...ve,...fe],Pe=[...Re,...pe];var Te=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:fe,UA_JSSIP_EVENT_NAMES:ve,SESSION_SYNTHETICS_EVENT_NAMES:pe,SESSION_JSSIP_EVENT_NAMES:Re,UA_EVENT_NAMES:Ne,SESSION_EVENT_NAMES:Pe});const Me="application/vinteo.webrtc.sharedesktop",Ae="application/vinteo.webrtc.maincam",be="X-WEBRTC-INPUT-CHANNELS",we="X-WEBRTC-OUTPUT-CHANNELS",Ie="X-WEBRTC-SYNC",Oe="x-webrtc-share-state",ye="YOUCANRECEIVECONTENT",De="CONTENTEND";const Ue=e=>e.trim().replace(/ /g,"_"),ke=(qe=1e5,Fe=99999999,()=>Math.floor(Math.random()*(Fe-qe))+qe);var qe,Fe;const Be=(e,{videoMode:t,audioMode:s}={})=>{if(!e||"recvonly"===t&&"recvonly"===s)return;const n=[..."recvonly"===s?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],i=new MediaStream(n);return i.getTracks=()=>[...i.getAudioTracks(),...i.getVideoTracks()],i},Le=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,xe=Le(1),We=Le(void 0),He=(e,t,s)=>{const n=e.getParameters();n.encodings&&0!==n.encodings.length||(n.encodings=[{}]);const[i]=n.encodings,r=i.scaleResolutionDownBy,o=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&xe(s,t))return s})(t.scaleResolutionDownBy,r);let a=!1;void 0!==o&&(n.encodings[0].scaleResolutionDownBy=o,a=!0);const c=i.maxBitrate,d=((e,t)=>{if(We(e,t))return e})(t.maxBitrate,c);return void 0!==d&&(n.encodings[0].maxBitrate=d,a=!0),a?(s&&s(n),e.setParameters(n).then((()=>({parameters:n,isChanged:a})))):Promise.resolve({parameters:n,isChanged:a})},Ve="local",je="remote";var Xe,Ye,$e,Je;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(Xe||(Xe={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(Ye||(Ye={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}($e||($e={})),e.EUseLicense=void 0,(Je=e.EUseLicense||(e.EUseLicense={})).AUDIO="AUDIO",Je.VIDEO="VIDEO",Je.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION";const Ge="SipConnector";const Ke=(e,t)=>!!e&&!!t&&e.toLowerCase().includes(t.toLowerCase()),ze=e=>1e6*e,Qe=ze(.06),Ze=ze(4),et=(e,t)=>(e=>Ke(e,"av1"))(t)?.6*e:e,tt=(e,t)=>{const s=(e=>e<=64?Qe:e<=128?ze(.12):e<=256?ze(.25):e<=384?ze(.32):e<=426?ze(.38):e<=640?ze(.5):e<=848?ze(.7):e<=1280?ze(1):e<=1920?ze(2):Ze)(e);return et(s,t)},st=h.default(),nt=e=>(st.add(e),st().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),it=({sender:e,scaleResolutionDownBy:t,maxBitrate:s,onSetParameters:n})=>nt((()=>He(e,{scaleResolutionDownBy:t,maxBitrate:s},n))),rt=({sender:e,codec:t},s)=>{const n=(e=>et(Qe,e))(t);return it({sender:e,maxBitrate:n,onSetParameters:s,scaleResolutionDownBy:200})},ot=({sender:e,track:t,codec:s},n)=>{const i=t.getSettings().width,r=tt(i,s);return it({sender:e,maxBitrate:r,onSetParameters:n,scaleResolutionDownBy:1})},at=({mainCam:e,resolutionMainCam:t,sender:s,track:n,codec:i},r)=>{switch(e){case Xe.PAUSE_MAIN_CAM:return rt({sender:s,codec:i},r);case Xe.RESUME_MAIN_CAM:return ot({sender:s,track:n,codec:i},r);case Xe.MAX_MAIN_CAM_RESOLUTION:return t?(({sender:e,track:t,resolution:s,codec:n},i)=>{const r=t.getSettings(),o=r.width,a=r.height,[c,d]=s.split("x"),l=o/+c,h=a/+d,u=Math.max(l,h,1),m=tt(+c,n);return it({sender:e,maxBitrate:m,onSetParameters:i,scaleResolutionDownBy:u})})({sender:s,track:n,codec:i,resolution:t},r):ot({sender:s,track:n,codec:i},r);default:return ot({sender:s,track:n,codec:i},r)}},ct={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}},dt=({mainCam:e,resolutionMainCam:t,connection:s,onSetParameters:n,ignoreForCodec:i})=>C(void 0,void 0,void 0,(function*(){const r=(e=>e.find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)})))(s.getSenders());if(!r||!r.track)return ct;const o=yield E(r);return Ke(o,i)?ct:at({mainCam:e,resolutionMainCam:t,sender:r,codec:o,track:r.track},n)})),lt=e=>{const{url:t,cause:s}=e;let n=t;return s!==P&&s!==p||(n=`${e.message.to.uri.user}@${e.message.to.uri.host}`),n};var ht;!function(e){e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK"}(ht||(ht={}));var ut=Object.freeze({__proto__:null,getLinkError:lt,getTypeFromError:(e=new Error)=>{var t;const{cause:s,socket:n}=e;let i=ht.CONNECT_SERVER_FAILED;return"Forbidden"===s?i=ht.WRONG_USER_OR_PASSWORD:s===P?i=ht.BAD_MEDIA_ERROR:s===p?i=ht.NOT_FOUND_ERROR:n&&3===(null===(t=null==n?void 0:n._ws)||void 0===t?void 0:t.readyState)?i=ht.WS_CONNECTION_FAILED:lt(e)&&(i=ht.CONNECT_SERVER_FAILED_BY_LINK),i},getValuesFromError:(e=new Error)=>{const{code:t,cause:s,message:n}=e,i=lt(e),r={};return n&&(r.message=n),i&&(r.link=i),t&&(r.code=t),s&&(r.cause=s),r}});const mt="sip-connector",gt=u.default(mt),_t=e=>"purgatory"===e,St=e=>()=>(gt("getRemoteStreams"),e.getRemoteStreams()),Et=e=>({track:t})=>{(({kind:e,readyState:t})=>"video"===e&&"live"===t)(t)&&e()},Ct=({getRemoteStreams:e,setRemoteStreams:t})=>m.default((()=>{const s=e();gt("remoteStreams",s),s&&t(s)}),200);var ft=Object.freeze({__proto__:null,error:ut,createSyncMediaState:({sipConnector:e})=>{const t=(e,t)=>(s={isSyncForced:!1})=>s.isSyncForced?e():t(),s=(e=>t=>(gt("onStartMainCam"),e.onSession("admin-start-main-cam",t)))(e),n=(e=>t=>(gt("onStopMainCam"),e.onSession("admin-stop-main-cam",t)))(e),i=(e=>t=>(gt("onStartMic"),e.onSession("admin-start-mic",t)))(e),r=(e=>t=>(gt("onStopMic"),e.onSession("admin-stop-mic",t)))(e);let o=()=>{},a=()=>{},c=()=>{},d=()=>{};return{start:e=>{(({onStartMainCamForced:e,onStartMainCamNotForced:l,onStopMainCamForced:h,onStopMainCamNotForced:u,onStartMicForced:m,onStartMicNotForced:g,onStopMicForced:_,onStopMicNotForced:S})=>{const E=t(e,l);o=s(E);const C=t(h,u);a=n(C);const f=t(m,g);c=i(f);const v=t(_,S);d=r(v)})(e)},stop:()=>{o(),a(),c(),d()}}},resolveAnswerIncomingCall:e=>t=>{const{mediaStream:s,extraHeaders:n,iceServers:i,degradationPreference:r,setRemoteStreams:o,onBeforeProgressCall:a,onSuccessProgressCall:c,onEnterPurgatory:d,onEnterConference:l,onFailProgressCall:h,onFinishProgressCall:u,onEndedCall:m}=t,g=Ct({setRemoteStreams:o,getRemoteStreams:St(e)}),_=Et(g);gt("answerIncomingCall",t);let S,E=!1;const C=(gt("subscribeEnterConference: onEnterConference",l),d||l?e.onSession("enterRoom",(e=>{gt("enterRoom",{_room:e,isSuccessProgressCall:E}),S=e,_t(S)?d&&d():l&&l({isSuccessProgressCall:E})})):()=>{});if(gt("onBeforeProgressCall"),a){a((()=>{const{remoteCallerData:t}=e,{incomingNumber:s}=t;return s})())}return e.answerToIncomingCall({mediaStream:s,extraHeaders:n,iceServers:i,degradationPreference:r,ontrack:_}).then((t=>(gt("onSuccess"),E=!0,g(),c&&c({isPurgatory:_t(S)}),e.onceRaceSession(["ended","failed"],(()=>{C(),m&&m()})),t))).catch((e=>{throw gt("onFail"),h&&h(),C(),e})).finally((()=>{gt("onFinish"),u&&u()}))},resolveConnectToServer:e=>{const s=e=>{if(!t.isCanceledError(e))throw e;return!1};return t=>{const{userAgent:n,sipWebSocketServerURL:i,sipServerUrl:r,remoteAddress:o,displayName:a,name:c,password:d,isRegisteredUser:l,sdpSemantics:h,isDisconnectOnFail:u}=t;return gt("connectToServer",t),e.connect({userAgent:n,sdpSemantics:h,sipWebSocketServerURL:i,sipServerUrl:r,remoteAddress:o,displayName:a,password:d,user:c,register:l}).then((()=>(gt("connectToServer then"),!0))).catch((t=>(gt("connectToServer catch: error",t),u?e.disconnect().then((()=>s(t))).catch((()=>s(t))):s(t))))}},resolveCallToServer:e=>t=>{const{conference:s,mediaStream:n,extraHeaders:i,iceServers:r,degradationPreference:o,setRemoteStreams:a,onBeforeProgressCall:c,onSuccessProgressCall:d,onEnterPurgatory:l,onEnterConference:h,onFailProgressCall:u,onFinishProgressCall:m,onEndedCall:g}=t,_=Ct({setRemoteStreams:a,getRemoteStreams:St(e)}),S=Et(_);gt("callToServer",t);let E,C=!1;const f=(gt("subscribeEnterConference: onEnterConference",h),l||h?e.onSession("enterRoom",(e=>{gt("enterRoom",{_room:e,isSuccessProgressCall:C}),E=e,_t(E)?l&&l():h&&h({isSuccessProgressCall:C})})):()=>{});return gt("onBeforeProgressCall"),c&&c(s),(gt("startCall"),e.call({mediaStream:n,extraHeaders:i,iceServers:r,degradationPreference:o,number:s,ontrack:S})).then((t=>(gt("onSuccess"),C=!0,_(),d&&d({isPurgatory:_t(E)}),e.onceRaceSession(["ended","failed"],(()=>{f(),g&&g()})),t))).catch((e=>{throw gt("onFail"),u&&u(),f(),e})).finally((()=>{gt("onFinish"),m&&m()}))},resolveDisconnectFromServer:e=>()=>(gt("disconnectFromServer"),e.disconnect().then((()=>(gt("disconnectFromServer: then"),!1))).catch((e=>(gt("disconnectFromServer: catch",e),!1)))),hasPurgatory:_t,resolveAskPermissionToEnableCam:e=>()=>e.isCallActive?(gt("askPermissionToEnableCam"),e.askPermissionToEnableCam()):Promise.resolve(),resolveStopShareSipConnector:({sipConnector:e})=>({isP2P:t=!1}={isP2P:!1})=>(gt("stopShareSipConnector"),e.stopPresentation({isP2P:t}).catch(gt)),resolveOnMustStopPresentation:e=>t=>(gt("onMustStopPresentation"),e.onSession("mustStopPresentation",t)),resolveOnUseLicense:e=>t=>(gt("onUseLicense"),e.onSession("useLicense",t)),resolveSendMediaState:e=>({isEnabledCam:t,isEnabledMic:s})=>e.isCallActive?(gt("sendMediaState"),e.sendMediaState({cam:t,mic:s})):Promise.resolve(),resolveSendRefusalToTurnOnCam:e=>()=>e.isCallActive?(gt("sendRefusalToTurnOnCam"),e.sendRefusalToTurnOnCam().catch((e=>{gt("sendRefusalToTurnOnCam: error",e)}))):Promise.resolve(),resolveSendRefusalToTurnOnMic:e=>()=>e.isCallActive?(gt("sendRefusalToTurnOnMic"),e.sendRefusalToTurnOnMic().catch((e=>{gt("sendRefusalToTurnOnMic: error",e)}))):Promise.resolve(),resolveStartPresentation:({maxBitrate:e=1e6,sipConnector:t})=>({mediaStream:s,isP2P:n=!1})=>(gt("startPresentation"),t.startPresentation(s,{isP2P:n,maxBitrate:e})),resolveUpdatePresentation:({sipConnector:e,maxBitrate:t=1e6})=>({mediaStream:s,isP2P:n=!1})=>(gt("updatePresentation"),e.updatePresentation(s,{isP2P:n,maxBitrate:t})),resolveUpdateRemoteStreams:Ct,resolveGetRemoteStreams:St,sendDTMFAccumulated:({accumulatedKeys:e,sendKey:t,canRunTask:s})=>{const n=(e=>_.default((e=>S.default(e,"")),(t=>t.map((t=>()=>e(t))))))(t),i=n(e);return g.default(i,s)}});Object.defineProperty(e,"debug",{enumerable:!0,get:function(){return u.default}}),e.causes=T,e.default=class{constructor({JsSIP:e}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger(I,void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const n=this.incomingSession,i=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger(A,i),t(n.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if(e===je){this.incomingSession=t;const e=this.remoteCallerData;t.on(ge,(({originator:t})=>{this.removeIncomingSession(),t!==Ve?this._uaEvents.trigger(b,e):this._uaEvents.trigger(w,e)})),this._uaEvents.trigger(M,e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:n=!1,sipServerUrl:i,sipWebSocketServerURL:r,remoteAddress:o,extraHeaders:a=[],sdpSemantics:c="plan-b",sessionTimers:d=!1,registerExpires:l=300,connectionRecoveryMinInterval:h=2,connectionRecoveryMaxInterval:u=6,userAgent:m})=>C(this,void 0,void 0,(function*(){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!s)throw new Error("password is required for authorized connection");let g;this._connectionConfiguration={sipServerUrl:i,displayName:e,register:n,user:t,password:s},this._init({sipServerUrl:i,sipWebSocketServerURL:r}),g=n&&t?t.trim():ke();const _={password:s,register:n,display_name:Ue(e),user_agent:m,sdp_semantics:c,sockets:[this.socket],uri:this.getSipServerUrl(g),session_timers:d,register_expires:l,connection_recovery_min_interval:h,connection_recovery_max_interval:u};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!_.register,this.ua=new this.JsSIP.UA(_),this._uaEvents.eachTriggers(((e,t)=>{const s=ve.find((e=>e===t));s&&this.ua.on(s,e)}));const S=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(o),E=[...S,...a];return this.ua.registrator().setExtraHeaders(E),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{i(),e(this.ua)},n=e=>{i(),t(e)},i=()=>{this.off(U,s),this.off(q,n),this.off(O,s),this.off(y,n)};(()=>{this.isRegisterConfig?(this.on(U,s),this.on(q,n)):this.on(O,s),this.on(y,n)})(),this.on(D,this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,n)=>{let i=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(i=this.ua.set("display_name",Ue(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=i||r;r&&this.isRegisterConfig?this.register().then((()=>s(o))).catch(n):o?s(o):n(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>C(this,void 0,void 0,(function*(){this.off(D,this.handleNewRTCSession);const e=new Promise((e=>{this.once(y,(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger(y,void 0)):this._uaEvents.trigger(y,void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:n,iceServers:i,videoMode:r,audioMode:o,degradationPreference:a,offerToReceiveAudio:c=!0,offerToReceiveVideo:d=!0})=>new Promise(((l,h)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(l).catch(h),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:Be(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:d}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:n,videoMode:i,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const s=Re.find((e=>e===t));s&&d.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const l=Be(e,{videoMode:i,audioMode:r});d.answer({extraHeaders:s,videoMode:i,audioMode:r,degradationPreference:o,mediaStream:l,pcConfig:{iceServers:n}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const n=()=>{this.offSession(me,a),this.offSession(ue,c)},i=()=>{this.offSession(ge,r),this.offSession(he,r)},r=e=>{n(),i(),s(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger(X,o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger(j,o),n(),i(),t(o)};(()=>{this.onSession(me,a),this.onSession(ue,c)})(),(()=>{this.onSession(ge,r),this.onSession(he,r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{const n=this.session;n?(this.onceSession(_e,(({originator:e})=>{e===Ve&&t()})),n.sendDTMF(e,{duration:120,interToneGap:600})):s(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>C(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case ye:this._sessionEvents.trigger(B,void 0);break;case De:this._sessionEvents.trigger(L,void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger(x,void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader(be),s=e.getHeader(we);if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger(Y,e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(se,t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger(te,t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(oe,s)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._uaEvents.trigger(ae,s)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger(ce,void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger(de,void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const n={conference:e,participant:t,jwt:s};this._uaEvents.trigger(le,n)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger($,t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ne,t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(re,t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger(ie,t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger(H,t)},this._triggerShareState=e=>{const t=e.getHeader(Oe);this._sessionEvents.trigger(W,t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader(Ie),n=s===$e.ADMIN_SYNC_FORCED;if(t===Xe.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger(z,{isSyncForced:n});else if(t===Xe.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger(K,{isSyncForced:n});else if(t!==Xe.RESUME_MAIN_CAM&&t!==Xe.PAUSE_MAIN_CAM||!s){const s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger(G,{mainCam:t,resolutionMainCam:s})}else this._sessionEvents.trigger(ee,{isSyncForced:n})},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC"),s=e.getHeader(Ie)===$e.ADMIN_SYNC_FORCED;t===Ye.ADMIN_START_MIC?this._sessionEvents.trigger(Z,{isSyncForced:s}):t===Ye.ADMIN_STOP_MIC&&this._sessionEvents.trigger(Q,{isSyncForced:s})},this._triggerUseLicense=e=>{const t=e.getHeader("X-WEBRTC-USE-LICENSE");this._sessionEvents.trigger(V,t)},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,n=s.getHeader("content-type");if(n)switch(n){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case Me:this._triggerShareState(s);break;case Ae:this._triggerMainCamControl(s);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(s);break;case"application/vinteo.webrtc.uselic":this._triggerUseLicense(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;t===je&&this._sessionEvents.trigger(J,e),this._restoreSession()},this.JsSIP=e,this._sessionEvents=new l.default(Pe),this._uaEvents=new l.default(Ne),this._cancelableConnect=new t.CancelableRequest(this._connect,{moduleName:Ge,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new t.CancelableRequest(this._createUa,{moduleName:Ge}),this._cancelableDisconnect=new t.CancelableRequest(this._disconnect,{moduleName:Ge}),this._cancelableSet=new t.CancelableRequest(this._set,{moduleName:Ge}),this._cancelableCall=new t.CancelableRequest(this._call,{moduleName:Ge}),this._cancelableAnswer=new t.CancelableRequest(this._answer,{moduleName:Ge}),this._cancelableSendDTMF=new t.CancelableRequest(this._sendDTMF,{moduleName:Ge}),this.onSession(W,this._handleShareState),this.onSession(Se,this._handleNewInfo),this.on(F,this._handleSipEvent),this.onSession(ge,this._handleEnded),this.onSession(he,this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on(U,e),this.ua.on(q,t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on(k,e),this.ua.unregister()):t(new Error("ua is not registered"))}))}sendOptions(e,t,s){return this.ua?new Promise(((n,i)=>{try{this.ua.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{n()},failed:e=>{i(e)}}})}catch(e){i(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const s=this.ua.configuration.uri;return this.sendOptions(s,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo(Ae,void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}_sendPresentation(e,t,{maxBitrate:s,degradationPreference:n,isNeedReinvite:i=!0,isP2P:r=!1}){const o=Be(t);this._streamPresentationCurrent=o;const a=r?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"],c=e.sendInfo(Me,void 0,{extraHeaders:a}).then((()=>e.startPresentation(o,i,n))).then((()=>{const{connection:e}=this;if(!e||void 0===s)return;return((e,t,s)=>{const n=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return n?He(n,{maxBitrate:s}):Promise.resolve()})(e.getSenders(),t,s)})).then((()=>t)).catch((e=>{throw this._sessionEvents.trigger(Ce,e),e}));return this.promisePendingStartPresentation=c,c.finally((()=>{this.promisePendingStartPresentation=void 0}))}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:n,degradationPreference:i}={}){const r=this.establishedSession;return r?this._streamPresentationCurrent?Promise.reject(new Error("Presentation is already started")):this._sendPresentation(r,e,{isNeedReinvite:t,isP2P:s,maxBitrate:n,degradationPreference:i}):Promise.reject(new Error("No session established"))}stopPresentation({isP2P:e=!1}={}){const t=this._streamPresentationCurrent;let s=this.promisePendingStartPresentation||Promise.resolve();const n=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],i=this.establishedSession;return i&&t&&(s=s.then((()=>i.sendInfo(Me,void 0,{extraHeaders:n}))).then((()=>i.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger(Ce,e),e}))),!i&&t&&this._sessionEvents.trigger(Ee,t),this.promisePendingStopPresentation=s,s.finally((()=>{this._resetPresentation()}))}updatePresentation(e,{isP2P:t=!1,maxBitrate:s,degradationPreference:n}={}){return C(this,void 0,void 0,(function*(){const i=this.establishedSession;return i?this._streamPresentationCurrent?(this.promisePendingStartPresentation&&(yield this.promisePendingStartPresentation),this._sendPresentation(i,e,{isP2P:t,maxBitrate:s,degradationPreference:n,isNeedReinvite:!1})):Promise.reject(new Error("Presentation has not started yet")):Promise.reject(new Error("No session established"))}))}_resetPresentation(){delete this._streamPresentationCurrent,this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,n,i,r;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(n=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===n?void 0:n.uri.host,incomingNumber:null===(r=null===(i=null==this?void 0:this.incomingSession)||void 0===i?void 0:i.remote_identity)||void 0===r?void 0:r.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!(!this.ua||!this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,n=this._remoteStreams[s]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[s]=n,n}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,n)=>{if("audio"===s.kind)return;const i=s,r=e[n-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(i,o);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession(Y)}waitSyncMediaState(){return this.waitSession(ee)}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}sendMediaState({cam:e,mic:t},s={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const n=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},s),{extraHeaders:n}))}_sendRefusalToTurnOn(e,t={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const s=[`X-Vinteo-Media-Type: ${"mic"==e?0:1}`];return this.session.sendInfo("application/vinteo.webrtc.refusal",void 0,Object.assign(Object.assign({},t),{extraHeaders:s}))}sendRefusalToTurnOnMic(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("mic",e)}sendRefusalToTurnOnCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");return this._sendRefusalToTurnOn("cam",e)}},e.disableDebug=()=>{u.default.enable(`-${mt}`)},e.enableDebug=()=>{u.default.enable(`${mt}`)},e.eventNames=Te,e.getCodecFromSender=E,e.hasCanceledCallError=(e=new Error)=>{const{originator:s,cause:n}=e;return!!t.isCanceledError(e)||"string"==typeof n&&(n===f||n===v||s===Ve&&(n===N||n===R))},e.resolveVideoSendingBalancer=(e,{ignoreForCodec:t,onSetParameters:s}={})=>{const n=()=>{const{connection:n}=e;return n?dt({connection:n,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))};let i=n;const r=n=>{i=()=>{const{mainCam:i,resolutionMainCam:r}=n,{connection:o}=e;return o?dt({mainCam:i,resolutionMainCam:r,connection:o,onSetParameters:s,ignoreForCodec:t}):Promise.reject(new Error("connection is not exist"))},i()};return{subscribe:()=>{e.onSession("main-cam-control",r)},unsubscribe:()=>{e.offSession("main-cam-control",r)},balanceByTrack:n,resetMainCamControl(){i=n},reBalance:()=>i()}},e.tools=ft,Object.defineProperty(e,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=index.umd.js.map