diff --git a/dist/sip-0.17.1.js b/dist/sip-0.17.1.js deleted file mode 100644 index 6ae99fccb..000000000 --- a/dist/sip-0.17.1.js +++ /dev/null @@ -1,20708 +0,0 @@ -/*! - * - * SIP version 0.17.1 - * Copyright (c) 2014-2020 Junction Networks, Inc - * Homepage: https://sipjs.com - * License: https://sipjs.com/license/ - * - * - * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ - * Homepage: http://jssip.net - * Copyright (c) 2012-2013 José Luis Millán - Versatica - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ~~~ end JsSIP license ~~~ - * - * - * - * - */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["SIP"] = factory(); - else - root["SIP"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "name", function() { return name; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; }); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); -/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _api__WEBPACK_IMPORTED_MODULE_1__) if(["name","version","Core","Web","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _api__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Grammar"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["NameAddrHeader"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["URI"]; }); - -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Core", function() { return _core__WEBPACK_IMPORTED_MODULE_3__; }); -/* harmony import */ var _platform_web__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(174); -/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Web", function() { return _platform_web__WEBPACK_IMPORTED_MODULE_4__; }); -// Helpful name and version exports - -const version = _version__WEBPACK_IMPORTED_MODULE_0__["LIBRARY_VERSION"]; -const name = "sip.js"; - -// Export api - -// Export grammar - -// Export namespaced core - - -// Export namespaced web - - - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LIBRARY_VERSION", function() { return LIBRARY_VERSION; }); -const LIBRARY_VERSION = "0.17.1"; - - -/***/ }), -/* 2 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionDescriptionHandlerError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionTerminatedError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["StateTransitionError"]; }); - -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(107); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return _bye__WEBPACK_IMPORTED_MODULE_1__["Bye"]; }); - -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(108); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return _emitter__WEBPACK_IMPORTED_MODULE_2__["EmitterImpl"]; }); - -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(109); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return _info__WEBPACK_IMPORTED_MODULE_3__["Info"]; }); - -/* harmony import */ var _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(110); -/* harmony import */ var _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(111); -/* harmony import */ var _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(112); -/* harmony import */ var _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(113); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return _invitation__WEBPACK_IMPORTED_MODULE_7__["Invitation"]; }); - -/* harmony import */ var _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(120); -/* harmony import */ var _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(121); -/* harmony import */ var _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _inviter_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(122); -/* harmony import */ var _inviter_options__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_inviter_options__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _inviter_options__WEBPACK_IMPORTED_MODULE_10__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _inviter_options__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(123); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return _inviter__WEBPACK_IMPORTED_MODULE_11__["Inviter"]; }); - -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(115); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return _message__WEBPACK_IMPORTED_MODULE_12__["Message"]; }); - -/* harmony import */ var _messager_message_options__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(124); -/* harmony import */ var _messager_message_options__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_messager_message_options__WEBPACK_IMPORTED_MODULE_13__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _messager_message_options__WEBPACK_IMPORTED_MODULE_13__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _messager_message_options__WEBPACK_IMPORTED_MODULE_13__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _messager_options__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(125); -/* harmony import */ var _messager_options__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_messager_options__WEBPACK_IMPORTED_MODULE_14__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _messager_options__WEBPACK_IMPORTED_MODULE_14__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _messager_options__WEBPACK_IMPORTED_MODULE_14__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _messager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(126); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return _messager__WEBPACK_IMPORTED_MODULE_15__["Messager"]; }); - -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(116); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; }); - -/* harmony import */ var _publisher_options__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(127); -/* harmony import */ var _publisher_options__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_publisher_options__WEBPACK_IMPORTED_MODULE_17__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publisher_options__WEBPACK_IMPORTED_MODULE_17__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publisher_options__WEBPACK_IMPORTED_MODULE_17__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(128); -/* harmony import */ var _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(129); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return _publisher_state__WEBPACK_IMPORTED_MODULE_19__["PublisherState"]; }); - -/* harmony import */ var _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(130); -/* harmony import */ var _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publisher__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(131); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return _publisher__WEBPACK_IMPORTED_MODULE_21__["Publisher"]; }); - -/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(117); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return _referral__WEBPACK_IMPORTED_MODULE_22__["Referral"]; }); - -/* harmony import */ var _registerer_options__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(132); -/* harmony import */ var _registerer_options__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_registerer_options__WEBPACK_IMPORTED_MODULE_23__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _registerer_options__WEBPACK_IMPORTED_MODULE_23__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _registerer_options__WEBPACK_IMPORTED_MODULE_23__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(133); -/* harmony import */ var _registerer_register_options__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_registerer_register_options__WEBPACK_IMPORTED_MODULE_24__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(134); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return _registerer_state__WEBPACK_IMPORTED_MODULE_25__["RegistererState"]; }); - -/* harmony import */ var _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(135); -/* harmony import */ var _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _registerer__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(136); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return _registerer__WEBPACK_IMPORTED_MODULE_27__["Registerer"]; }); - -/* harmony import */ var _session_bye_options__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(137); -/* harmony import */ var _session_bye_options__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_session_bye_options__WEBPACK_IMPORTED_MODULE_28__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_bye_options__WEBPACK_IMPORTED_MODULE_28__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_bye_options__WEBPACK_IMPORTED_MODULE_28__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(138); -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_session_delegate__WEBPACK_IMPORTED_MODULE_29__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_delegate__WEBPACK_IMPORTED_MODULE_29__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_delegate__WEBPACK_IMPORTED_MODULE_29__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(139); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(140); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler__WEBPACK_IMPORTED_MODULE_31__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler__WEBPACK_IMPORTED_MODULE_31__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_31__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_info_options__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(141); -/* harmony import */ var _session_info_options__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_session_info_options__WEBPACK_IMPORTED_MODULE_32__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_info_options__WEBPACK_IMPORTED_MODULE_32__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_info_options__WEBPACK_IMPORTED_MODULE_32__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_invite_options__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(142); -/* harmony import */ var _session_invite_options__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_session_invite_options__WEBPACK_IMPORTED_MODULE_33__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_invite_options__WEBPACK_IMPORTED_MODULE_33__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_invite_options__WEBPACK_IMPORTED_MODULE_33__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_message_options__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(143); -/* harmony import */ var _session_message_options__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_session_message_options__WEBPACK_IMPORTED_MODULE_34__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_message_options__WEBPACK_IMPORTED_MODULE_34__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_message_options__WEBPACK_IMPORTED_MODULE_34__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_options__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(144); -/* harmony import */ var _session_options__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_session_options__WEBPACK_IMPORTED_MODULE_35__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_options__WEBPACK_IMPORTED_MODULE_35__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_options__WEBPACK_IMPORTED_MODULE_35__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_refer_options__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(145); -/* harmony import */ var _session_refer_options__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_session_refer_options__WEBPACK_IMPORTED_MODULE_36__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_refer_options__WEBPACK_IMPORTED_MODULE_36__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_refer_options__WEBPACK_IMPORTED_MODULE_36__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(118); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session_state__WEBPACK_IMPORTED_MODULE_37__["SessionState"]; }); - -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(114); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return _session__WEBPACK_IMPORTED_MODULE_38__["Session"]; }); - -/* harmony import */ var _subscriber_options__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(146); -/* harmony import */ var _subscriber_options__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_subscriber_options__WEBPACK_IMPORTED_MODULE_39__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscriber_options__WEBPACK_IMPORTED_MODULE_39__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscriber_options__WEBPACK_IMPORTED_MODULE_39__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(147); -/* harmony import */ var _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscriber__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(148); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _subscriber__WEBPACK_IMPORTED_MODULE_41__["Subscriber"]; }); - -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(151); -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_subscription_delegate__WEBPACK_IMPORTED_MODULE_42__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription_options__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(152); -/* harmony import */ var _subscription_options__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_subscription_options__WEBPACK_IMPORTED_MODULE_43__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_options__WEBPACK_IMPORTED_MODULE_43__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_options__WEBPACK_IMPORTED_MODULE_43__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(150); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription_state__WEBPACK_IMPORTED_MODULE_44__["SubscriptionState"]; }); - -/* harmony import */ var _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(153); -/* harmony import */ var _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(154); -/* harmony import */ var _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(149); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _subscription__WEBPACK_IMPORTED_MODULE_47__["Subscription"]; }); - -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(155); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_transport__WEBPACK_IMPORTED_MODULE_48__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport__WEBPACK_IMPORTED_MODULE_48__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport__WEBPACK_IMPORTED_MODULE_48__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transport_state__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(156); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return _transport_state__WEBPACK_IMPORTED_MODULE_49__["TransportState"]; }); - -/* harmony import */ var _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(157); -/* harmony import */ var _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","TransportState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(119); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["SIPExtension"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["UserAgentRegisteredOptionTags"]; }); - -/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(158); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return _user_agent_state__WEBPACK_IMPORTED_MODULE_52__["UserAgentState"]; }); - -/* harmony import */ var _user_agent__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(159); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return _user_agent__WEBPACK_IMPORTED_MODULE_53__["UserAgent"]; }); - -/** - * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. - * @packageDocumentation - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/***/ }), -/* 3 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); - -/* harmony import */ var _request_pending__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _request_pending__WEBPACK_IMPORTED_MODULE_1__["RequestPendingError"]; }); - -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(104); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]; }); - -/* harmony import */ var _session_terminated__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(105); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _session_terminated__WEBPACK_IMPORTED_MODULE_3__["SessionTerminatedError"]; }); - -/* harmony import */ var _state_transition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(106); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _state_transition__WEBPACK_IMPORTED_MODULE_4__["StateTransitionError"]; }); - - - - - - - - -/***/ }), -/* 4 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return ContentTypeUnsupportedError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating an unsupported content type prevented execution. - * @public - */ -class ContentTypeUnsupportedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Unsupported content type."); - } -} - - -/***/ }), -/* 5 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _dialogs__WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["Exception"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransportError"]; }); - -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(84); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Levels"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["LoggerFactory"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); - -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _messages__WEBPACK_IMPORTED_MODULE_3__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _messages__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(44); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session__WEBPACK_IMPORTED_MODULE_4__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(79); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription__WEBPACK_IMPORTED_MODULE_5__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(48); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transactions__WEBPACK_IMPORTED_MODULE_6__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(88); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_core__WEBPACK_IMPORTED_MODULE_7__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(90); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["CancelUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PublishUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentServer"]; }); - -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(47); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return _timers__WEBPACK_IMPORTED_MODULE_9__["Timers"]; }); - -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(102); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_transport__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport__WEBPACK_IMPORTED_MODULE_10__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","ByeUserAgentClient","ByeUserAgentServer","CancelUserAgentClient","InfoUserAgentClient","InfoUserAgentServer","InviteUserAgentClient","InviteUserAgentServer","MessageUserAgentClient","MessageUserAgentServer","NotifyUserAgentClient","NotifyUserAgentServer","PublishUserAgentClient","PrackUserAgentClient","PrackUserAgentServer","ReInviteUserAgentClient","ReInviteUserAgentServer","ReSubscribeUserAgentClient","ReSubscribeUserAgentServer","ReferUserAgentClient","ReferUserAgentServer","RegisterUserAgentClient","RegisterUserAgentServer","SubscribeUserAgentClient","SubscribeUserAgentServer","UserAgentClient","UserAgentServer","Timers","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -// Directories - - - - - - - - - -// Files - - - - -/***/ }), -/* 6 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _dialog__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); - -/* harmony import */ var _dialog_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42); -/* harmony import */ var _dialog_state__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_dialog_state__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _dialog_state__WEBPACK_IMPORTED_MODULE_1__) if(["Dialog","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _dialog_state__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_dialog__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(43); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return _session_dialog__WEBPACK_IMPORTED_MODULE_2__["SessionDialog"]; }); - -/* harmony import */ var _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(78); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__["SubscriptionDialog"]; }); - - - - - - - -/***/ }), -/* 7 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return Dialog; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); - -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -class Dialog { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - constructor(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForUserAgentClient(outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const localSequenceNumber = outgoingRequestMessage.cseq; - const remoteSequenceNumber = undefined; - const callId = outgoingRequestMessage.callId; - const localTag = outgoingRequestMessage.fromTag; - const remoteTag = incomingResponseMessage.toTag; - if (!callId) { - // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { - // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { - // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { - // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { - // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - const localURI = outgoingRequestMessage.from.uri; - const remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - const early = incomingResponseMessage.statusCode < 200 ? true : false; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, early = false) { - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const routeSet = incomingRequestMessage.getHeaders("record-route"); - const contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const remoteSequenceNumber = incomingRequestMessage.cseq; - const localSequenceNumber = undefined; - const callId = incomingRequestMessage.callId; - const localTag = toTag; - const remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const remoteURI = incomingRequestMessage.from.uri; - const localURI = incomingRequestMessage.to.uri; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - /** Destructor. */ - dispose() { - this.core.dialogs.delete(this.id); - } - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get id() { - return this.dialogState.id; - } - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get early() { - return this.dialogState.early; - } - /** Call identifier component of the dialog id. */ - get callId() { - return this.dialogState.callId; - } - /** Local tag component of the dialog id. */ - get localTag() { - return this.dialogState.localTag; - } - /** Remote tag component of the dialog id. */ - get remoteTag() { - return this.dialogState.remoteTag; - } - /** Local sequence number (used to order requests from the UA to its peer). */ - get localSequenceNumber() { - return this.dialogState.localSequenceNumber; - } - /** Remote sequence number (used to order requests from its peer to the UA). */ - get remoteSequenceNumber() { - return this.dialogState.remoteSequenceNumber; - } - /** Local URI. */ - get localURI() { - return this.dialogState.localURI; - } - /** Remote URI. */ - get remoteURI() { - return this.dialogState.remoteURI; - } - /** Remote target. */ - get remoteTarget() { - return this.dialogState.remoteTarget; - } - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get routeSet() { - return this.dialogState.routeSet; - } - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get secure() { - return this.dialogState.secure; - } - /** The user agent core servicing this dialog. */ - get userAgentCore() { - return this.core; - } - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm() { - this.dialogState.early = false; - } - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - } - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - recomputeRouteSet(message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - } - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - createOutgoingRequestMessage(method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - const toUri = this.remoteURI; - const toTag = this.remoteTag; - const fromUri = this.localURI; - const fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - const callId = this.callId; - let cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - const ruri = this.remoteTarget; - const routeSet = this.routeSet; - const extraHeaders = options && options.extraHeaders; - const body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId, - cseq, - fromTag, - toTag, - routeSet - }, extraHeaders, body); - return message; - } - /** - * Increment the local sequence number by one. - * It feels like this should be protected, but the current authentication handling currently - * needs this to keep the dialog in sync when "auto re-sends" request messages. - * @internal - */ - incrementLocalSequenceNumber() { - if (!this.dialogState.localSequenceNumber) { - throw new Error("Local sequence number undefined."); - } - this.dialogState.localSequenceNumber += 1; - } - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - sequenceGuard(message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - } -} - - -/***/ }), -/* 8 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Parameters"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["URI"]; }); - -/* harmony import */ var _methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _methods__WEBPACK_IMPORTED_MODULE_1__) if(["Grammar","NameAddrHeader","Parameters","URI","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _methods__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _body__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["fromBodyLegacy"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["isBody"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["getBody"]; }); - -/* harmony import */ var _digest_authentication__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return _digest_authentication__WEBPACK_IMPORTED_MODULE_3__["DigestAuthentication"]; }); - -/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return _incoming_message__WEBPACK_IMPORTED_MODULE_4__["IncomingMessage"]; }); - -/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__["IncomingRequestMessage"]; }); - -/* harmony import */ var _incoming_request__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(37); -/* harmony import */ var _incoming_request__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_incoming_request__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _incoming_request__WEBPACK_IMPORTED_MODULE_6__) if(["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _incoming_request__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(33); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__["IncomingResponseMessage"]; }); - -/* harmony import */ var _incoming_response__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(38); -/* harmony import */ var _incoming_response__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_incoming_response__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _incoming_response__WEBPACK_IMPORTED_MODULE_8__) if(["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _incoming_response__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(34); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__["OutgoingRequestMessage"]; }); - -/* harmony import */ var _outgoing_request__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(39); -/* harmony import */ var _outgoing_request__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_outgoing_request__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _outgoing_request__WEBPACK_IMPORTED_MODULE_10__) if(["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","OutgoingRequestMessage","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _outgoing_request__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _outgoing_response__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(40); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return _outgoing_response__WEBPACK_IMPORTED_MODULE_11__["constructOutgoingResponse"]; }); - -/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(41); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _parser__WEBPACK_IMPORTED_MODULE_12__["Parser"]; }); - -// Grammar - -// Directories - -// Files - - - - - - - - - - - - - -/***/ }), -/* 9 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); - -/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _name_addr_header__WEBPACK_IMPORTED_MODULE_1__["NameAddrHeader"]; }); - -/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _parameters__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); - -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _uri__WEBPACK_IMPORTED_MODULE_3__["URI"]; }); - - - - - - - -/***/ }), -/* 10 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return Grammar; }); -/* harmony import */ var _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); -/* eslint-disable @typescript-eslint/no-namespace */ -/* eslint-disable no-inner-declarations */ - -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function parse(input, startRule) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const options = { startRule }; - try { - _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__["parse"](input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar || (Grammar = {})); - - -/***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyntaxError", function() { return SyntaxError; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); -/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs - - -class SyntaxError extends Error { - constructor(message, expected, found, location) { - super(); - this.message = message; - this.expected = expected; - this.found = found; - this.location = location; - this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(this, SyntaxError); - } - } - static buildMessage(expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) - .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) - .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - const escapedParts = expectation.parts.map((part) => { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - const descriptions = expected1.map(describeExpectation); - let i; - let j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - } -} -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - const peg$FAILED = {}; - const peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - let peg$startRuleIndex = 119; - const peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new _uri__WEBPACK_IMPORTED_MODULE_1__["URI"](options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new _uri__WEBPACK_IMPORTED_MODULE_1__["URI"](options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new _uri__WEBPACK_IMPORTED_MODULE_1__["URI"](options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - const peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map((ch) => ch.charCodeAt(0) - 32); - } - function peg$parseRule(index) { - const bc = peg$bytecode[index]; - let ip = 0; - const ips = []; - let end = bc.length; - const ends = []; - const stack = []; - let params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -const parse = peg$parse; - - -/***/ }), -/* 12 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return NameAddrHeader; }); -/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); - -/** - * Name Address SIP header. - * @public - */ -class NameAddrHeader extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - constructor(uri, displayName, parameters) { - super(parameters); - this.uri = uri; - this._displayName = displayName; - } - get friendlyName() { - return this.displayName || this.uri.aor; - } - get displayName() { return this._displayName; } - set displayName(value) { - this._displayName = value; - } - clone() { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - } - toString() { - let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (const parameter in this.parameters) { - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - } -} - - -/***/ }), -/* 13 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return Parameters; }); -/** - * @internal - */ -class Parameters { - constructor(parameters) { - this.parameters = {}; - for (const param in parameters) { - // eslint-disable-next-line no-prototype-builtins - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setParam(key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - } - getParam(key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - } - hasParam(key) { - if (key) { - // eslint-disable-next-line no-prototype-builtins - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - deleteParam(parameter) { - parameter = parameter.toLowerCase(); - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - const value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - } - clearParams() { - this.parameters = {}; - } -} - - -/***/ }), -/* 14 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; }); -/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** - * URI. - * @public - */ -class URI extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - constructor(scheme, user, host, port, parameters, headers) { - super(parameters); - this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (const header in headers) { - // eslint-disable-next-line no-prototype-builtins - if (headers.hasOwnProperty(header)) { - this.setHeader(header, headers[header]); - } - } - // Raw URI - this.raw = { - scheme, - user, - host, - port - }; - // Normalized URI - this.normal = { - scheme: scheme.toLowerCase(), - user, - host: host.toLowerCase(), - port - }; - } - get scheme() { return this.normal.scheme; } - set scheme(value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - } - get user() { return this.normal.user; } - set user(value) { - this.normal.user = this.raw.user = value; - } - get host() { return this.normal.host; } - set host(value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - } - get aor() { return this.normal.user + "@" + this.normal.host; } - get port() { return this.normal.port; } - set port(value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - } - setHeader(name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - } - getHeader(name) { - if (name) { - return this.headers[this.headerize(name)]; - } - } - hasHeader(name) { - // eslint-disable-next-line no-prototype-builtins - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - } - deleteHeader(header) { - header = this.headerize(header); - // eslint-disable-next-line no-prototype-builtins - if (this.headers.hasOwnProperty(header)) { - const value = this.headers[header]; - delete this.headers[header]; - return value; - } - } - clearHeaders() { - this.headers = {}; - } - clone() { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - } - toRaw() { - return this._toString(this._raw); - } - toString() { - return this._toString(this._normal); - } - get _normal() { return this.normal; } - get _raw() { return this.raw; } - _toString(uri) { - let uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (const parameter in this.parameters) { - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - const headers = []; - for (const header in this.headers) { - // eslint-disable-next-line no-prototype-builtins - if (this.headers.hasOwnProperty(header)) { - for (const idx in this.headers[header]) { - // eslint-disable-next-line no-prototype-builtins - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - } - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - escapeUser(user) { - let decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - // eslint-disable-next-line no-useless-catch - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - headerize(str) { - const exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - const name = str.toLowerCase().replace(/_/g, "-").split("-"); - const parts = name.length; - let hname = ""; - for (let part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } -} - - -/***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["C"]; }); - -/* harmony import */ var _ack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); -/* harmony import */ var _ack__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_ack__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _ack__WEBPACK_IMPORTED_MODULE_1__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _ack__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_bye__WEBPACK_IMPORTED_MODULE_2__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _bye__WEBPACK_IMPORTED_MODULE_2__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _bye__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _cancel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19); -/* harmony import */ var _cancel__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cancel__WEBPACK_IMPORTED_MODULE_3__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _cancel__WEBPACK_IMPORTED_MODULE_3__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _cancel__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_info__WEBPACK_IMPORTED_MODULE_4__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _info__WEBPACK_IMPORTED_MODULE_4__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _info__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invite__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(21); -/* harmony import */ var _invite__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_invite__WEBPACK_IMPORTED_MODULE_5__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invite__WEBPACK_IMPORTED_MODULE_5__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invite__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(22); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_message__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _message__WEBPACK_IMPORTED_MODULE_6__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _message__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _notify__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(23); -/* harmony import */ var _notify__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_notify__WEBPACK_IMPORTED_MODULE_7__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _notify__WEBPACK_IMPORTED_MODULE_7__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _notify__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _prack__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(24); -/* harmony import */ var _prack__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_prack__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _prack__WEBPACK_IMPORTED_MODULE_8__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _prack__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publish__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(25); -/* harmony import */ var _publish__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_publish__WEBPACK_IMPORTED_MODULE_9__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publish__WEBPACK_IMPORTED_MODULE_9__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publish__WEBPACK_IMPORTED_MODULE_9__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(26); -/* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_register__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _register__WEBPACK_IMPORTED_MODULE_10__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _register__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _refer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(27); -/* harmony import */ var _refer__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_refer__WEBPACK_IMPORTED_MODULE_11__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _refer__WEBPACK_IMPORTED_MODULE_11__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _refer__WEBPACK_IMPORTED_MODULE_11__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscribe__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(28); -/* harmony import */ var _subscribe__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_subscribe__WEBPACK_IMPORTED_MODULE_12__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscribe__WEBPACK_IMPORTED_MODULE_12__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscribe__WEBPACK_IMPORTED_MODULE_12__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - - - - - - - - - - - - -/***/ }), -/* 16 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return C; }); -/* eslint-disable @typescript-eslint/no-namespace */ -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C || (C = {})); - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 18 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 20 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 21 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 23 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 25 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 26 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 27 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 28 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 29 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return fromBodyLegacy; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return isBody; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return getBody; }); -/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30); -/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(33); -/* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34); - - - -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - const content = typeof bodyLegacy === "string" ? bodyLegacy : bodyLegacy.body; - const contentType = typeof bodyLegacy === "string" ? "application/sdp" : bodyLegacy.contentType; - const contentDisposition = contentTypeToContentDisposition(contentType); - const body = { contentDisposition, contentType, content }; - return body; -} -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined - ? true - : typeof body.contentDisposition === "string"; -} -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - let contentDisposition; - let contentType; - let content; - // We're in UAS role, receiving incoming request - if (message instanceof _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - if (message.body) { - // FIXME: Parsing needs typing - const parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof _incoming_response_message__WEBPACK_IMPORTED_MODULE_1__["IncomingResponseMessage"]) { - if (message.body) { - // FIXME: Parsing needs typing - const parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof _outgoing_request_message__WEBPACK_IMPORTED_MODULE_2__["OutgoingRequestMessage"]) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition, - contentType, - content - }; -} - - -/***/ }), -/* 30 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return IncomingRequestMessage; }); -/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); - -/** - * Incoming request message. - * @public - */ -class IncomingRequestMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { - constructor() { - super(); - } -} - - -/***/ }), -/* 31 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return IncomingMessage; }); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); - - -/** - * Incoming message. - * @public - */ -class IncomingMessage { - constructor() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - addHeader(name, value) { - const header = { raw: value }; - name = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - } - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name) { - const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - } - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - getHeaders(name) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - const result = []; - if (!header) { - return []; - } - for (const headerPart of header) { - result.push(headerPart.raw); - } - return result; - } - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name) { - return !!this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - } - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - parseHeader(name, idx = 0) { - name = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - const header = this.headers[name][idx]; - const value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - } - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - s(name, idx = 0) { - return this.parseHeader(name, idx); - } - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - setHeader(name, value) { - this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)] = [{ raw: value }]; - } - toString() { - return this.data; - } -} - - -/***/ }), -/* 32 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomToken", function() { return createRandomToken; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getReasonPhrase", function() { return getReasonPhrase; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newTag", function() { return newTag; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "headerize", function() { return headerize; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8Length", function() { return utf8Length; }); -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -const REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base = 32) { - let token = ""; - for (let i = 0; i < size; i++) { - const r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -/** - * @param str - - * @internal - */ -function headerize(str) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const exceptions = { - "Call-Id": "Call-ID", - Cseq: "CSeq", - "Min-Se": "Min-SE", - Rack: "RAck", - Rseq: "RSeq", - "Www-Authenticate": "WWW-Authenticate" - }; - const name = str.toLowerCase().replace(/_/g, "-").split("-"); - const parts = name.length; - let hname = ""; - for (let part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -/** - * @param str - - * @internal - */ -function utf8Length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} - - -/***/ }), -/* 33 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return IncomingResponseMessage; }); -/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); - -/** - * Incoming response message. - * @public - */ -class IncomingResponseMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { - constructor() { - super(); - } -} - - -/***/ }), -/* 34 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return OutgoingRequestMessage; }); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); - - -/** - * Outgoing SIP request message. - * @public - */ -class OutgoingRequestMessage { - constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - // Initialize default options - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = Object.assign(Object.assign({}, this.options), options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : Object(_utils__WEBPACK_IMPORTED_MODULE_1__["newTag"])(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - static getDefaultOptions() { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - } - static makeNameAddrHeader(uri, displayName, tag) { - const parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new _grammar__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](uri, displayName, parameters); - } - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name) { - const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const exHeader of this.extraHeaders) { - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - } - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - getHeaders(name) { - const result = []; - const headerArray = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - if (headerArray) { - for (const headerPart of headerArray) { - result.push(headerPart); - } - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const exHeader of this.extraHeaders) { - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - } - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name) { - if (this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]) { - return true; - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const extraHeader of this.extraHeaders) { - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - } - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - setHeader(name, value) { - this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)] = value instanceof Array ? value : [value]; - } - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param transport - The sent protocol transport. - */ - setViaHeader(branch, transport) { - // FIXME: Hack - if (this.options.hackViaTcp) { - transport = "TCP"; - } - let via = "SIP/2.0/" + transport; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - } - toString() { - let msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (const header in this.headers) { - if (this.headers[header]) { - for (const headerPart of this.headers[header]) { - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (const header of this.extraHeaders) { - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - } -} - - -/***/ }), -/* 35 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return DigestAuthentication; }); -/* harmony import */ var _md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); - - -function MD5(s) { - return _md5__WEBPACK_IMPORTED_MODULE_0__["Md5"].hashStr(s); -} -/** - * Digest Authentication. - * @internal - */ -class DigestAuthentication { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - constructor(loggerFactory, ha1, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.ha1 = ha1; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - authenticate(request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - } - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - toString() { - const authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - } - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - updateNcHex() { - const hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - } - /** - * Generate Digest 'response' value. - */ - calculateResponse(body) { - let ha1, ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - ha1 = this.ha1; - if (ha1 === "" || ha1 === undefined) { - ha1 = MD5(this.username + ":" + this.realm + ":" + this.password); - } - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = MD5(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)` - this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = MD5(this.method + ":" + this.uri + ":" + MD5(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = MD5(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = MD5(ha1 + ":" + this.nonce + ":" + ha2); - } - } -} - - -/***/ }), -/* 36 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Md5", function() { return Md5; }); -/* eslint-disable */ -// -// Scoped from: https://github.com/cotag/ts-md5 -// -/* - -TypeScript Md5 -============== - -Based on work by -* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html -* André Cruz: https://github.com/satazor/SparkMD5 -* Raymond Hill: https://github.com/gorhill/yamd5.js - -Effectively a TypeScrypt re-write of Raymond Hill JS Library - -The MIT License (MIT) - -Copyright (C) 2014 Raymond Hill - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2015 André Cruz - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - - -*/ -class Md5 { - constructor() { - this._dataLength = 0; - this._bufferLength = 0; - this._state = new Int32Array(4); - this._buffer = new ArrayBuffer(68); - this._buffer8 = new Uint8Array(this._buffer, 0, 68); - this._buffer32 = new Uint32Array(this._buffer, 0, 17); - this.start(); - } - static hashStr(str, raw = false) { - return this.onePassHasher - .start() - .appendStr(str) - .end(raw); - } - static hashAsciiStr(str, raw = false) { - return this.onePassHasher - .start() - .appendAsciiStr(str) - .end(raw); - } - static _hex(x) { - const hc = Md5.hexChars; - const ho = Md5.hexOut; - let n; - let offset; - let j; - let i; - for (i = 0; i < 4; i += 1) { - offset = i * 8; - n = x[i]; - for (j = 0; j < 8; j += 2) { - ho[offset + 1 + j] = hc.charAt(n & 0x0F); - n >>>= 4; - ho[offset + 0 + j] = hc.charAt(n & 0x0F); - n >>>= 4; - } - } - return ho.join(''); - } - static _md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - // ff() - a += (b & c | ~b & d) + k[0] - 680876936 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[1] - 389564586 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[2] + 606105819 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[3] - 1044525330 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[4] - 176418897 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[5] + 1200080426 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[6] - 1473231341 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[7] - 45705983 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[8] + 1770035416 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[9] - 1958414417 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[10] - 42063 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[11] - 1990404162 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[12] + 1804603682 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[13] - 40341101 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[14] - 1502002290 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[15] + 1236535329 | 0; - b = (b << 22 | b >>> 10) + c | 0; - // gg() - a += (b & d | c & ~d) + k[1] - 165796510 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[6] - 1069501632 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[11] + 643717713 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[0] - 373897302 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[5] - 701558691 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[10] + 38016083 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[15] - 660478335 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[4] - 405537848 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[9] + 568446438 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[14] - 1019803690 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[3] - 187363961 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[8] + 1163531501 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[13] - 1444681467 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[2] - 51403784 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[7] + 1735328473 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[12] - 1926607734 | 0; - b = (b << 20 | b >>> 12) + c | 0; - // hh() - a += (b ^ c ^ d) + k[5] - 378558 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[8] - 2022574463 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[11] + 1839030562 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[14] - 35309556 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[1] - 1530992060 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[4] + 1272893353 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[7] - 155497632 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[10] - 1094730640 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[13] + 681279174 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[0] - 358537222 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[3] - 722521979 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[6] + 76029189 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[9] - 640364487 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[12] - 421815835 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[15] + 530742520 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[2] - 995338651 | 0; - b = (b << 23 | b >>> 9) + c | 0; - // ii() - a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; - b = (b << 21 | b >>> 11) + c | 0; - x[0] = a + x[0] | 0; - x[1] = b + x[1] | 0; - x[2] = c + x[2] | 0; - x[3] = d + x[3] | 0; - } - start() { - this._dataLength = 0; - this._bufferLength = 0; - this._state.set(Md5.stateIdentity); - return this; - } - // Char to code point to to array conversion: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt - // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown - appendStr(str) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let code; - let i; - for (i = 0; i < str.length; i += 1) { - code = str.charCodeAt(i); - if (code < 128) { - buf8[bufLen++] = code; - } - else if (code < 0x800) { - buf8[bufLen++] = (code >>> 6) + 0xC0; - buf8[bufLen++] = code & 0x3F | 0x80; - } - else if (code < 0xD800 || code > 0xDBFF) { - buf8[bufLen++] = (code >>> 12) + 0xE0; - buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; - buf8[bufLen++] = (code & 0x3F) | 0x80; - } - else { - code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; - if (code > 0x10FFFF) { - throw new Error('Unicode standard supports code points up to U+10FFFF'); - } - buf8[bufLen++] = (code >>> 18) + 0xF0; - buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; - buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; - buf8[bufLen++] = (code & 0x3F) | 0x80; - } - if (bufLen >= 64) { - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen -= 64; - buf32[0] = buf32[16]; - } - } - this._bufferLength = bufLen; - return this; - } - appendAsciiStr(str) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let i; - let j = 0; - for (;;) { - i = Math.min(str.length - j, 64 - bufLen); - while (i--) { - buf8[bufLen++] = str.charCodeAt(j++); - } - if (bufLen < 64) { - break; - } - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen = 0; - } - this._bufferLength = bufLen; - return this; - } - appendByteArray(input) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let i; - let j = 0; - for (;;) { - i = Math.min(input.length - j, 64 - bufLen); - while (i--) { - buf8[bufLen++] = input[j++]; - } - if (bufLen < 64) { - break; - } - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen = 0; - } - this._bufferLength = bufLen; - return this; - } - getState() { - const self = this; - const s = self._state; - return { - buffer: String.fromCharCode.apply(null, self._buffer8), - buflen: self._bufferLength, - length: self._dataLength, - state: [s[0], s[1], s[2], s[3]] - }; - } - setState(state) { - const buf = state.buffer; - const x = state.state; - const s = this._state; - let i; - this._dataLength = state.length; - this._bufferLength = state.buflen; - s[0] = x[0]; - s[1] = x[1]; - s[2] = x[2]; - s[3] = x[3]; - for (i = 0; i < buf.length; i += 1) { - this._buffer8[i] = buf.charCodeAt(i); - } - } - end(raw = false) { - const bufLen = this._bufferLength; - const buf8 = this._buffer8; - const buf32 = this._buffer32; - const i = (bufLen >> 2) + 1; - let dataBitsLen; - this._dataLength += bufLen; - buf8[bufLen] = 0x80; - buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; - buf32.set(Md5.buffer32Identity.subarray(i), i); - if (bufLen > 55) { - Md5._md5cycle(this._state, buf32); - buf32.set(Md5.buffer32Identity); - } - // Do the final computation based on the tail and length - // Beware that the final length may not fit in 32 bits so we take care of that - dataBitsLen = this._dataLength * 8; - if (dataBitsLen <= 0xFFFFFFFF) { - buf32[14] = dataBitsLen; - } - else { - const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); - if (matches === null) { - return; - } - const lo = parseInt(matches[2], 16); - const hi = parseInt(matches[1], 16) || 0; - buf32[14] = lo; - buf32[15] = hi; - } - Md5._md5cycle(this._state, buf32); - return raw ? this._state : Md5._hex(this._state); - } -} -// Private Static Variables -Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); -Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); -Md5.hexChars = '0123456789abcdef'; -Md5.hexOut = []; -// Permanent instance is to use for one-call hashing -Md5.onePassHasher = new Md5(); -if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { - console.error('Md5 self test failed.'); -} - - -/***/ }), -/* 37 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 39 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 40 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return constructOutgoingResponse; }); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(32); - -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - const CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_utils__WEBPACK_IMPORTED_MODULE_0__["getReasonPhrase"])(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - let response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - const fromHeader = "From: " + message.getHeader("From") + CRLF; - const callIdHeader = "Call-ID: " + message.callId + CRLF; - const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - const viaHeaders = message.getHeaders("via").reduce((previous, current) => { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - let toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - let toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = Object(_utils__WEBPACK_IMPORTED_MODULE_0__["newTag"])(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - let supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - let userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - let extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce((previous, current) => { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + Object(_utils__WEBPACK_IMPORTED_MODULE_0__["utf8Length"])(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} - - -/***/ }), -/* 41 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return Parser; }); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30); -/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); -/* eslint-disable no-inner-declarations */ -/* eslint-disable @typescript-eslint/no-namespace */ - - - -/** - * Extract and parse every header of a SIP message. - * @internal - */ -var Parser; -(function (Parser) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function getHeader(data, headerStart) { - // 'start' position of the header. - let start = headerStart; - // 'end' position of the header. - let end = 0; - // 'partial end' position of the header. - let partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, headerStart, headerEnd) { - const hcolonIndex = data.indexOf(":", headerStart); - const headerName = data.substring(headerStart, hcolonIndex).trim(); - const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach((header) => { - message.addHeader("record-route", headerValue.substring(header.position, header.offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = header.parsed; - }); - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach((header) => { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["IncomingResponseMessage"]) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - function parseMessage(data, logger) { - let headerStart = 0; - let headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - const firstLine = data.substring(0, headerEnd); - const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(firstLine, "Request_Response"); - let message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__["IncomingRequestMessage"](); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["IncomingResponseMessage"](); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - // Loop over every line in data. Detect the end of each header and parse - // it or simply add to the headers collection. - let bodyStart; - // eslint-disable-next-line no-constant-condition - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - const parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - // RFC3261 18.3. - // If there are additional bytes in the transport packet - // beyond the end of the body, they MUST be discarded. - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser || (Parser = {})); - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 43 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return SessionDialog; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); -/* harmony import */ var _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62); -/* harmony import */ var _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(64); -/* harmony import */ var _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(66); -/* harmony import */ var _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(67); -/* harmony import */ var _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(68); -/* harmony import */ var _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(69); -/* harmony import */ var _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(70); -/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(71); -/* harmony import */ var _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); -/* harmony import */ var _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); -/* harmony import */ var _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); -/* harmony import */ var _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); -/* harmony import */ var _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(76); -/* harmony import */ var _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(77); -/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(7); - - - - - - - - - - - - - - - - - - - -/** - * Session Dialog. - * @public - */ -class SessionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_18__["Dialog"] { - constructor(initialTransaction, core, state, delegate) { - super(core, state); - this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - this.ackWait = false; - /** True if processing an ACK to the initial transaction 2xx (UAS only). */ - this.ackProcessing = false; - this.delegate = delegate; - if (initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!this.early) { - this.start2xxRetransmissionTimer(); - } - this.signalingStateTransition(initialTransaction.request); - this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - this.logger.log(`INVITE dialog ${this.id} constructed`); - } - dispose() { - super.dispose(); - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log(`INVITE dialog ${this.id} destroyed`); - } - // FIXME: Need real state machine - get sessionState() { - if (this.early) { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Early; - } - else if (this.ackWait) { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].AckWait; - } - else if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed) { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Terminated; - } - else { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Confirmed; - } - } - /** The state of the offer/answer exchange. */ - get signalingState() { - return this._signalingState; - } - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get offer() { - return this._offer; - } - /** The current answer. Undefined unless signaling state Stable. */ - get answer() { - return this._answer; - } - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm() { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - super.confirm(); - } - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - reConfirm() { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - } - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - ack(options = {}) { - this.logger.log(`INVITE dialog ${this.id} sending ACK request`); - let transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"])) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, { - cseq: transaction.request.cseq, - extraHeaders: options.extraHeaders, - body: options.body - }); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message }; - } - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - bye(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending BYE request`); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__["ByeUserAgentClient"](this, delegate, options); - } - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - info(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending INFO request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__["InfoUserAgentClient"](this, delegate, options); - } - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - invite(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending INVITE request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"](this, delegate, options); - } - /** - * A UAC MAY associate a MESSAGE request with an existing dialog. If a - * MESSAGE request is sent within a dialog, it is "associated" with any - * media session or sessions associated with that dialog. - * https://tools.ietf.org/html/rfc3428#section-4 - * @param options - Options bucket. - */ - message(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, options); - return new _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"](this.core, message, delegate); - } - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - notify(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__["NotifyUserAgentClient"](this, delegate, options); - } - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - prack(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); - return new _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["PrackUserAgentClient"](this, delegate, options); - } - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - refer(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending REFER request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["ReferUserAgentClient"](this, delegate, options); - } - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message) { - this.logger.log(`INVITE dialog ${this.id} received ${message.method} request`); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"]) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - const promiseOrVoid = this.delegate.onAck({ message }); - if (promiseOrVoid instanceof Promise) { - this.ackProcessing = true; // make sure this is always reset to false - promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false)); - } - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log(`INVITE dialog ${this.id} rejected out of order ${message.method} request.`); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - super.receiveRequest(message); - // Handle various INVITE related cross-over, glare and race conditions - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - // Hopefully this message is helpful... - const warning = () => { - const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK"; - this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`); - let msg = "RFC 5407 suggests the following to avoid this race condition... "; - msg += " Note: Implementation issues are outside the scope of this document,"; - msg += " but the following tip is provided for avoiding race conditions of"; - msg += " this type. The caller can delay sending re-INVITE F6 for some period"; - msg += " of time (2 seconds, perhaps), after which the caller can reasonably"; - msg += " assume that its ACK has been received. Implementors can decouple the"; - msg += " actions of the user (e.g., pressing the hold button) from the actions"; - msg += " of the protocol (the sending of re-INVITE F6), so that the UA can"; - msg += " behave like this. In this case, it is the implementor's choice as to"; - msg += " how long to wait. In most cases, such an implementation may be"; - msg += " useful to prevent the type of race condition shown in this section."; - msg += " This document expresses no preference about whether or not they"; - msg += " should wait for an ACK to be delivered. After considering the impact"; - msg += " on user experience, implementors should decide whether or not to wait"; - msg += " for a while, because the user experience depends on the"; - msg += " implementation and has no direct bearing on protocol behavior."; - this.logger.warn(msg); - return; // drop re-INVITE request message - }; - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - const retryAfter = Math.floor(Math.random() * 10) + 1; - const extraHeaders = [`Retry-After: ${retryAfter}`]; - // There may be ONLY ONE offer/answer negotiation in progress for a - // single dialog at any point in time. Section 4 explains how to ensure - // this. - // https://tools.ietf.org/html/rfc6337#section-2.2 - if (this.ackProcessing) { - // UAS-IsI: While an INVITE server transaction is incomplete or ACK - // transaction associated with an offer/answer is incomplete, - // a UA must reject another INVITE request with a 500 - // response. - // https://tools.ietf.org/html/rfc6337#section-4.3 - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - warning(); - return; - } - // 3.1.4. Callee Receives re-INVITE (Established State) While in the - // Moratorium State (Case 1) - // https://tools.ietf.org/html/rfc5407#section-3.1.4 - // 3.1.5. Callee Receives re-INVITE (Established State) While in the - // Moratorium State (Case 2) - // https://tools.ietf.org/html/rfc5407#section-3.1.5 - if (this.ackWait && this.signalingState !== _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable) { - // This scenario is basically the same as that of Section 3.1.4, but - // differs in sending an offer in the 200 and an answer in the ACK. In - // contrast to the previous case, the offer in the 200 (F3) and the - // offer in the re-INVITE (F6) collide with each other. - // - // Bob sends a 491 to the re-INVITE (F6) since he is not able to - // properly handle a new request until he receives an answer. (Note: - // 500 with a Retry-After header may be returned if the 491 response is - // understood to indicate request collision. However, 491 is - // recommended here because 500 applies to so many cases that it is - // difficult to determine what the real problem was.) - // https://tools.ietf.org/html/rfc5407#section-3.1.5 - // UAS-IsI: While an INVITE server transaction is incomplete or ACK - // transaction associated with an offer/answer is incomplete, - // a UA must reject another INVITE request with a 500 - // response. - // https://tools.ietf.org/html/rfc6337#section-4.3 - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - warning(); - return; - } - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - // FIXME: parser needs to be typed... - const contact = message.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - const uas = new _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__["ByeUserAgentServer"](this, message); - this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); - this.dispose(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - const uas = new _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__["InfoUserAgentServer"](this, message); - this.delegate && this.delegate.onInfo - ? this.delegate.onInfo(uas) - : uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - const uas = new _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["ReInviteUserAgentServer"](this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE: - { - const uas = new _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__["MessageUserAgentServer"](this.core, message); - this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__["NotifyUserAgentServer"](this, message); - this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - const uas = new _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"](this, message); - this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - const uas = new _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["ReferUserAgentServer"](this, message); - this.delegate && this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject(); - } - break; - default: - { - this.logger.log(`INVITE dialog ${this.id} received unimplemented ${message.method} request`); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - } - /** - * Guard against out of order reliable provisional responses and retransmissions. - * Returns false if the response should be discarded, otherwise true. - * @param message - Incoming response message within this dialog. - */ - reliableSequenceGuard(message) { - const statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - const requireHeader = message.getHeader("require"); - const rseqHeader = message.getHeader("rseq"); - const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - this.rseq = this.rseq ? this.rseq + 1 : rseq; - } - } - return true; - } - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - signalingStateRollback() { - if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer || - this.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - } - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - signalingStateTransition(message) { - const body = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["getBody"])(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"]) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (Object(_messages__WEBPACK_IMPORTED_MODULE_0__["isBody"])(message)) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - } - start2xxRetransmissionTimer() { - if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - const transaction = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; - const retransmission = () => { - if (!this.ackWait) { - this.invite2xxTimer = undefined; - return; - } - this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction.retransmitAcceptedResponse(); - timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); - this.invite2xxTimer = setTimeout(retransmission, timeout); - }; - this.invite2xxTimer = setTimeout(retransmission, timeout); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - const stateChanged = () => { - if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - transaction.removeStateChangeListener(stateChanged); - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - if (this.ackWait) { - if (this.delegate && this.delegate.onAckTimeout) { - this.delegate.onAckTimeout(); - } - else { - this.bye(); - } - } - } - }; - transaction.addStateChangeListener(stateChanged); - } - } - // FIXME: Refactor - startReInvite2xxRetransmissionTimer() { - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - const transaction = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; - const retransmission = () => { - if (!this.reinviteUserAgentServer) { - this.invite2xxTimer = undefined; - return; - } - this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction.retransmitAcceptedResponse(); - timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); - this.invite2xxTimer = setTimeout(retransmission, timeout); - }; - this.invite2xxTimer = setTimeout(retransmission, timeout); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - const stateChanged = () => { - if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - transaction.removeStateChangeListener(stateChanged); - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction.addStateChangeListener(stateChanged); - } - } -} - - -/***/ }), -/* 44 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SessionState"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SignalingState"]; }); - -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46); -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_session_delegate__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_delegate__WEBPACK_IMPORTED_MODULE_1__) if(["SessionState","SignalingState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_delegate__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - -/***/ }), -/* 45 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return SignalingState; }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState || (SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState || (SignalingState = {})); - - -/***/ }), -/* 46 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 47 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return Timers; }); -const T1 = 500; -const T2 = 4000; -const T4 = 5000; -/** - * Timers. - * @public - */ -const Timers = { - T1, - T2, - T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -/***/ }), -/* 48 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(49); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return _client_transaction__WEBPACK_IMPORTED_MODULE_0__["ClientTransaction"]; }); - -/* harmony import */ var _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"]; }); - -/* harmony import */ var _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(57); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__["InviteServerTransaction"]; }); - -/* harmony import */ var _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(59); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"]; }); - -/* harmony import */ var _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__["NonInviteServerTransaction"]; }); - -/* empty/unused harmony star reexport *//* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return _server_transaction__WEBPACK_IMPORTED_MODULE_5__["ServerTransaction"]; }); - -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(56); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return _transaction_state__WEBPACK_IMPORTED_MODULE_6__["TransactionState"]; }); - -/* harmony import */ var _transaction_user__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(61); -/* harmony import */ var _transaction_user__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_transaction_user__WEBPACK_IMPORTED_MODULE_7__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transaction_user__WEBPACK_IMPORTED_MODULE_7__) if(["ClientTransaction","InviteClientTransaction","InviteServerTransaction","NonInviteClientTransaction","NonInviteServerTransaction","ServerTransaction","TransactionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transaction_user__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(50); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return _transaction__WEBPACK_IMPORTED_MODULE_8__["Transaction"]; }); - - - - - - - - - - - - - -/***/ }), -/* 49 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return ClientTransaction; }); -/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); - -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -class ClientTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { - constructor(_request, transport, user, state, loggerCategory) { - super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); - this._request = _request; - this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - _request.setViaHeader(this.id, transport.protocol); - } - static makeId(request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - } - /** The outgoing request the transaction handling. */ - get request() { - return this._request; - } - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - onRequestTimeout() { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - } -} - - -/***/ }), -/* 50 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return Transaction; }); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); - -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -class Transaction { - constructor(_transport, _user, _id, _state, loggerCategory) { - this._transport = _transport; - this._user = _user; - this._id = _id; - this._state = _state; - this.listeners = new Array(); - this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - dispose() { - this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); - } - /** Transaction id. */ - get id() { - return this._id; - } - /** Transaction kind. Deprecated. */ - get kind() { - throw new Error("Invalid kind."); - } - /** Transaction state. */ - get state() { - return this._state; - } - /** Transaction transport. */ - get transport() { - return this._transport; - } - /** - * Sets up a function that will be called whenever the transaction state changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addStateChangeListener(listener, options) { - const onceWrapper = () => { - this.removeStateChangeListener(onceWrapper); - listener(); - }; - (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); - } - /** - * This is currently public so tests may spy on it. - * @internal - */ - notifyStateChangeListeners() { - this.listeners.slice().forEach((listener) => listener()); - } - /** - * Removes a listener previously registered with addStateListener. - * @param listener - Callback function. - */ - removeStateChangeListener(listener) { - this.listeners = this.listeners.filter((l) => l !== listener); - } - logTransportError(error, message) { - this.logger.error(error.message); - this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`); - this.logger.error(message); - } - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - send(message) { - return this.transport.send(message).catch((error) => { - // If the transport rejects, it SHOULD reject with a TransportError. - // But the transport may be external code, so we are careful - // make sure we convert it to a TransportError if need be. - if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"]) { - this.onTransportError(error); - throw error; - } - let transportError; - if (error && typeof error.message === "string") { - transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](error.message); - } - else { - transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](); - } - this.onTransportError(transportError); - throw transportError; - }); - } - setState(state) { - this.logger.debug(`State change to "${state}" on ${this.typeToString()} with id ${this.id}.`); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.notifyStateChangeListeners(); - } - typeToString() { - return "UnknownType"; - } -} - - -/***/ }), -/* 51 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"]; }); - -/* harmony import */ var _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(53); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); - -/* harmony import */ var _transport_error__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _transport_error__WEBPACK_IMPORTED_MODULE_2__["TransportError"]; }); - - - - - - -/***/ }), -/* 52 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return Exception; }); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -class Exception extends Error { - constructor(message) { - super(message); // 'Error' breaks prototype chain here - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain - } -} - - -/***/ }), -/* 53 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return TransactionStateError; }); -/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); - -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -class TransactionStateError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Transaction state error."); - } -} - - -/***/ }), -/* 54 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return TransportError; }); -/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); - -/** - * Transport error. - * @public - */ -class TransportError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Unspecified transport error."); - } -} - - -/***/ }), -/* 55 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return InviteClientTransaction; }); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); -/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); - - - -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -class InviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling, "sip.transaction.ict"); - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - this.B = setTimeout(() => this.timerB(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_B); - this.send(request.toString()).catch((error) => { - this.logTransportError(error, "Failed to send initial outgoing request."); - }); - } - /** - * Destructor. - */ - dispose() { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "ict"; - } - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - ackResponse(ack) { - const toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - ack.setViaHeader(id, this.transport.protocol); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch((error) => { - this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - } - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response) { - const statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - const ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - const message = `Received unexpected ${statusCode} response while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); - } - /** For logging. */ - typeToString() { - return "INVITE client transaction"; - } - ack(response) { - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - const ruri = this.request.ruri; - const callId = this.request.callId; - const cseq = this.request.cseq; - const from = this.request.getHeader("from"); - const to = response.getHeader("to"); - const via = this.request.getHeader("via"); - const route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - let ack = `ACK ${ruri} SIP/2.0\r\n`; - if (route) { - ack += `Route: ${route}\r\n`; - } - ack += `Via: ${via}\r\n`; - ack += `To: ${to}\r\n`; - ack += `From: ${from}\r\n`; - ack += `Call-ID: ${callId}\r\n`; - ack += `CSeq: ${cseq} ACK\r\n`; - ack += `Max-Forwards: 70\r\n`; - ack += `Content-Length: 0\r\n\r\n`; - // TOOO: "User-Agent" header - this.send(ack).catch((error) => { - this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted: - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.D = setTimeout(() => this.timerD(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { - this.M = setTimeout(() => this.timerM(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - timerA() { - // TODO - } - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - timerB() { - this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { - this.onRequestTimeout(); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - timerD() { - this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - timerM() { - this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 56 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return TransactionState; }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState || (TransactionState = {})); - - -/***/ }), -/* 57 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return InviteServerTransaction; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47); -/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(58); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(56); - - - - -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -class InviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_2__["ServerTransaction"] { - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding, "sip.transaction.ist"); - } - /** - * Destructor. - */ - dispose() { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "ist"; - } - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request) { - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return; - } - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `INVITE server transaction received unexpected ${request.method} request while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - receiveResponse(statusCode, response) { - if (statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; - this.logger.error(message); - throw new Error(message); - } - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - retransmitAcceptedResponse() { - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - } - } - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - } - /** For logging. */ - typeToString() { - return "INVITE server transaction"; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisional responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { - this.L = setTimeout(() => this.timerL(), _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(() => this.timerH(), _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(() => this.timerI(), _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - startProgressExtensionTimer() { - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(() => { - this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`); - if (!this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - this.send(this.lastProvisionalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].PROVISIONAL_RESPONSE_INTERVAL); - } - } - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - stopProgressExtensionTimer() { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - } - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerG() { - // TODO - } - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerH() { - this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); - } - } - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerI() { - this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); - } - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - timerL() { - this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 58 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return ServerTransaction; }); -/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); - -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -class ServerTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { - constructor(_request, transport, user, state, loggerCategory) { - super(transport, user, _request.viaBranch, state, loggerCategory); - this._request = _request; - this.user = user; - } - /** The incoming request the transaction handling. */ - get request() { - return this._request; - } -} - - -/***/ }), -/* 59 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return NonInviteClientTransaction; }); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); -/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); - - - -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -class NonInviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nict"); - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - this.F = setTimeout(() => this.timerF(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_F); - this.send(request.toString()).catch((error) => { - this.logTransportError(error, "Failed to send initial outgoing request."); - }); - } - /** - * Destructor. - */ - dispose() { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "nict"; - } - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response) { - const statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `Non-INVITE client transaction received unexpected ${statusCode} response while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the fail over mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Transport error - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); - } - /** For logging. */ - typeToString() { - return "non-INVITE client transaction"; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(() => this.timerK(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - timerF() { - this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying || this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - this.onRequestTimeout(); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - timerK() { - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 60 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return NonInviteServerTransaction; }); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); -/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); - - - -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -class NonInviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_1__["ServerTransaction"] { - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nist"); - } - /** - * Destructor. - */ - dispose() { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "nist"; - } - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - receiveRequest(request) { - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - } - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - receiveResponse(statusCode, response) { - if (statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `Non-INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; - this.logger.error(message); - throw new Error(message); - } - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); - } - /** For logging. */ - typeToString() { - return "non-INVITE server transaction"; - } - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.J = setTimeout(() => this.timerJ(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated) { - this.dispose(); - } - this.setState(newState); - } - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - timerJ() { - this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 61 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 62 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return ByeUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * BYE UAC. - * @public - */ -class ByeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - dialog.dispose(); - } -} - - -/***/ }), -/* 63 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return UserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); - - -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -class UserAgentClient { - constructor(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - dispose() { - this.transaction.dispose(); - } - get loggerFactory() { - return this.core.loggerFactory; - } - /** The transaction associated with this request. */ - get transaction() { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - } - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - cancel(reason, options = {}) { - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - const message = this.core.makeOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { - new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); - } - else { - this.transaction.addStateChangeListener(() => { - if (this.transaction && this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { - new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); - } - }, { once: true }); - } - return message; - } - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @param dialog - If defined, the dialog within which the response was received. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - authenticationGuard(message, dialog) { - const statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let challenge; - let authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - // If response to out of dialog request, assume incrementing the CSeq will suffice. - let cseq = (this.message.cseq += 1); - // If response to in dialog request, get a valid next CSeq number. - if (dialog && dialog.localSequenceNumber) { - dialog.incrementLocalSequenceNumber(); - cseq = this.message.cseq = dialog.localSequenceNumber; - } - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - } - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - onRequestTimeout() { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"](); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - } - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * @param error - Transport error - */ - onTransportError(error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"](); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - break; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - } - init() { - // We are the transaction user. - const user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: () => this.onRequestTimeout(), - onStateChange: (newState) => { - if (newState === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Terminated) { - // Remove the terminated transaction from the core. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - if (transaction === this._transaction) { - this.dispose(); - } - } - }, - onTransportError: (error) => this.onTransportError(error), - receiveResponse: (message) => this.receiveResponse(message) - }; - // Create a new transaction with us as the user. - const transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - const userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - } -} - - -/***/ }), -/* 64 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return ByeUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * BYE UAS. - * @public - */ -class ByeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 65 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return UserAgentServer; }); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _messages_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); - - - - -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -class UserAgentServer { - constructor(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : Object(_messages_utils__WEBPACK_IMPORTED_MODULE_2__["newTag"])(); - this.init(); - } - dispose() { - this.transaction.dispose(); - } - get loggerFactory() { - return this.core.loggerFactory; - } - /** The transaction associated with this request. */ - get transaction() { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - } - accept(options = { statusCode: 200 }) { - if (!this.acceptable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not acceptable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - progress(options = { statusCode: 180 }) { - if (!this.progressable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not progressable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - redirect(contacts, options = { statusCode: 302 }) { - if (!this.redirectable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not redirectable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const contactHeaders = new Array(); - contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - const response = this.reply(options); - return response; - } - reject(options = { statusCode: 480 }) { - if (!this.rejectable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not rejectable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - trying(options) { - if (!this.tryingable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not tryingable in state ${this.transaction.state}.`); - } - const response = this.reply({ statusCode: 100 }); - return response; - } - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - receiveCancel(message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - } - get acceptable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); - } - throw new Error("Unknown transaction type."); - } - get progressable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - } - get redirectable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); - } - throw new Error("Unknown transaction type."); - } - get rejectable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); - } - throw new Error("Unknown transaction type."); - } - get tryingable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying; - } - throw new Error("Unknown transaction type."); - } - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - reply(options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - const response = Object(_messages__WEBPACK_IMPORTED_MODULE_1__["constructOutgoingResponse"])(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - } - init() { - // We are the transaction user. - const user = { - loggerFactory: this.loggerFactory, - onStateChange: (newState) => { - if (newState === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - // Remove the terminated transaction from the core. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.core.userAgentServers.delete(userAgentServerId); - this.dispose(); - } - }, - onTransportError: (error) => { - this.logger.error(error.message); - if (this.delegate && this.delegate.onTransportError) { - this.delegate.onTransportError(error); - } - else { - this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - const transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - const userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - } -} - - -/***/ }), -/* 66 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return InfoUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * INFO UAC. - * @public - */ -class InfoUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 67 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return InfoUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * INFO UAS. - * @public - */ -class InfoUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 68 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return MessageUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * MESSAGE UAC. - * @public - */ -class MessageUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 69 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return MessageUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * MESSAGE UAS. - * @public - */ -class MessageUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 70 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return NotifyUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * NOTIFY UAS. - * @public - */ -class NotifyUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 71 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return NotifyUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} -/** - * NOTIFY UAS. - * @public - */ -class NotifyUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - constructor(dialogOrCore, message, delegate) { - const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 72 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return PrackUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * PRACK UAC. - * @public - */ -class PrackUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - dialog.signalingStateTransition(message); - } -} - - -/***/ }), -/* 73 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return PrackUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * PRACK UAS. - * @public - */ -class PrackUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - this.dialog = dialog; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options = { statusCode: 200 }) { - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return super.accept(options); - } -} - - -/***/ }), -/* 74 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return ReInviteUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -class ReInviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"], dialog.userAgentCore, message, delegate); - this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = this; // let the dialog know re-invite request sent - this.dialog = dialog; - } - receiveResponse(message) { - if (!this.authenticationGuard(message, this.dialog)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message, - session: this.dialog, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - prack: (options) => { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message, - session: this.dialog, - ack: (options) => { - const outgoingAckRequest = this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - } -} - - -/***/ }), -/* 75 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return ReInviteUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -class ReInviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["InviteServerTransaction"], dialog.userAgentCore, message, delegate); - dialog.reinviteUserAgentServer = this; - this.dialog = dialog; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options = { statusCode: 200 }) { - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map((route) => `Record-Route: ${route}`)); - // Send and return the response - const response = super.accept(options); - const session = this.dialog; - const result = Object.assign(Object.assign({}, response), { session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - } - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - progress(options = { statusCode: 180 }) { - // Send and return the response - const response = super.progress(options); - const session = this.dialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - } - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - redirect(contacts, options = { statusCode: 302 }) { - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - } - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - reject(options = { statusCode: 488 }) { - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return super.reject(options); - } -} - - -/***/ }), -/* 76 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return ReferUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * REFER UAC. - * @public - */ -class ReferUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 77 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return ReferUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} -/** - * REFER UAS. - * @public - */ -class ReferUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - constructor(dialogOrCore, message, delegate) { - const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 78 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return SubscriptionDialog; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); -/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); -/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(71); -/* harmony import */ var _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(83); -/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7); - - - - - - - -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -class SubscriptionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_6__["Dialog"] { - constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - super(core, state); - this.delegate = delegate; - this._autoRefresh = false; - this._subscriptionEvent = subscriptionEvent; - this._subscriptionExpires = subscriptionExpires; - this._subscriptionExpiresInitial = subscriptionExpires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - this._subscriptionRefresh = undefined; - this._subscriptionRefreshLastSet = undefined; - this._subscriptionState = subscriptionState; - this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForSubscription(outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - const contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - const remoteSequenceNumber = undefined; - const callId = outgoingSubscribeRequestMessage.callId; - const localTag = outgoingSubscribeRequestMessage.fromTag; - const remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { - // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { - // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { - // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { - // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { - // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - const localURI = outgoingSubscribeRequestMessage.from.uri; - const remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - const early = false; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - dispose() { - super.dispose(); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); - } - get autoRefresh() { - return this._autoRefresh; - } - set autoRefresh(autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - } - get subscriptionEvent() { - return this._subscriptionEvent; - } - /** Number of seconds until subscription expires. */ - get subscriptionExpires() { - const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - } - set subscriptionExpires(expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - const refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - } - get subscriptionExpiresInitial() { - return this._subscriptionExpiresInitial; - } - /** Number of seconds until subscription auto refresh. */ - get subscriptionRefresh() { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - } - get subscriptionState() { - return this._subscriptionState; - } - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - receiveRequest(message) { - this.logger.log(`SUBSCRIBE dialog ${this.id} received ${message.method} request`); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${message.method} request.`); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - super.receiveRequest(message); - // Switch on method and then delegate. - switch (message.method) { - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${message.method} request`); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - } - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh() { - const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - } - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - subscribe(delegate, options = {}) { - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - // FIXME: This needs to be a proper exception - throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`); - } - this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`); - const uac = new _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["ReSubscribeUserAgentClient"](this, delegate, options); - // Abort any outstanding timer (as it would otherwise become guaranteed to terminate us). - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].TIMER_N); - return uac; - } - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - terminate() { - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); - this.onTerminated(); - } - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe() { - const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - } - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - onNotify(message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - const state = subscriptionState.state; - const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending, expires); - break; - case "active": - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active, expires); - break; - case "terminated": - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["NotifyUserAgentServer"](this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - } - onRefresh(request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - } - onTerminated() { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - } - refreshTimerClear() { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - } - refreshTimerSet() { - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - const refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(() => { - this.refreshTimer = undefined; - this._subscriptionRefresh = undefined; - this._subscriptionRefreshLastSet = undefined; - this.onRefresh(this.refresh()); - }, refresh); - } - } - stateTransition(newState, newExpires) { - // Assert valid state transitions. - const invalidStateTransition = () => { - this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); - }; - switch (newState) { - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: - invalidStateTransition(); - return; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: - invalidStateTransition(); - return; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending: - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending) { - invalidStateTransition(); - return; - } - break; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active: - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - invalidStateTransition(); - return; - } - break; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated: - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - } - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - timerN() { - this.logger.warn(`Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY.`); - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); - this.onTerminated(); - } - } -} - - -/***/ }), -/* 79 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"]; }); - -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_subscription_delegate__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__) if(["SubscriptionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - -/***/ }), -/* 80 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState || (SubscriptionState = {})); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 82 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllowedMethods", function() { return AllowedMethods; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); - -/** - * FIXME: TODO: Should be configurable/variable. - */ -const AllowedMethods = [ - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE -]; - - -/***/ }), -/* 83 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return ReSubscribeUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * Re-SUBSCRIBE UAC. - * @public - */ -class ReSubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - this.dialog = dialog; - } - waitNotifyStop() { - // TODO: Placeholder. Not utilized currently. - return; - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - const expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - const subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - const errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - super.receiveResponse(message); - } -} - - -/***/ }), -/* 84 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"]; }); - -/* harmony import */ var _logger_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _logger_factory__WEBPACK_IMPORTED_MODULE_1__["LoggerFactory"]; }); - -/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _logger__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); - - - - - - -/***/ }), -/* 85 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return Levels; }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels || (Levels = {})); - - -/***/ }), -/* 86 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return LoggerFactory; }); -/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); -/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87); - - -/** - * Logger. - * @public - */ -class LoggerFactory { - constructor() { - this.builtinEnabled = true; - this._level = _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - get level() { - return this._level; - } - set level(newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - // eslint-disable-next-line no-prototype-builtins - } - else if (_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get connector() { - return this._connector; - } - set connector(value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - } - getLogger(category, label) { - if (label && this.level === 3) { - return new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - const logger = new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category); - this.loggers[category] = logger; - return logger; - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - genericLog(levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"][levelToLog], category, label, content); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - print(levelToLog, category, label, content) { - if (typeof content === "string") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error: - // eslint-disable-next-line no-console - console.error(content); - break; - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn: - // eslint-disable-next-line no-console - console.warn(content); - break; - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log: - // eslint-disable-next-line no-console - console.log(content); - break; - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug: - // eslint-disable-next-line no-console - console.debug(content); - break; - default: - break; - } - } -} - - -/***/ }), -/* 87 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return Logger; }); -/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); - -/** - * Logger. - * @public - */ -class Logger { - constructor(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - error(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error, content); - } - warn(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn, content); - } - log(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log, content); - } - debug(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug, content); - } - genericLog(level, content) { - this.logger.genericLog(level, this.category, this.label, content); - } -} - - -/***/ }), -/* 88 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"]; }); - -/* harmony import */ var _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100); -/* harmony import */ var _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__) if(["UserAgentCore","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(101); -/* harmony import */ var _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__) if(["UserAgentCore","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - - -/***/ }), -/* 89 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return UserAgentCore; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(90); -/* harmony import */ var _allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); - - - - -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -const acceptedBodyTypes = ["application/sdp", "application/dtmf-relay"]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -class UserAgentCore { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - constructor(configuration, delegate = {}) { - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - dispose() { - this.reset(); - } - /** Reset. */ - reset() { - this.dialogs.forEach((dialog) => dialog.dispose()); - this.dialogs.clear(); - this.subscribers.forEach((subscriber) => subscriber.dispose()); - this.subscribers.clear(); - this.userAgentClients.forEach((uac) => uac.dispose()); - this.userAgentClients.clear(); - this.userAgentServers.forEach((uac) => uac.dispose()); - this.userAgentServers.clear(); - } - /** Logger factory. */ - get loggerFactory() { - return this.configuration.loggerFactory; - } - /** Transport. */ - get transport() { - const transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - } - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - invite(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentClient"](this, request, delegate); - } - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - message(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentClient"](this, request, delegate); - } - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - publish(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["PublishUserAgentClient"](this, request, delegate); - } - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - register(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentClient"](this, request, delegate); - } - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - subscribe(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["SubscribeUserAgentClient"](this, request, delegate); - } - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - request(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"](_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this, request, delegate); - } - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - const callIdPrefix = this.configuration.sipjsId; - const fromDisplayName = this.configuration.displayName; - const forceRport = this.configuration.viaForceRport; - const hackViaTcp = this.configuration.hackViaTcp; - const optionTags = this.configuration.supportedOptionTags.slice(); - if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - const routeSet = this.configuration.routeSet; - const userAgentString = this.configuration.userAgentHeaderFieldValue; - const viaHost = this.configuration.viaHost; - const defaultOptions = { - callIdPrefix, - forceRport, - fromDisplayName, - hackViaTcp, - optionTags, - routeSet, - userAgentString, - viaHost - }; - // merge provided options with default options - const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); - return new _messages__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"](method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - } - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - receiveIncomingRequestFromTransport(message) { - this.receiveRequestFromTransport(message); - } - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - receiveIncomingResponseFromTransport(message) { - this.receiveResponseFromTransport(message); - } - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - replyStateless(message, options) { - const userAgent = this.configuration.userAgentHeaderFieldValue; - const supported = this.configuration.supportedOptionTagsResponse; - options = Object.assign(Object.assign({}, options), { userAgent, supported }); - const response = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["constructOutgoingResponse"])(message, options); - this.transport.send(response.message).catch((error) => { - // If the transport rejects, it SHOULD reject with a TransportError. - // But the transport may be external code, so we are careful... - if (error instanceof Error) { - this.logger.error(error.message); - } - this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); - // TODO: Currently there is no hook to provide notification that a transport error occurred - // and throwing would result in an uncaught error (in promise), so we silently eat the error. - // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. - }); - return response; - } - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - receiveRequestFromTransport(message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - const uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - if (uas && uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Accepted) { - if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"]) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${transactionId}.`); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_1__["InviteServerTransaction"] && - uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { - if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"]) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - } - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - receiveRequest(message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].includes(message.method)) { - const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { - // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - const ruri = message.ruri; - const ruriMatches = (uri) => { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - const transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - const mergedRequest = Array.from(this.userAgentServers.values()).some((uas) => uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - } - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - receiveInsideDialogRequest(message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY) { - const event = message.parseHeader("Event"); - if (!event || !event.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - const subscriberId = message.callId + message.toTag + event.event; - const subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["NotifyUserAgentServer"](this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - const dialogId = message.callId + message.toTag + message.fromTag; - const dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS) { - const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - } - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - receiveOutsideDialogRequest(message) { - switch (message.method) { - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK: - // Absorb stray out of dialog ACKs - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL: - throw new Error(`Unexpected out of dialog request method ${message.method}.`); - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"](this, message); - this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentServer"](this, message); - this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["NotifyUserAgentServer"](this, message); - this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["ReferUserAgentServer"](this, message); - this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentServer"](this, message); - this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["SubscribeUserAgentServer"](this, message); - this.delegate.onSubscribe ? this.delegate.onSubscribe(uas) : uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error(`Unexpected out of dialog request method ${message.method}.`); - } - return; - } - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - receiveResponseFromTransport(message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - const userAgentClientId = message.viaBranch + message.method; - const userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn(`Discarding unmatched ${message.statusCode} response to ${message.method} ${userAgentClientId}.`); - } - } -} - - -/***/ }), -/* 90 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(62); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__["ByeUserAgentClient"]; }); - -/* harmony import */ var _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__["ByeUserAgentServer"]; }); - -/* harmony import */ var _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__["CancelUserAgentClient"]; }); - -/* harmony import */ var _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__["InfoUserAgentClient"]; }); - -/* harmony import */ var _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(67); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["InfoUserAgentServer"]; }); - -/* harmony import */ var _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(92); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["InviteUserAgentClient"]; }); - -/* harmony import */ var _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(93); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__["InviteUserAgentServer"]; }); - -/* harmony import */ var _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(68); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__["MessageUserAgentClient"]; }); - -/* harmony import */ var _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(69); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); - -/* harmony import */ var _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(70); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__["NotifyUserAgentClient"]; }); - -/* harmony import */ var _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(71); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__["NotifyUserAgentServer"]; }); - -/* harmony import */ var _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(94); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__["PublishUserAgentClient"]; }); - -/* harmony import */ var _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["PrackUserAgentClient"]; }); - -/* harmony import */ var _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"]; }); - -/* harmony import */ var _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"]; }); - -/* harmony import */ var _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["ReInviteUserAgentServer"]; }); - -/* harmony import */ var _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(83); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["ReSubscribeUserAgentClient"]; }); - -/* harmony import */ var _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(95); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["ReSubscribeUserAgentServer"]; }); - -/* harmony import */ var _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(76); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__["ReferUserAgentClient"]; }); - -/* harmony import */ var _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(77); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__["ReferUserAgentServer"]; }); - -/* harmony import */ var _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(96); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__["RegisterUserAgentClient"]; }); - -/* harmony import */ var _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(97); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__["RegisterUserAgentServer"]; }); - -/* harmony import */ var _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(98); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__["SubscribeUserAgentClient"]; }); - -/* harmony import */ var _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(99); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__["SubscribeUserAgentServer"]; }); - -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(63); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agent_client__WEBPACK_IMPORTED_MODULE_24__["UserAgentClient"]; }); - -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(65); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agent_server__WEBPACK_IMPORTED_MODULE_25__["UserAgentServer"]; }); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/***/ }), -/* 91 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return CancelUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * CANCEL UAC. - * @public - */ -class CancelUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 92 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return InviteUserAgentClient; }); -/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); - - - - -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -class InviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_3__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"], core, message, delegate); - this.confirmedDialogAcks = new Map(); - this.confirmedDialogs = new Map(); - this.earlyDialogs = new Map(); - this.delegate = delegate; - } - dispose() { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - super.dispose(); - } - /** - * Special case for transport error while sending ACK. - * @param error - Transport error - */ - onTransportError(error) { - if (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { - return super.onTransportError(error); - } - // If not in 'calling' state, the transport error occurred while sending an ACK. - this.logger.error(error.message); - this.logger.error("User agent client request transport error while sending ACK."); - } - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Dialogs are created through the generation of non-failure responses - // to requests with specific methods. Within this specification, only - // 2xx and 101-199 responses with a To tag, where the request was - // INVITE, will establish a dialog. A dialog established by a non-final - // response to a request is in the "early" state and it is called an - // early dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1 - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - // Provisional without Contact header field, malformed response. - const contact = message.parseHeader("contact"); - if (!contact) { - this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping."); - return; - } - // Compute dialog state. - const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - let earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || - earlyDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - const session = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message, - session, - prack: (options) => { - const outgoingPrackRequest = session.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Dialogs are created through the generation of non-failure responses - // to requests with specific methods. Within this specification, only - // 2xx and 101-199 responses with a To tag, where the request was - // INVITE, will establish a dialog. A dialog established by a non-final - // response to a request is in the "early" state and it is called an - // early dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1 - // Final without to tag, malformed response. - if (!message.toTag) { - this.logger.error("2xx INVITE response received without a to tag, dropping."); - return; - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - // Final without Contact header field, malformed response. - const contact = message.parseHeader("contact"); - if (!contact) { - this.logger.error("2xx INVITE response received without a Contact header field, dropping."); - return; - } - // Compute dialog state. - const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - let dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || - dialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - const session = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message, - session, - ack: (options) => { - const outgoingAckRequest = session.ack(options); - this.confirmedDialogAcks.set(session.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - const outgoingAckRequest = session.ack(); - this.confirmedDialogAcks.set(session.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - return; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - throw new Error(`Executing what should be an unreachable code path receiving ${statusCode} response.`); - } -} - - -/***/ }), -/* 93 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return InviteUserAgentServer; }); -/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(44); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); -/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(82); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(65); - - - - - - -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -class InviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_5__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"], core, message, delegate); - this.core = core; - } - dispose() { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - super.dispose(); - } - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - accept(options = { statusCode: 200 }) { - if (!this.acceptable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"](`${this.message.method} not acceptable in state ${this.transaction.state}.`); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); - const contactHeader = `Contact: ${this.core.configuration.contact.toString()}`; - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__["AllowedMethods"].toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Initial || - this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - const response = super.accept(options); - const session = this.confirmedDialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - } - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - progress(options = { statusCode: 180 }) { - if (!this.progressable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"](`${this.message.method} not progressable in state ${this.transaction.state}.`); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); - const contactHeader = `Contact: ${this.core.configuration.contact}`; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - const response = super.progress(options); - const session = this.earlyDialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - } - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts, options = { statusCode: 302 }) { - return super.redirect(contacts, options); - } - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - reject(options = { statusCode: 486 }) { - return super.reject(options); - } -} - - -/***/ }), -/* 94 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return PublishUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * PUBLISH UAC. - * @public - */ -class PublishUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 95 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return ReSubscribeUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * Re-SUBSCRIBE UAS. - * @public - */ -class ReSubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 96 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return RegisterUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * REGISTER UAC. - * @public - */ -class RegisterUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 97 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return RegisterUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * REGISTER UAS. - * @public - */ -class RegisterUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); - this.core = core; - } -} - - -/***/ }), -/* 98 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return SubscribeUserAgentClient; }); -/* harmony import */ var _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(63); - - - - - -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE requests. - * @public - */ -class SubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_4__["UserAgentClient"] { - constructor(core, message, delegate) { - // Get event from request message. - const event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from request message. - const expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - super(_transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"], core, message, delegate); - this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - this.subscriberId = message.callId + message.fromTag + event; - this.subscriptionExpiresRequested = this.subscriptionExpires = Number(expires); - this.subscriptionEvent = event; - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - this.waitNotifyStart(); - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - dispose() { - super.dispose(); - } - /** - * Handle out of dialog NOTIFY associated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - onNotify(uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - const event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn(`Failed to parse event.`); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - const state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn(`Invalid subscription state ${state}`); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - const contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install multiple subscriptions. - // As such and in accordance with the specification, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = subscriptionState.expires - ? Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) - : this.subscriptionExpires; - // Update subscription state. - switch (state) { - case "pending": - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending; - break; - case "active": - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active; - break; - case "terminated": - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated; - break; - default: - throw new Error(`Unrecognized state ${state}.`); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - const dialogState = _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"].initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"](this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - const request = uas; - const subscription = this.dialog; - this.delegate.onNotify({ request, subscription }); - } - else { - uas.accept(); - } - } - waitNotifyStart() { - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].TIMER_N); - } - } - waitNotifyStop() { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - const expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - const subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - super.receiveResponse(message); - } - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - timerN() { - this.logger.warn(`Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY.`); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - } -} - - -/***/ }), -/* 99 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return SubscribeUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * SUBSCRIBE UAS. - * @public - */ -class SubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); - this.core = core; - } -} - - -/***/ }), -/* 100 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 101 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 102 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 103 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return RequestPendingError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating an outstanding prior request prevented execution. - * @public - */ -class RequestPendingError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - /** @internal */ - constructor(message) { - super(message ? message : "Request pending."); - } -} - - -/***/ }), -/* 104 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return SessionDescriptionHandlerError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating a session description handler error occured. - * @public - */ -class SessionDescriptionHandlerError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Unspecified session description handler error."); - } -} - - -/***/ }), -/* 105 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return SessionTerminatedError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating the session terminated before the action completed. - * @public - */ -class SessionTerminatedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor() { - super("The session has terminated."); - } -} - - -/***/ }), -/* 106 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return StateTransitionError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating an invalid state transition error occured. - * @public - */ -class StateTransitionError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "An error occurred during state transition."); - } -} - - -/***/ }), -/* 107 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return Bye; }); -/** - * A request to end a {@link Session} (incoming BYE). - * @public - */ -class Bye { - /** @internal */ - constructor(incomingByeRequest) { - this.incomingByeRequest = incomingByeRequest; - } - /** Incoming BYE request message. */ - get request() { - return this.incomingByeRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingByeRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingByeRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 108 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return EmitterImpl; }); -/** - * An {@link Emitter} implementation. - * @internal - */ -class EmitterImpl { - constructor() { - this.listeners = new Array(); - } - /** - * Sets up a function that will be called whenever the target changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addListener(listener, options) { - const onceWrapper = (data) => { - this.removeListener(onceWrapper); - listener(data); - }; - (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); - } - /** - * Emit change. - * @param data - Data to emit. - */ - emit(data) { - this.listeners.slice().forEach((listener) => listener(data)); - } - /** - * Removes all listeners previously registered with addListener. - */ - removeAllListeners() { - this.listeners = []; - } - /** - * Removes a listener previously registered with addListener. - * @param listener - Callback function. - */ - removeListener(listener) { - this.listeners = this.listeners.filter((l) => l !== listener); - } - /** - * Registers a listener. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - on(listener) { - return this.addListener(listener); - } - /** - * Unregisters a listener. - * @param listener - Callback function. - * @deprecated Use removeListener. - */ - off(listener) { - return this.removeListener(listener); - } - /** - * Registers a listener then unregisters the listener after one event emission. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - once(listener) { - return this.addListener(listener, { once: true }); - } -} - - -/***/ }), -/* 109 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return Info; }); -/** - * An exchange of information (incoming INFO). - * @public - */ -class Info { - /** @internal */ - constructor(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - /** Incoming MESSAGE request message. */ - get request() { - return this.incomingInfoRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 110 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 111 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 112 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 113 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return Invitation; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(114); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(118); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(119); - - - - - - -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -class Invitation extends _session__WEBPACK_IMPORTED_MODULE_3__["Session"] { - /** @internal */ - constructor(userAgent, incomingInviteRequest) { - super(userAgent); - this.incomingInviteRequest = incomingInviteRequest; - /** True if dispose() has been called. */ - this.disposed = false; - /** INVITE will be rejected if not accepted within a certain period time. */ - this.expiresTimer = undefined; - /** True if this Session has been Terminated due to a CANCEL request. */ - this.isCanceled = false; - /** Are reliable provisional responses required or supported. */ - this.rel100 = "none"; - /** The current RSeq header value. */ - this.rseq = Math.floor(Math.random() * 10000); - /** INVITE will be rejected if final response not sent in a certain period time. */ - this.userNoAnswerTimer = undefined; - /** True if waiting for a PRACK before sending a 200 Ok. */ - this.waitingForPrack = false; - this.logger = userAgent.getLogger("sip.Invitation"); - const incomingRequestMessage = this.incomingInviteRequest.message; - // Set 100rel if necessary - const requireHeader = incomingRequestMessage.getHeader("require"); - if (requireHeader && requireHeader.toLowerCase().includes("100rel")) { - this.rel100 = "required"; - } - const supportedHeader = incomingRequestMessage.getHeader("supported"); - if (supportedHeader && supportedHeader.toLowerCase().includes("100rel")) { - this.rel100 = "supported"; - } - // FIXME: HACK: This is a hack to port an existing behavior. - // Set the toTag on the incoming request message to the toTag which - // will be used in the response to the incoming request!!! - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - // eslint-disable-next-line @typescript-eslint/no-explicit-any - incomingRequestMessage.toTag = incomingInviteRequest.toTag; - if (typeof incomingRequestMessage.toTag !== "string") { - throw new TypeError("toTag should have been a string."); - } - // The following mapping values are RECOMMENDED: - // ... - // 19 no answer from the user 480 Temporarily unavailable - // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 - this.userNoAnswerTimer = setTimeout(() => { - incomingInviteRequest.reject({ statusCode: 480 }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); - // 1. If the request is an INVITE that contains an Expires header - // field, the UAS core sets a timer for the number of seconds - // indicated in the header field value. When the timer fires, the - // invitation is considered to be expired. If the invitation - // expires before the UAS has generated a final response, a 487 - // (Request Terminated) response SHOULD be generated. - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - if (incomingRequestMessage.hasHeader("expires")) { - const expires = Number(incomingRequestMessage.getHeader("expires") || 0) * 1000; - this.expiresTimer = setTimeout(() => { - if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { - incomingInviteRequest.reject({ statusCode: 487 }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - }, expires); - } - // Session parent properties - const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(assertedIdentity); - } - this._contact = this.userAgent.contact.toString(); - const contentDisposition = incomingRequestMessage.parseHeader("Content-Disposition"); - if (contentDisposition && contentDisposition.type === "render") { - this._renderbody = incomingRequestMessage.body; - this._rendertype = incomingRequestMessage.getHeader("Content-Type"); - } - // Identifier - this._id = incomingRequestMessage.callId + incomingRequestMessage.fromTag; - // Add to the user agent's session collection. - this.userAgent._sessions[this._id] = this; - } - /** - * Destructor. - */ - dispose() { - // Only run through this once. It can and does get called multiple times - // depending on the what the sessions state is when first called. - // For example, if called when "establishing" it will be called again - // at least once when the session transitions to "terminated". - // Regardless, running through this more than once is pointless. - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - // Clear timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - this.expiresTimer = undefined; - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - this.userNoAnswerTimer = undefined; - } - // If accept() is still waiting for a PRACK, make sure it rejects - this.prackNeverArrived(); - // If the final response for the initial INVITE not yet been sent, reject it - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial: - return this.reject().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing: - return this.reject().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminating: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated: - return super.dispose(); - default: - throw new Error("Unknown state."); - } - } - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - get autoSendAnInitialProvisionalResponse() { - return this.rel100 === "required" ? false : true; - } - /** - * Initial incoming INVITE request message body. - */ - get body() { - return this.incomingInviteRequest.message.body; - } - /** - * The identity of the local user. - */ - get localIdentity() { - return this.request.to; - } - /** - * The identity of the remote user. - */ - get remoteIdentity() { - return this.request.from; - } - /** - * Initial incoming INVITE request message. - */ - get request() { - return this.incomingInviteRequest.message; - } - /** - * Accept the invitation. - * - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * Resolves once the response sent, otherwise rejects. - * - * This method may reject for a variety of reasons including - * the receipt of a CANCEL request before `accept` is able - * to construct a response. - * @param options - Options bucket. - */ - accept(options = {}) { - this.logger.log("Invitation.accept"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing); - return (this.sendAccept() - // eslint-disable-next-line @typescript-eslint/no-unused-vars - .then(({ message, session }) => { - session.delegate = { - onAck: (ackRequest) => this.onAckRequest(ackRequest), - onAckTimeout: () => this.onAckTimeout(), - onBye: (byeRequest) => this.onByeRequest(byeRequest), - onInfo: (infoRequest) => this.onInfoRequest(infoRequest), - onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), - onMessage: (messageRequest) => this.onMessageRequest(messageRequest), - onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), - onPrack: (prackRequest) => this.onPrackRequest(prackRequest), - onRefer: (referRequest) => this.onReferRequest(referRequest) - }; - this._dialog = session; - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established); - // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. - // This behavior has been ported forward from legacy versions. - if (this._replacee) { - this._replacee._bye(); - } - }) - .catch((error) => this.handleResponseError(error))); - } - /** - * Indicate progress processing the invitation. - * - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * Resolves once the response sent, otherwise rejects. - * @param options - Options bucket. - */ - progress(options = {}) { - this.logger.log("Invitation.progress"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // Ported - const statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.waitingForPrack) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return Promise.resolve(); - } - // Trying provisional response - if (options.statusCode === 100) { - return this.sendProgressTrying() - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - // Standard provisional response - if (!(this.rel100 === "required") && - !(this.rel100 === "supported" && options.rel100) && - !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_5__["SIPExtension"].Required)) { - return this.sendProgress(options) - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - // Reliable provisional response - return this.sendProgressReliableWaitForPrack(options) - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - /** - * Reject the invitation. - * - * @remarks - * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. - * Resolves once the response sent, otherwise rejects. - * - * The expectation is that this method is used to reject an INVITE request. - * That is indeed the case - a call to `progress` followed by `reject` is - * a typical way to "decline" an incoming INVITE request. However it may - * also be called after calling `accept` (but only before it completes) - * which will reject the call and cause `accept` to reject. - * @param options - Options bucket. - */ - reject(options = {}) { - this.logger.log("Invitation.reject"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - const statusCode = options.statusCode || 480; - const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(statusCode); - const extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(options.body) : undefined; - // FIXME: Need to redirect to someplace - statusCode < 400 - ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) - : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - return Promise.resolve(); - } - /** - * Handle CANCEL request. - * - * @param message - CANCEL message. - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _onCancel(message) { - this.logger.log("Invitation._onCancel"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { - this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); - return; - } - // flag canceled - this.isCanceled = true; - // reject INVITE with 487 status code - this.incomingInviteRequest.reject({ statusCode: 487 }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - /** - * Helper function to handle offer/answer in a PRACK. - */ - handlePrackOfferAnswer(request) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - const options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.dialog.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: - // Receved answer. - return this.setAnswer(body, options).then(() => undefined); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: - // Received offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - } - } - /** - * A handler for errors which occur while attempting to send 1xx and 2xx responses. - * In all cases, an attempt is made to reject the request if it is still outstanding. - * And while there are a variety of things which can go wrong and we log something here - * for all errors, there are a handful of common exceptions we pay some extra attention to. - * @param error - The error which occurred. - */ - handleResponseError(error) { - let statusCode = 480; // "Temporarily Unavailable" - // Log Error message - if (error instanceof Error) { - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw our way, - // and more generally as a last resort catch all, just assume we are getting an "unknown" and log it. - this.logger.error(error); - } - // Log Exception message - if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["ContentTypeUnsupportedError"]) { - this.logger.error("A session description handler occurred while sending response (content type unsupported"); - statusCode = 415; // "Unsupported Media Type" - } - else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]) { - this.logger.error("A session description handler occurred while sending response"); - } - else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]) { - this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"); - } - else if (error instanceof _core__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"]) { - this.logger.error("Session changed state before response could be formulated and sent"); - } - // Reject if still in "initial" or "establishing" state. - if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial || this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { - try { - this.incomingInviteRequest.reject({ statusCode }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - catch (e) { - this.logger.error("An error occurred attempting to reject the request while handling another error"); - throw e; // This is not a good place to be... - } - } - // FIXME: TODO: - // Here we are squelching the throwing of errors due to an race condition. - // We have an internal race between calling `accept()` and handling an incoming - // CANCEL request. As there is no good way currently to delegate the handling of - // these race errors to the caller of `accept()`, we are squelching the throwing - // of ALL errors when/if they occur after receiving a CANCEL to catch the ONE we know - // is a "normal" exceptional condition. While this is a completely reasonable approach, - // the decision should be left up to the library user. Furthermore, as we are eating - // ALL errors in this case, we are potentially (likely) hiding "real" errors which occur. - // - // Only rethrow error if the session has not been canceled. - if (this.isCanceled) { - this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE." + - " However a CANCEL was received and processed while doing so which can (and often does) result" + - " in errors occurring as the session terminates in the meantime. Said error is being ignored."); - return; - } - throw error; - } - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - onAckTimeout() { - this.logger.log("Invitation.onAckTimeout"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.log("No ACK received for an extended period of time, terminating session"); - this.dialog.bye(); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - sendAccept() { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.waitingForPrack) { - return this.waitForArrivalOfPrack() - .then(() => clearTimeout(this.userNoAnswerTimer)) // Ported - .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions)) - .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); - } - clearTimeout(this.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions).then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); - } - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - sendProgress(options = {}) { - const statusCode = options.statusCode || 180; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this.sendProgressWithSDP(options); - } - try { - const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - this._dialog = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - } - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - sendProgressWithSDP(options = {}) { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - const statusCode = options.statusCode || 183; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) - .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) - .then((progressResponse) => { - this._dialog = progressResponse.session; - return progressResponse; - }); - } - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - sendProgressReliable(options = {}) { - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push("Require: 100rel"); - options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - return this.sendProgressWithSDP(options); - } - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - sendProgressReliableWaitForPrack(options = {}) { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - const statusCode = options.statusCode || 183; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - let body; - return new Promise((resolve, reject) => { - this.waitingForPrack = true; - this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) - .then((offerAnswer) => { - body = offerAnswer; - return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - }) - .then((progressResponse) => { - this._dialog = progressResponse.session; - let prackRequest; - let prackResponse; - progressResponse.session.delegate = { - onPrack: (request) => { - prackRequest = request; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(prackWaitTimeoutTimer); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(rel1xxRetransmissionTimer); - if (!this.waitingForPrack) { - return; - } - this.waitingForPrack = false; - this.handlePrackOfferAnswer(prackRequest) - .then((prackResponseBody) => { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - this.prackArrived(); - resolve({ prackRequest, prackResponse, progressResponse }); - } - catch (error) { - reject(error); - } - }) - .catch((error) => reject(error)); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - const prackWaitTimeout = () => { - if (!this.waitingForPrack) { - return; - } - this.waitingForPrack = false; - this.logger.warn("No PRACK received, rejecting INVITE."); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(rel1xxRetransmissionTimer); - this.reject({ statusCode: 504 }) - .then(() => reject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]())) - .catch((error) => reject(error)); - }; - const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - const rel1xxRetransmission = () => { - try { - this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - } - catch (error) { - this.waitingForPrack = false; - reject(error); - return; - } - // eslint-disable-next-line @typescript-eslint/no-use-before-define - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, (timeout *= 2)); - }; - let timeout = _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1; - let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }) - .catch((error) => { - this.waitingForPrack = false; - reject(error); - }); - }); - } - /** - * A version of `progress` which resolves when a 100 Trying provisional response is sent. - */ - sendProgressTrying() { - try { - const progressResponse = this.incomingInviteRequest.trying(); - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - } - /** - * When attempting to accept the INVITE, an invitation waits - * for any outstanding PRACK to arrive before sending the 200 Ok. - * It will be waiting on this Promise to resolve which lets it know - * the PRACK has arrived and it may proceed to send the 200 Ok. - */ - waitForArrivalOfPrack() { - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise((resolve, reject) => { - this.waitingForPrackResolve = resolve; - this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - } - /** - * Here we are resolving the promise which in turn will cause - * the accept to proceed (it may still fail for other reasons, but...). - */ - prackArrived() { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - } - /** - * Here we are rejecting the promise which in turn will cause - * the accept to fail and the session to transition to "terminated". - */ - prackNeverArrived() { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - } -} - - -/***/ }), -/* 114 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return Session; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(107); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(108); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3); -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(109); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(115); -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(116); -/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(117); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(118); - - - - - - - - - - - -/** - * A session provides real time communication between one or more participants. - * - * @remarks - * The transport behaves in a deterministic manner according to the - * the state defined in {@link SessionState}. - * @public - */ -class Session { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - constructor(userAgent, options = {}) { - /** True if there is an outgoing re-INVITE request outstanding. */ - this.pendingReinvite = false; - /** True if there is an incoming re-INVITE ACK request outstanding. */ - this.pendingReinviteAck = false; - /** Session state. */ - this._state = _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial; - this.delegate = options.delegate; - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_4__["EmitterImpl"](); - this._userAgent = userAgent; - } - /** - * Destructor. - */ - dispose() { - this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`); - // Remove from the user agent's session collection - delete this.userAgent._sessions[this.id]; - // Dispose of dialog media - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - // TODO: The SDH needs to remain defined as it will be called after it is closed in cases - // where an answer/offer arrives while the session is being torn down. There are a variety - // of circumstances where this can happen - sending a BYE during a re-INVITE for example. - // The code is currently written such that it lazily makes a new SDH when it needs one - // and one is not yet defined. Thus if we undefined it here, it will currently make a - // new one which is out of sync and then never gets cleaned up. - // - // The downside of leaving it defined are that calls this closed SDH will continue to be - // made (think setDescription) and those should/will fail. These failures are handled, but - // it would be nice to have it all coded up in a way where having an undefined SDH where - // one is expected throws an error. - // - // this._sessionDescriptionHandler = undefined; - } - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: - break; // the Inviter/Invitation sub class dispose method handles this case - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: - break; // the Inviter/Invitation sub class dispose method handles this case - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: - return new Promise((resolve) => { - this._bye({ - // wait for the response to the BYE before resolving - onAccept: () => resolve(), - onRedirect: () => resolve(), - onReject: () => resolve() - }); - }); - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: - break; // nothing to be done - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: - break; // nothing to be done - default: - throw new Error("Unknown state."); - } - return Promise.resolve(); - } - /** - * The asserted identity of the remote user. - */ - get assertedIdentity() { - return this._assertedIdentity; - } - /** - * The confirmed session dialog. - */ - get dialog() { - return this._dialog; - } - /** - * A unique identifier for this session. - */ - get id() { - return this._id; - } - /** - * The session being replace by this one. - */ - get replacee() { - return this._replacee; - } - /** - * Session description handler. - * @remarks - * If `this` is an instance of `Invitation`, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". - * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * Otherwise `undefined`. - */ - get sessionDescriptionHandler() { - return this._sessionDescriptionHandler; - } - /** - * Session description handler factory. - */ - get sessionDescriptionHandlerFactory() { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - } - /** - * SDH modifiers for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerModifiers() { - return this._sessionDescriptionHandlerModifiers || []; - } - set sessionDescriptionHandlerModifiers(modifiers) { - this._sessionDescriptionHandlerModifiers = modifiers.slice(); - } - /** - * SDH options for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerOptions() { - return this._sessionDescriptionHandlerOptions || {}; - } - set sessionDescriptionHandlerOptions(options) { - this._sessionDescriptionHandlerOptions = Object.assign({}, options); - } - /** - * SDH modifiers for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerModifiersReInvite() { - return this._sessionDescriptionHandlerModifiersReInvite || []; - } - set sessionDescriptionHandlerModifiersReInvite(modifiers) { - this._sessionDescriptionHandlerModifiersReInvite = modifiers.slice(); - } - /** - * SDH options for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerOptionsReInvite() { - return this._sessionDescriptionHandlerOptionsReInvite || {}; - } - set sessionDescriptionHandlerOptionsReInvite(options) { - this._sessionDescriptionHandlerOptionsReInvite = Object.assign({}, options); - } - /** - * Session state. - */ - get state() { - return this._state; - } - /** - * Session state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * The user agent. - */ - get userAgent() { - return this._userAgent; - } - /** - * End the {@link Session}. Sends a BYE. - * @param options - Options bucket. See {@link SessionByeOptions} for details. - */ - bye(options = {}) { - let message = "Session.bye() may only be called if established session."; - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " However Inviter.invite() has not yet been called."; - message += " Perhaps you should have called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " However Invitation.accept() has not yet been called."; - message += " Perhaps you should have called Invitation.reject()?"; - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " However a dialog does not yet exist."; - message += " Perhaps you should have called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " However Invitation.accept() has not yet been called (or not yet resolved)."; - message += " Perhaps you should have called Invitation.reject()?"; - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: { - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._bye(requestDelegate, requestOptions); - } - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: - message += " However this session is already terminating."; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " Perhaps you have already called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " Perhaps you have already called Session.bye()?"; - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: - message += " However this session is already terminated."; - break; - default: - throw new Error("Unknown state"); - } - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - /** - * Share {@link Info} with peer. Sends an INFO. - * @param options - Options bucket. See {@link SessionInfoOptions} for details. - */ - info(options = {}) { - // guard session state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - const message = "Session.info() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._info(requestDelegate, requestOptions); - } - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. See {@link SessionInviteOptions} for details. - */ - invite(options = {}) { - this.logger.log("Session.invite"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - if (this.pendingReinvite) { - return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["RequestPendingError"]("Reinvite in progress. Please wait until complete, then try again.")); - } - this.pendingReinvite = true; - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptions; - } - const delegate = { - onAccept: (response) => { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Received 2xx response to re-INVITE without a session description"); - this.ackAndBye(response, 400, "Missing session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - const answerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.setOfferAndGetAnswer(body, answerOptions) - .then((answerBody) => { - response.ack({ body: answerBody }); - }) - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - this.logger.error(error.message); - if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - // A BYE should not be sent if already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - response.ack(); - } - else { - this.ackAndBye(response, 488, "Bad Media Description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - }) - .then(() => { - this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - const answerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.setAnswer(body, answerOptions) - .then(() => { - response.ack(); - }) - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - this.logger.error(error.message); - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // The ACK needs to be sent regardless as it was not handled by the transaction. - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - this.ackAndBye(response, 488, "Bad Media Description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - else { - response.ack(); - } - }) - .then(() => { - this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onProgress: (response) => { - return; - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect: (response) => { - return; - }, - onReject: (response) => { - this.logger.warn("Received a non-2xx response to re-INVITE"); - this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - this.rollbackOffer() - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - this.logger.error(error.message); - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // Note that the ACK was already sent by the transaction, so just need to send BYE. - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - const extraHeaders = []; - extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); - this.dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTrying: (response) => { - return; - } - }; - const requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__["AllowedMethods"].toString()); - requestOptions.extraHeaders.push("Contact: " + this._contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - const offerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - return this.getOffer(offerOptions) - .then((offerBody) => { - if (!this.dialog) { - this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return this.dialog.invite(delegate, requestOptions); - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.error("Failed to send re-INVITE"); - this.pendingReinvite = false; - throw error; - }); - } - /** - * Deliver a {@link Message}. Sends a MESSAGE. - * @param options - Options bucket. See {@link SessionMessageOptions} for details. - */ - message(options = {}) { - // guard session state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - const message = "Session.message() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._message(requestDelegate, requestOptions); - } - /** - * Proffer a {@link Referral}. Send a REFER. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - Options bucket. See {@link SessionReferOptions} for details. - */ - refer(referTo, options = {}) { - // guard session state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - const message = "Session.refer() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - requestOptions.extraHeaders = requestOptions.extraHeaders - ? requestOptions.extraHeaders.concat(this.referExtraHeaders(this.referToString(referTo))) - : this.referExtraHeaders(this.referToString(referTo)); - return this._refer(options.onNotify, requestDelegate, requestOptions); - } - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _bye(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - const dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].AckWait: { - // This state only occurs if we are the callee. - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating); // We're terminating - return new Promise((resolve) => { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: () => { - const request = dialog.bye(delegate, options); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - resolve(request); - return Promise.resolve(); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: () => { - const request = dialog.bye(delegate, options); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - resolve(request); - } - }; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Confirmed: { - const request = dialog.bye(delegate, options); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(request); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - default: - throw new Error("Unrecognized state."); - } - } - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _info(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - } - /** - * Send MESSAGE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _message(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.message(delegate, options)); - } - /** - * Send REFER. - * @param onNotify - Notification callback. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _refer(onNotify, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If set, deliver any in-dialog NOTIFY requests here... - this.onNotify = onNotify; - return Promise.resolve(this.dialog.refer(delegate, options)); - } - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and send a BYE. - * Note that the BYE is sent in the dialog associated with the response - * which is not necessarily `this.dialog`. And, accordingly, the - * session state is not transitioned to terminated and session is not closed. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - ackAndBye(response, statusCode, reasonPhrase) { - response.ack(); - const extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); - } - // Using the dialog session associate with the response (which might not be this.dialog) - response.session.bye(undefined, { extraHeaders }); - } - /** - * Handle in dialog ACK request. - * @internal - */ - onAckRequest(request) { - this.logger.log("Session.onAckRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating) { - this.logger.error(`ACK received while in state ${this.state}, dropping request`); - return Promise.resolve(); - } - const dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // if received answer in ACK. - const answerOptions = { - sessionDescriptionHandlerOptions: this.pendingReinviteAck - ? this.sessionDescriptionHandlerOptionsReInvite - : this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.pendingReinviteAck - ? this._sessionDescriptionHandlerModifiersReInvite - : this._sessionDescriptionHandlerModifiers - }; - // reset pending ACK flag - this.pendingReinviteAck = false; - switch (dialog.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: { - // State should never be reached as first reliable response must have answer/offer. - // So we must have never has sent an offer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { - // State we should be in. - // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); - // If the ACK doesn't have an answer, nothing to be done. - if (!body) { - return Promise.resolve(); - } - if (body.contentDisposition === "render") { - this._renderbody = body.content; - this._rendertype = body.contentType; - return Promise.resolve(); - } - if (body.contentDisposition !== "session") { - return Promise.resolve(); - } - return this.setAnswer(body, answerOptions).catch((error) => { - this.logger.error(error.message); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: { - // State should never be reached as local offer would be answered by this ACK. - // So we must have received an ACK without an answer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: { - // State should never be reached as remote offer would be answered in first reliable response. - // So we must have never has sent an answer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - throw new Error(`Invalid signaling state ${dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${dialog.signalingState}.`); - } - } - /** - * Handle in dialog BYE request. - * @internal - */ - onByeRequest(request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`BYE received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onBye) { - const bye = new _bye__WEBPACK_IMPORTED_MODULE_3__["Bye"](request); - this.delegate.onBye(bye); - } - else { - request.accept(); - } - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - /** - * Handle in dialog INFO request. - * @internal - */ - onInfoRequest(request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`INFO received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onInfo) { - const info = new _info__WEBPACK_IMPORTED_MODULE_6__["Info"](request); - this.delegate.onInfo(info); - } - else { - // FIXME: TODO: We should reject request... - // - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - // https://tools.ietf.org/html/rfc6086#section-4.2.2 - request.accept(); - } - } - /** - * Handle in dialog INVITE request. - * @internal - */ - onInviteRequest(request) { - this.logger.log("Session.onInviteRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`INVITE received while in state ${this.state}, dropping request`); - return; - } - // set pending ACK flag - this.pendingReinviteAck = true; - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - const extraHeaders = ["Contact: " + this._contact]; - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - const header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(header); - } - const options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.generateResponseOfferAnswerInDialog(options) - .then((body) => { - const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.error("Failed to handle to re-INVITE request"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.error(this.dialog.signalingState); - // If we don't have a local/remote offer... - if (this.dialog.signalingState === _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable) { - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - this.rollbackOffer() - .then(() => { - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch((errorRollback) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error(errorRollback.message); - this.logger.error("Failed to rollback offer on re-INVITE request"); - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // Note that the ACK was already sent by the transaction, so just need to send BYE. - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - const extraHeadersBye = []; - extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); - this.dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - } - /** - * Handle in dialog MESSAGE request. - * @internal - */ - onMessageRequest(request) { - this.logger.log("Session.onMessageRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onMessage) { - const message = new _message__WEBPACK_IMPORTED_MODULE_7__["Message"](request); - this.delegate.onMessage(message); - } - else { - request.accept(); - } - } - /** - * Handle in dialog NOTIFY request. - * @internal - */ - onNotifyRequest(request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); - return; - } - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated callback. - if (this.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); - this.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - } - /** - * Handle in dialog PRACK request. - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onPrackRequest(request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`PRACK received while in state ${this.state}, dropping request`); - return; - } - throw new Error("Unimplemented."); - } - /** - * Handle in dialog REFER request. - * @internal - */ - onReferRequest(request) { - this.logger.log("Session.onReferRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`REFER received while in state ${this.state}, dropping request`); - return; - } - // REFER is a SIP request and is constructed as defined in [1]. A REFER - // request MUST contain exactly one Refer-To header field value. - // https://tools.ietf.org/html/rfc3515#section-2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - const referral = new _referral__WEBPACK_IMPORTED_MODULE_9__["Referral"](request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral - .accept() - .then(() => referral.makeInviter(this._referralInviterOptions).invite()) - .catch((error) => { - // FIXME: logging and eating error... - this.logger.error(error.message); - }); - } - } - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - generateResponseOfferAnswer(request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - } - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - generateResponseOfferAnswerInDialog(options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - return this.getOffer(options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - } - } - /** - * Get local offer. - * @internal - */ - getOffer(options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - return sdh - .getDescription(sdhOptions, sdhModifiers) - .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) - .catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.getOffer: SDH getDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.getOffer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.getOffer: SDH getDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Rollback local/remote offer. - * @internal - */ - rollbackOffer() { - const sdh = this.setupSessionDescriptionHandler(); - if (sdh.rollbackDescription === undefined) { - return Promise.resolve(); - } - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - return sdh.rollbackDescription().catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.rollbackOffer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Set remote answer. - * @internal - */ - setAnswer(answer, options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); - } - } - catch (error) { - this.logger.error("Session.setAnswer: SDH hasDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - try { - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers).catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.setAnswer: SDH setDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.setAnswer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.setAnswer: SDH setDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Set remote offer and get local answer. - * @internal - */ - setOfferAndGetAnswer(offer, options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); - } - } - catch (error) { - this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - try { - return sdh - .setDescription(offer.content, sdhOptions, sdhModifiers) - .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) - .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) - .catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.setOfferAndGetAnswer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * SDH for confirmed dialog. - * @internal - */ - setSessionDescriptionHandler(sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Session description handler defined."); - } - this._sessionDescriptionHandler = sdh; - } - /** - * SDH for confirmed dialog. - * @internal - */ - setupSessionDescriptionHandler() { - var _a; - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { - this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler, false); - } - return this._sessionDescriptionHandler; - } - /** - * Transition session state. - * @internal - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - this.dispose(); - } - } - copyRequestOptions(requestOptions = {}) { - const extraHeaders = requestOptions.extraHeaders ? requestOptions.extraHeaders.slice() : undefined; - const body = requestOptions.body - ? { - contentDisposition: requestOptions.body.contentDisposition || "render", - contentType: requestOptions.body.contentType || "text/plain", - content: requestOptions.body.content || "" - } - : undefined; - return { - extraHeaders, - body - }; - } - getReasonHeaderValue(code, reason) { - const cause = code; - let text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code); - if (!text && reason) { - text = reason; - } - return "SIP;cause=" + cause + ';text="' + text + '"'; - } - referExtraHeaders(referTo) { - const extraHeaders = []; - extraHeaders.push("Referred-By: <" + this.userAgent.configuration.uri + ">"); - extraHeaders.push("Contact: " + this._contact); - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - extraHeaders.push("Refer-To: " + referTo); - return extraHeaders; - } - referToString(target) { - let referTo; - if (target instanceof _core__WEBPACK_IMPORTED_MODULE_0__["URI"]) { - // REFER without Replaces (Blind Transfer) - referTo = target.toString(); - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.dialog) { - throw new Error("Dialog undefined."); - } - const displayName = target.remoteIdentity.friendlyName; - const remoteTarget = target.dialog.remoteTarget.toString(); - const callId = target.dialog.callId; - const remoteTag = target.dialog.remoteTag; - const localTag = target.dialog.localTag; - const replaces = encodeURIComponent(`${callId};to-tag=${remoteTag};from-tag=${localTag}`); - referTo = `"${displayName}" <${remoteTarget}?Replaces=${replaces}>`; - } - return referTo; - } -} - - -/***/ }), -/* 115 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; }); -/** - * A received message (incoming MESSAGE). - * @public - */ -class Message { - /** @internal */ - constructor(incomingMessageRequest) { - this.incomingMessageRequest = incomingMessageRequest; - } - /** Incoming MESSAGE request message. */ - get request() { - return this.incomingMessageRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingMessageRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingMessageRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 116 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; }); -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -class Notification { - /** @internal */ - constructor(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - /** Incoming NOTIFY request message. */ - get request() { - return this.incomingNotifyRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 117 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return Referral; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -class Referral { - /** @internal */ - constructor(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - get referTo() { - const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof _core__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - } - get referredBy() { - return this.incomingReferRequest.message.getHeader("referred-by"); - } - get replaces() { - return this.referTo.uri.getHeader("replaces"); - } - /** Incoming REFER request message. */ - get request() { - return this.incomingReferRequest.message; - } - /** Accept the request. */ - accept(options = { statusCode: 202 }) { - this.incomingReferRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - } - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - makeInviter(options) { - if (this.inviter) { - return this.inviter; - } - const targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - const extraHeaders = (options.extraHeaders || []).slice(); - const replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - const referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent._makeInviter(targetURI, options); - this.inviter._referred = this.session; - this.session._referral = this.inviter; - return this.inviter; - } -} - - -/***/ }), -/* 118 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); -/** - * {@link Session} state. - * - * @remarks - * The {@link Session} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ___________________________________________________________ - * | ____________________________________________ | - * | | ____________________________ | | - * Session | | | v v v - * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated - * | |___________________________^ ^ - * |_______________________________________________| - * ``` - * @public - */ -var SessionState; -(function (SessionState) { - /** - * If `Inviter`, INVITE not sent yet. - * If `Invitation`, received INVITE (but no final response sent yet). - */ - SessionState["Initial"] = "Initial"; - /** - * If `Inviter`, sent INVITE and waiting for a final response. - * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). - */ - SessionState["Establishing"] = "Establishing"; - /** - * If `Inviter`, sent INVITE and received 200 final response and sent ACK. - * If `Invitation`, received INVITE and sent 200 final response. - */ - SessionState["Established"] = "Established"; - /** - * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). - * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE - * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). - */ - SessionState["Terminating"] = "Terminating"; - /** - * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). - * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). - */ - SessionState["Terminated"] = "Terminated"; -})(SessionState || (SessionState = {})); - - -/***/ }), -/* 119 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return SIPExtension; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return UserAgentRegisteredOptionTags; }); -/** - * SIP extension support level. - * @public - */ -var SIPExtension; -(function (SIPExtension) { - SIPExtension["Required"] = "Required"; - SIPExtension["Supported"] = "Supported"; - SIPExtension["Unsupported"] = "Unsupported"; -})(SIPExtension || (SIPExtension = {})); -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -const UserAgentRegisteredOptionTags = { - "100rel": true, - "199": true, - answermode: true, - "early-session": true, - eventlist: true, - explicitsub: true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - gin: true, - gruu: true, - histinfo: true, - ice: true, - join: true, - "multiple-refer": true, - norefersub: true, - nosub: true, - outbound: true, - path: true, - policy: true, - precondition: true, - pref: true, - privacy: true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - replaces: true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - tdialog: true, - timer: true, - uui: true // RFC 7433 -}; - - -/***/ }), -/* 120 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 121 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 122 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 123 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return Inviter; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(114); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(118); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(119); - - - - - -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -class Inviter extends _session__WEBPACK_IMPORTED_MODULE_2__["Session"] { - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - constructor(userAgent, targetURI, options = {}) { - super(userAgent, options); - /** True if dispose() has been called. */ - this.disposed = false; - /** True if early media use is enabled. */ - this.earlyMedia = false; - /** The early media session description handlers. */ - this.earlyMediaSessionDescriptionHandlers = new Map(); - /** True if cancel() was called. */ - this.isCanceled = false; - /** True if initial INVITE without SDP. */ - this.inviteWithoutSdp = false; - this.logger = userAgent.getLogger("sip.Inviter"); - // Early media - this.earlyMedia = options.earlyMedia !== undefined ? options.earlyMedia : this.earlyMedia; - // From tag - this.fromTag = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["newTag"])(); - // Invite without SDP - this.inviteWithoutSdp = options.inviteWithoutSdp !== undefined ? options.inviteWithoutSdp : this.inviteWithoutSdp; - // Inviter options (could do better copying these options) - const inviterOptions = Object.assign({}, options); - inviterOptions.params = Object.assign({}, options.params); - // Anonymous call - const anonymous = options.anonymous || false; - // Contact - const contact = userAgent.contact.toString({ - anonymous, - // Do not add ;ob in initial forming dialog requests if the - // registration over the current connection got a GRUU URI. - outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu - }); - // FIXME: TODO: We should not be parsing URIs here as if it fails we have to throw an exception - // which is not something we want our constructor to do. URIs should be passed in as params. - // URIs - if (anonymous && userAgent.configuration.uri) { - inviterOptions.params.fromDisplayName = "Anonymous"; - inviterOptions.params.fromUri = "sip:anonymous@anonymous.invalid"; - } - let fromURI = userAgent.userAgentCore.configuration.aor; - if (inviterOptions.params.fromUri) { - fromURI = - typeof inviterOptions.params.fromUri === "string" - ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.fromUri) - : inviterOptions.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + inviterOptions.params.fromUri); - } - let toURI = targetURI; - if (inviterOptions.params.toUri) { - toURI = - typeof inviterOptions.params.toUri === "string" - ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.toUri) - : inviterOptions.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + inviterOptions.params.toUri); - } - // Params - const messageOptions = Object.assign({}, inviterOptions.params); - messageOptions.fromTag = this.fromTag; - // Extra headers - const extraHeaders = (inviterOptions.extraHeaders || []).slice(); - if (anonymous && userAgent.configuration.uri) { - extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - if (userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { - extraHeaders.push("Require: 100rel"); - } - if (userAgent.configuration.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { - extraHeaders.push("Require: replaces"); - } - inviterOptions.extraHeaders = extraHeaders; - // Body - const body = undefined; - // Make initial outgoing request message - this.outgoingRequestMessage = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, targetURI, fromURI, toURI, messageOptions, extraHeaders, body); - // Session parent properties - this._contact = contact; - this._referralInviterOptions = inviterOptions; - this._renderbody = options.renderbody; - this._rendertype = options.rendertype; - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // Modifiers and options for re-INVITE transactions - if (options.sessionDescriptionHandlerModifiersReInvite) { - this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiersReInvite; - } - if (options.sessionDescriptionHandlerOptionsReInvite) { - this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptionsReInvite; - } - // Identifier - this._id = this.outgoingRequestMessage.callId + this.fromTag; - // Add to the user agent's session collection. - this.userAgent._sessions[this._id] = this; - } - /** - * Destructor. - */ - dispose() { - // Only run through this once. It can and does get called multiple times - // depending on the what the sessions state is when first called. - // For example, if called when "establishing" it will be called again - // at least once when the session transitions to "terminated". - // Regardless, running through this more than once is pointless. - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - // Dispose of early dialog media - this.disposeEarlyMedia(); - // If the final response for the initial INVITE not yet been received, cancel it - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial: - return this.cancel().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing: - return this.cancel().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated: - return super.dispose(); - default: - throw new Error("Unknown state."); - } - } - /** - * Initial outgoing INVITE request message body. - */ - get body() { - return this.outgoingRequestMessage.body; - } - /** - * The identity of the local user. - */ - get localIdentity() { - return this.outgoingRequestMessage.from; - } - /** - * The identity of the remote user. - */ - get remoteIdentity() { - return this.outgoingRequestMessage.to; - } - /** - * Initial outgoing INVITE request message. - */ - get request() { - return this.outgoingRequestMessage; - } - /** - * Cancels the INVITE request. - * - * @remarks - * Sends a CANCEL request. - * Resolves once the response sent, otherwise rejects. - * - * After sending a CANCEL request the expectation is that a 487 final response - * will be received for the INVITE. However a 200 final response to the INVITE - * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before - * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect - * is that this method will terminate the session regardless of the race. - * @param options - Options bucket. - */ - cancel(options = {}) { - this.logger.log("Inviter.cancel"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // flag canceled - this.isCanceled = true; - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating); - // helper function - function getCancelReason(code, reason) { - if ((code && code < 200) || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - const cause = code; - const text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code) || reason; - return "SIP;cause=" + cause + ';text="' + text + '"'; - } - } - if (this.outgoingInviteRequest) { - // the CANCEL may not be respected by peer(s), so don't transition to terminated - let cancelReason; - if (options.statusCode && options.reasonPhrase) { - cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); - } - this.outgoingInviteRequest.cancel(cancelReason, options); - } - else { - this.logger.warn("Canceled session before INVITE was sent"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - } - return Promise.resolve(); - } - /** - * Sends the INVITE request. - * - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behavior may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behavior of the SIP - * servers being utilized is configured to disallow forking. - */ - invite(options = {}) { - this.logger.log("Inviter.invite"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial) { - // re-invite - return super.invite(options); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // just send an INVITE with no sdp... - if (options.withoutSdp || this.inviteWithoutSdp) { - if (this._renderbody && this._rendertype) { - this.outgoingRequestMessage.body = { contentType: this._rendertype, body: this._renderbody }; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); - return Promise.resolve(this.sendInvite(options)); - } - // get an offer and send it in an INVITE - const offerOptions = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.getOffer(offerOptions) - .then((body) => { - this.outgoingRequestMessage.body = { body: body.content, contentType: body.contentType }; - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); - return this.sendInvite(options); - }) - .catch((error) => { - this.logger.log(error.message); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - sendInvite(options = {}) { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - //// - //// - // TODO: The Offer/Answer Model Implementation - // - // Currently if `earlyMedia` is enabled and the INVITE request forks, - // the session is terminated if the early dialog does not match the - // confirmed dialog. This restriction make sense in a WebRTC environment, - // but there are other environments where this restriction does not hold. - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we propose doing the following... - // - // OPTION 1 - // - add a `earlyMediaForking` option and - // - require SDH.setDescription() to be callable multiple times. - // - // OPTION 2 - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.userAgent.userAgentCore.invite(this.outgoingRequestMessage, { - onAccept: (inviteResponse) => { - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this additional confirmed session. - if (this.dialog) { - this.logger.log("Additional confirmed dialog, sending ACK and BYE"); - this.ackAndBye(inviteResponse); - // We do NOT transition state in this case (this is an "extra" dialog) - return; - } - // If the user requested cancellation, ack & bye this session. - if (this.isCanceled) { - this.logger.log("Canceled session accepted, sending ACK and BYE"); - this.ackAndBye(inviteResponse); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return; - } - this.notifyReferer(inviteResponse); - this.onAccept(inviteResponse) - .then(() => { - this.disposeEarlyMedia(); - }) - .catch(() => { - this.disposeEarlyMedia(); - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(inviteResponse); - } - }); - }, - onProgress: (inviteResponse) => { - // If the user requested cancellation, ignore response. - if (this.isCanceled) { - return; - } - this.notifyReferer(inviteResponse); - this.onProgress(inviteResponse) - .catch(() => { - this.disposeEarlyMedia(); - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(inviteResponse); - } - }); - }, - onRedirect: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onRedirect(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(inviteResponse); - } - }, - onReject: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onReject(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(inviteResponse); - } - }, - onTrying: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onTrying(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(inviteResponse); - } - } - }); - return this.outgoingInviteRequest; - } - disposeEarlyMedia() { - this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { - sessionDescriptionHandler.close(); - }); - this.earlyMediaSessionDescriptionHandlers.clear(); - } - notifyReferer(response) { - if (!this._referred) { - return; - } - if (!(this._referred instanceof _session__WEBPACK_IMPORTED_MODULE_2__["Session"])) { - throw new Error("Referred session not instance of session"); - } - if (!this._referred.dialog) { - return; - } - if (!response.message.statusCode) { - throw new Error("Status code undefined."); - } - if (!response.message.reasonPhrase) { - throw new Error("Reason phrase undefined."); - } - const statusCode = response.message.statusCode; - const reasonPhrase = response.message.reasonPhrase; - const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); - const outgoingNotifyRequest = this._referred.dialog.notify(undefined, { - extraHeaders: ["Event: refer", "Subscription-State: terminated"], - body: { - contentDisposition: "render", - contentType: "message/sipfrag", - content: body - } - }); - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - // If the notify is rejected, stop sending NOTIFY requests. - outgoingNotifyRequest.delegate = { - onReject: () => { - this._referred = undefined; - } - }; - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - onAccept(inviteResponse) { - this.logger.log("Inviter.onAccept"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - this.logger.error(`Accept received while in state ${this.state}, dropping response`); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const response = inviteResponse.message; - const session = inviteResponse.session; - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - session.delegate = { - onAck: (ackRequest) => this.onAckRequest(ackRequest), - onBye: (byeRequest) => this.onByeRequest(byeRequest), - onInfo: (infoRequest) => this.onInfoRequest(infoRequest), - onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), - onMessage: (messageRequest) => this.onMessageRequest(messageRequest), - onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), - onPrack: (prackRequest) => this.onPrackRequest(prackRequest), - onRefer: (referRequest) => this.onReferRequest(referRequest) - }; - this._dialog = session; - switch (session.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - // INVITE without offer, so MUST have offer at this point, so invalid state. - this.logger.error("Received 2xx response to INVITE without a session description"); - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return Promise.reject(new Error("Bad Media Description")); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // INVITE with offer, so MUST have answer at this point, so invalid state. - this.logger.error("Received 2xx response to INVITE without a session description"); - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return Promise.reject(new Error("Bad Media Description")); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: { - // INVITE without offer, received offer in 2xx, so MUST send answer in ACK. - if (!this._dialog.offer) { - throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setOfferAndGetAnswer(this._dialog.offer, options) - .then((body) => { - inviteResponse.ack({ body }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - }) - .catch((error) => { - this.ackAndBye(inviteResponse, 488, "Invalid session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { - // If INVITE without offer and we have already completed the initial exchange. - if (this.earlyMediaSessionDescriptionHandlers.size > 0) { - const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!sdh) { - throw new Error("Session description handler undefined."); - } - this.setSessionDescriptionHandler(sdh); - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - inviteResponse.ack(); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - return Promise.resolve(); - } - // If INVITE with offer and we used an "early" answer in a provisional response for media - if (this.earlyMediaDialog) { - // If early media dialog doesn't match confirmed dialog, we must unfortunately fail. - // This limitation stems from how WebRTC currently implements its offer/answer model. - // There are details elsewhere, but in short a WebRTC offer cannot be forked. - if (this.earlyMediaDialog !== session) { - if (this.earlyMedia) { - const message = "You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests " + - "do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly " + - "the end point which accepted the INVITE (confirmed dialog) does not match the end point with " + - "which early media has been setup (early dialog) and thus this session is unable to proceed. " + - "In accordance with the SIP specifications, the SIP servers your end point is connected to " + - "determine if an INVITE forks and the forking behavior of those servers cannot be controlled " + - "by this library. If you wish to use early media with this library you must configure those " + - "servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow " + - "this library to function with any INVITE requests which do fork."; - this.logger.error(message); - } - const error = new Error("Early media dialog does not equal confirmed dialog, terminating session"); - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return Promise.reject(error); - } - // Otherwise we are good to go. - inviteResponse.ack(); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - return Promise.resolve(); - } - // If INVITE with offer and we have been waiting till now to apply the answer. - const answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setAnswer(answer, options) - .then(() => { - // This session has completed an initial offer/answer exchange... - let ackOptions; - if (this._renderbody && this._rendertype) { - ackOptions = { - body: { contentDisposition: "render", contentType: this._rendertype, content: this._renderbody } - }; - } - inviteResponse.ack(ackOptions); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - }) - .catch((error) => { - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - } - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - onProgress(inviteResponse) { - var _a; - this.logger.log("Inviter.onProgress"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - this.logger.error(`Progress received while in state ${this.state}, dropping response`); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - const response = inviteResponse.message; - const session = inviteResponse.session; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - const requireHeader = response.getHeader("require"); - const rseqHeader = response.getHeader("rseq"); - const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - const responseReliable = !!rseq; - const extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - switch (session.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - // INVITE without offer and session still has no offer (and no answer). - if (responseReliable) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders }); - } - return Promise.resolve(); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // INVITE with offer and session only has that initial local offer. - if (responseReliable) { - inviteResponse.prack({ extraHeaders }); - } - return Promise.resolve(); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: - if (!responseReliable) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return Promise.resolve(); - } - { - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { - this.delegate.onSessionDescriptionHandler(sdh, true); - } - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); - return sdh - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers) - .then(() => sdh.getDescription(this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers)) - .then((description) => { - const body = { - contentDisposition: "session", - contentType: description.contentType, - content: description.body - }; - inviteResponse.prack({ extraHeaders, body }); - }) - .catch((error) => { - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (responseReliable) { - inviteResponse.prack({ extraHeaders }); - } - if (this.earlyMedia && !this.earlyMediaDialog) { - this.earlyMediaDialog = session; - const answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setAnswer(answer, options).catch((error) => { - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - return Promise.resolve(); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect(inviteResponse) { - this.logger.log("Inviter.onRedirect"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { - this.logger.error(`Redirect received while in state ${this.state}, dropping response`); - return; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onReject(inviteResponse) { - this.logger.log("Inviter.onReject"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { - this.logger.error(`Reject received while in state ${this.state}, dropping response`); - return; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTrying(inviteResponse) { - this.logger.log("Inviter.onTrying"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - this.logger.error(`Trying received while in state ${this.state}, dropping response`); - return; - } - } -} - - -/***/ }), -/* 124 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 125 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 126 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return Messager; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -class Messager { - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - constructor(userAgent, targetURI, content, contentType = "text/plain", options = {}) { - // Logger - this.logger = userAgent.getLogger("sip.Messager"); - // Default options params - options.params = options.params || {}; - // URIs - let fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - typeof options.params.fromUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.fromUri) : options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - let toURI = targetURI; - if (options.params.toUri) { - toURI = typeof options.params.toUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.toUri) : options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Message params - const params = options.params ? Object.assign({}, options.params) : {}; - // Extra headers - const extraHeaders = (options.extraHeaders || []).slice(); - // Body - const contentDisposition = "render"; - const body = { - contentDisposition, - contentType, - content - }; - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); - // User agent - this.userAgent = userAgent; - } - /** - * Send the message. - */ - message(options = {}) { - this.userAgent.userAgentCore.request(this.request, options.requestDelegate); - return Promise.resolve(); - } -} - - -/***/ }), -/* 127 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 128 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 129 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return PublisherState; }); -/** - * {@link Publisher} state. - * @remarks - * The {@link Publisher} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Publisher | | v v - * Constructed -> Initial -> Published -> Unpublished -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -var PublisherState; -(function (PublisherState) { - PublisherState["Initial"] = "Initial"; - PublisherState["Published"] = "Published"; - PublisherState["Unpublished"] = "Unpublished"; - PublisherState["Terminated"] = "Terminated"; -})(PublisherState || (PublisherState = {})); - - -/***/ }), -/* 130 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 131 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return Publisher; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); -/* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(129); - - - -/** - * A publisher publishes a publication (outgoing PUBLISH). - * @public - */ -class Publisher { - /** - * Constructs a new instance of the `Publisher` class. - * - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - constructor(userAgent, targetURI, eventType, options = {}) { - this.disposed = false; - /** The publication state. */ - this._state = _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial; - // state emitter - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); - this.userAgent = userAgent; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = options.contentType || "text/plain"; - if (typeof options.expires !== "number" || options.expires % 1 !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof options.unpublishOnClose !== "boolean") { - options.unpublishOnClose = true; - } - this.target = targetURI; - this.event = eventType; - this.options = options; - this.pubRequestExpires = options.expires; - this.logger = userAgent.getLogger("sip.Publisher"); - const params = options.params || {}; - const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; - const toURI = params.toUri ? params.toUri : targetURI; - let body; - if (options.body && options.contentType) { - const contentDisposition = "render"; - const contentType = options.contentType; - const content = options.body; - body = { - contentDisposition, - contentType, - content - }; - } - const extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); - // Identifier - this.id = this.target.toString() + ":" + this.event; - // Add to the user agent's publisher collection. - this.userAgent._publishers[this.id] = this; - } - /** - * Destructor. - */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's publisher collection - delete this.userAgent._publishers[this.id]; - // Send unpublish, if requested - if (this.options.unpublishOnClose && this.state === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published) { - return this.unpublish(); - } - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - return Promise.resolve(); - } - /** The publication state. */ - get state() { - return this._state; - } - /** Emits when the publisher state changes. */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * Publish. - * @param content - Body to publish - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - publish(content, options = {}) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Initial or Modify request - this.options.body = content; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - if (this.options.expires === undefined) { - throw new Error("Expires undefined."); - } - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - this.sendPublishRequest(); - return Promise.resolve(); - } - /** - * Unpublish. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - unpublish(options = {}) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - return Promise.resolve(); - } - /** @internal */ - receiveResponse(response) { - const statusCode = response.statusCode || 0; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - const expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(() => this.refreshRequest(), this.pubRequestExpires * 900); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published); - } - else { - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - if (this.options.body === undefined) { - throw new Error("Body undefined."); - } - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - const minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - if (this.options.body === undefined) { - throw new Error("Body undefined."); - } - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - } - break; - default: - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - } - /** @internal */ - send() { - return this.userAgent.userAgentCore.publish(this.request, { - onAccept: (response) => this.receiveResponse(response.message), - onProgress: (response) => this.receiveResponse(response.message), - onRedirect: (response) => this.receiveResponse(response.message), - onReject: (response) => this.receiveResponse(response.message), - onTrying: (response) => this.receiveResponse(response.message) - }); - } - refreshRequest() { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - throw new Error("Etag undefined"); - } - if (this.pubRequestExpires === 0) { - throw new Error("Expires zero"); - } - this.sendPublishRequest(); - } - sendPublishRequest() { - const reqOptions = Object.assign({}, this.options); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - const ruri = this.target; - const params = this.options.params || {}; - let bodyAndContentType; - if (this.pubRequestBody !== undefined) { - if (this.options.contentType === undefined) { - throw new Error("Content type undefined."); - } - bodyAndContentType = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - let body; - if (bodyAndContentType) { - body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType); - } - this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - return this.send(); - } - /** - * Transition publication state. - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial: - if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && - newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && - newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - invalidTransition(); - } - break; - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published: - if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - invalidTransition(); - } - break; - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished: - if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - invalidTransition(); - } - break; - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Publication transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - this.dispose(); - } - } -} - - -/***/ }), -/* 132 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 133 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 134 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return RegistererState; }); -/** - * {@link Registerer} state. - * @remarks - * The {@link Registerer} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Registerer | | v v - * Constructed -> Initial -> Registered -> Unregistered -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -var RegistererState; -(function (RegistererState) { - RegistererState["Initial"] = "Initial"; - RegistererState["Registered"] = "Registered"; - RegistererState["Unregistered"] = "Unregistered"; - RegistererState["Terminated"] = "Terminated"; -})(RegistererState || (RegistererState = {})); - - -/***/ }), -/* 135 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 136 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return Registerer; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(134); - - - - -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -class Registerer { - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - constructor(userAgent, options = {}) { - this.disposed = false; - /** The contacts returned from the most recent accepted REGISTER request. */ - this._contacts = []; - /** The number of seconds to wait before retrying to register. */ - this._retryAfter = undefined; - /** The registration state. */ - this._state = _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial; - /** True is waiting for final response to outstanding REGISTER request. */ - this._waiting = false; - // state emitter - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); - // waiting emitter - this._waitingEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); - // Set user agent - this.userAgent = userAgent; - // Default registrar is domain portion of user agent uri - const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); - defaultUserAgentRegistrar.user = undefined; - // Initialize configuration - this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions()), { registrar: defaultUserAgentRegistrar }), Registerer.stripUndefinedProperties(options)); - // Make sure we are not using references to array options - this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); - this.options.extraHeaders = (this.options.extraHeaders || []).slice(); - // Make sure we are not using references to registrar uri - if (!this.options.registrar) { - throw new Error("Registrar undefined."); - } - this.options.registrar = this.options.registrar.clone(); - // Set instanceId and regId conditional defaults and validate - if (this.options.regId && !this.options.instanceId) { - this.options.instanceId = Registerer.newUUID(); - } - else if (!this.options.regId && this.options.instanceId) { - this.options.regId = 1; - } - if (this.options.instanceId && _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(this.options.instanceId, "uuid") === -1) { - throw new Error("Invalid instanceId."); - } - if (this.options.regId && this.options.regId < 0) { - throw new Error("Invalid regId."); - } - const registrar = this.options.registrar; - const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; - const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; - const params = this.options.params || {}; - const extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); - // Registration expires - this.expires = this.options.expires || Registerer.defaultExpires; - if (this.expires < 0) { - throw new Error("Invalid expires."); - } - // initialize logger - this.logger = userAgent.getLogger("sip.Registerer"); - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - Object.keys(this.options).forEach((key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value = this.options[key]; - switch (key) { - case "registrar": - this.logger.log("· " + key + ": " + value); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - }); - } - // Identifier - this.id = this.request.callId + this.request.from.parameters.tag; - // Add to the user agent's session collection. - this.userAgent._registerers[this.id] = this; - } - /** Default registerer options. */ - static defaultOptions() { - return { - expires: Registerer.defaultExpires, - extraContactHeaderParams: [], - extraHeaders: [], - logConfiguration: true, - instanceId: "", - params: {}, - regId: 0, - registrar: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid") - }; - } - // http://stackoverflow.com/users/109538/broofa - static newUUID() { - const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = Math.floor(Math.random() * 16); - const v = c === "x" ? r : (r % 4) + 8; - return v.toString(16); - }); - return UUID; - } - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - static stripUndefinedProperties(options) { - return Object.keys(options).reduce((object, key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (options[key] !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object[key] = options[key]; - } - return object; - }, {}); - } - /** The registered contacts. */ - get contacts() { - return this._contacts.slice(); - } - /** - * The number of seconds to wait before retrying to register. - * @defaultValue `undefined` - * @remarks - * When the server rejects a registration request, if it provides a suggested - * duration to wait before retrying, that value is available here when and if - * the state transitions to `Unsubscribed`. It is also available during the - * callback to `onReject` after a call to `register`. (Note that if the state - * if already `Unsubscribed`, a rejected request created by `register` will - * not cause the state to transition to `Unsubscribed`. One way to avoid this - * case is to dispose of `Registerer` when unregistered and create a new - * `Registerer` for any attempts to retry registering.) - * @example - * ```ts - * // Checking for retry after on state change - * registerer.stateChange.addListener((newState) => { - * switch (newState) { - * case RegistererState.Unregistered: - * const retryAfter = registerer.retryAfter; - * break; - * } - * }); - * - * // Checking for retry after on request rejection - * registerer.register({ - * requestDelegate: { - * onReject: () => { - * const retryAfter = registerer.retryAfter; - * } - * } - * }); - * ``` - */ - get retryAfter() { - return this._retryAfter; - } - /** The registration state. */ - get state() { - return this._state; - } - /** Emits when the registerer state changes. */ - get stateChange() { - return this._stateEventEmitter; - } - /** Destructor. */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's registerer collection - delete this.userAgent._registerers[this.id]; - // If registered, unregisters and resolves after final response received. - return new Promise((resolve) => { - const doClose = () => { - // If we are registered, unregister and resolve after our state changes - if (!this.waiting && this._state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { - this.stateChange.addListener(() => { - this.terminated(); - resolve(); - }, { once: true }); - this.unregister(); - return; - } - // Otherwise just resolve - this.terminated(); - resolve(); - }; - // If we are waiting for an outstanding request, wait for it to finish and then try closing. - // Otherwise just try closing. - if (this.waiting) { - this.waitingChange.addListener(() => { - doClose(); - }, { once: true }); - } - else { - doClose(); - } - }); - } - /** - * Sends the REGISTER request. - * @remarks - * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - register(options = {}) { - if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.stateError(); - throw new Error("Registerer terminated. Unable to register."); - } - if (this.disposed) { - this.stateError(); - throw new Error("Registerer disposed. Unable to register."); - } - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - this.waitingWarning(); - const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); - return Promise.reject(error); - } - // Options - if (options.requestOptions) { - this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); - } - // Extra headers - const extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.waitingToggle(true); - const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: (response) => { - let expires; - // FIXME: This does NOT appear to be to spec and should be removed. - // I haven't found anywhere that an Expires header may be used in a response. - if (response.message.hasHeader("expires")) { - expires = Number(response.message.getHeader("expires")); - } - // 8. The registrar returns a 200 (OK) response. The response MUST - // contain Contact header field values enumerating all current - // bindings. Each Contact value MUST feature an "expires" - // parameter indicating its expiration interval chosen by the - // registrar. The response SHOULD include a Date header field. - // https://tools.ietf.org/html/rfc3261#section-10.3 - this._contacts = response.message.getHeaders("contact"); - let contacts = this._contacts.length; - if (!contacts) { - this.logger.error("No Contact header in response to REGISTER, dropping response."); - this.unregistered(); - return; - } - // The 200 (OK) response from the registrar contains a list of Contact - // fields enumerating all current bindings. The UA compares each - // contact address to see if it created the contact address, using - // comparison rules in Section 19.1.4. If so, it updates the expiration - // time interval according to the expires parameter or, if absent, the - // Expires field value. The UA then issues a REGISTER request for each - // of its bindings before the expiration interval has elapsed. - // https://tools.ietf.org/html/rfc3261#section-10.2.4 - let contact; - while (contacts--) { - contact = response.message.parseHeader("contact", contacts); - if (!contact) { - throw new Error("Contact undefined"); - } - if (contact.uri.user === this.userAgent.contact.uri.user) { - expires = Number(contact.getParam("expires")); - break; - } - contact = undefined; - } - // There must be a matching contact. - if (contact === undefined) { - this.logger.error("No Contact header pointing to us, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // The contact must have an expires. - if (expires === undefined) { - this.logger.error("Contact pointing to us is missing expires parameter, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // Save gruu values - if (contact.hasParam("temp-gruu")) { - const gruu = contact.getParam("temp-gruu"); - if (gruu) { - this.userAgent.contact.tempGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); - } - } - if (contact.hasParam("pub-gruu")) { - const gruu = contact.getParam("pub-gruu"); - if (gruu) { - this.userAgent.contact.pubGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); - } - } - this.registered(expires); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - this.waitingToggle(false); - }, - onProgress: (response) => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: (response) => { - this.logger.error("Redirect received. Not supported."); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - this.waitingToggle(false); - }, - onReject: (response) => { - if (response.message.statusCode === 423) { - // If a UA receives a 423 (Interval Too Brief) response, it MAY retry - // the registration after making the expiration interval of all contact - // addresses in the REGISTER request equal to or greater than the - // expiration interval within the Min-Expires header field of the 423 - // (Interval Too Brief) response. - // https://tools.ietf.org/html/rfc3261#section-10.2.8 - // - // The registrar MAY choose an expiration less than the requested - // expiration interval. If and only if the requested expiration - // interval is greater than zero AND smaller than one hour AND - // less than a registrar-configured minimum, the registrar MAY - // reject the registration with a response of 423 (Interval Too - // Brief). This response MUST contain a Min-Expires header field - // that states the minimum expiration interval the registrar is - // willing to honor. It then skips the remaining steps. - // https://tools.ietf.org/html/rfc3261#section-10.3 - if (!response.message.hasHeader("min-expires")) { - // This response MUST contain a Min-Expires header field - this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // Increase our registration interval to the suggested minimum - this.expires = Number(response.message.getHeader("min-expires")); - // Attempt the registration again immediately - this.waitingToggle(false); - this.register(); - return; - } - this.logger.warn(`Failed to register, status code ${response.message.statusCode}`); - // The Retry-After header field can be used with a 500 (Server Internal - // Error) or 503 (Service Unavailable) response to indicate how long the - // service is expected to be unavailable to the requesting client... - // https://tools.ietf.org/html/rfc3261#section-20.33 - let retryAfterDuration = NaN; - if (response.message.statusCode === 500 || response.message.statusCode === 503) { - const header = response.message.getHeader("retry-after"); - if (header) { - retryAfterDuration = Number.parseInt(header, undefined); - } - } - // Set for the state change (if any) and the delegate callback (if any) - this._retryAfter = isNaN(retryAfterDuration) ? undefined : retryAfterDuration; - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - this._retryAfter = undefined; - this.waitingToggle(false); - }, - onTrying: (response) => { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return Promise.resolve(outgoingRegisterRequest); - } - /** - * Sends the REGISTER request with expires equal to zero. - * @remarks - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - unregister(options = {}) { - if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.stateError(); - throw new Error("Registerer terminated. Unable to register."); - } - if (this.disposed) { - if (this.state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { - // allows unregister while disposing and registered - this.stateError(); - throw new Error("Registerer disposed. Unable to register."); - } - } - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - this.waitingWarning(); - const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); - return Promise.reject(error); - } - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && !options.all) { - this.logger.warn("Not currently registered, but sending an unregister anyway."); - } - // Extra headers - const extraHeaders = ((options.requestOptions && options.requestOptions.extraHeaders) || []).slice(); - this.request.extraHeaders = extraHeaders; - // Registrations are soft state and expire unless refreshed, but can - // also be explicitly removed. A client can attempt to influence the - // expiration interval selected by the registrar as described in Section - // 10.2.1. A UA requests the immediate removal of a binding by - // specifying an expiration interval of "0" for that contact address in - // a REGISTER request. UAs SHOULD support this mechanism so that - // bindings can be removed before their expiration interval has passed. - // - // The REGISTER-specific Contact header field value of "*" applies to - // all registrations, but it MUST NOT be used unless the Expires header - // field is present with a value of "0". - // https://tools.ietf.org/html/rfc3261#section-10.2.2 - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - // Pre-emptive clear the registration timer to avoid a race condition where - // this timer fires while waiting for a final response to the unsubscribe. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - this.waitingToggle(true); - const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: (response) => { - this._contacts = response.message.getHeaders("contact"); // Update contacts - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - this.waitingToggle(false); - }, - onProgress: (response) => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: (response) => { - this.logger.error("Unregister redirected. Not currently supported."); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - this.waitingToggle(false); - }, - onReject: (response) => { - this.logger.error(`Unregister rejected with status code ${response.message.statusCode}`); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - this.waitingToggle(false); - }, - onTrying: (response) => { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return Promise.resolve(outgoingRegisterRequest); - } - /** - * Clear registration timers. - */ - clearTimers() { - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - } - /** - * Generate Contact Header - */ - generateContactHeader(expires) { - let contact = this.userAgent.contact.toString(); - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach((header) => { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - } - /** - * Helper function, called when registered. - */ - registered(expires) { - this.clearTimers(); - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - this.registrationTimer = setTimeout(() => { - this.registrationTimer = undefined; - this.register(); - }, expires * 1000 - 3000); - // We are unregistered if the registration expires. - this.registrationExpiredTimer = setTimeout(() => { - this.logger.warn("Registration expired"); - this.unregistered(); - }, expires * 1000); - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { - this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered); - } - } - /** - * Helper function, called when unregistered. - */ - unregistered() { - this.clearTimers(); - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered) { - this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered); - } - } - /** - * Helper function, called when terminated. - */ - terminated() { - this.clearTimers(); - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated); - } - } - /** - * Transition registration state. - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial: - if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && - newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && - newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - invalidTransition(); - } - break; - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered: - if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - invalidTransition(); - } - break; - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered: - if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - invalidTransition(); - } - break; - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Registration transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.dispose(); - } - } - /** True if the registerer is currently waiting for final response to a REGISTER request. */ - get waiting() { - return this._waiting; - } - /** Emits when the registerer waiting state changes. */ - get waitingChange() { - return this._waitingEventEmitter; - } - /** - * Toggle waiting. - */ - waitingToggle(waiting) { - if (this._waiting === waiting) { - throw new Error(`Invalid waiting transition from ${this._waiting} to ${waiting}`); - } - this._waiting = waiting; - this.logger.log(`Waiting toggled to ${this._waiting}`); - this._waitingEventEmitter.emit(this._waiting); - } - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - waitingWarning() { - let message = "An attempt was made to send a REGISTER request while a prior one was still in progress."; - message += " RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response"; - message += " from the registrar for the previous one or the previous REGISTER request has timed out."; - message += " Note that if the transport disconnects, you still must wait for the prior request to time out before"; - message += - " sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer."; - this.logger.warn(message); - } - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - stateError() { - const reason = this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated ? "is in 'Terminated' state" : "has been disposed"; - let message = `An attempt was made to send a REGISTER request when the Registerer ${reason}.`; - message += " The Registerer transitions to 'Terminated' when Registerer.dispose() is called."; - message += " Perhaps you called UserAgent.stop() which dipsoses of all Registerers?"; - this.logger.error(message); - } -} -Registerer.defaultExpires = 600; - - -/***/ }), -/* 137 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 138 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 139 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 140 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 141 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 142 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 143 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 144 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 145 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 146 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 147 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 148 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(82); -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(116); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(149); -/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(150); - - - - - -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.addListener((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -class Subscriber extends _subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"] { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - constructor(userAgent, targetURI, eventType, options = {}) { - super(userAgent, options); - this.body = undefined; - this.logger = userAgent.getLogger("sip.Subscriber"); - if (options.body) { - this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - this.targetURI = targetURI; - // Subscription event - this.event = eventType; - // Subscription expires - if (options.expires === undefined) { - this.expires = 3600; - } - else if (typeof options.expires !== "number") { - // pre-typescript type guard - this.logger.warn(`Option "expires" must be a number. Using default of 3600.`); - this.expires = 3600; - } - else { - this.expires = options.expires; - } - // Subscription extra headers - this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - this.subscriberRequest = this.initSubscriberRequest(); - this.outgoingRequestMessage = this.subscriberRequest.message; - // Add to UserAgent's collection - this.id = this.outgoingRequestMessage.callId + this.outgoingRequestMessage.from.parameters.tag + this.event; - this._userAgent._subscriptions[this.id] = this; - } - /** - * Destructor. - * @internal - */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's subscription collection - delete this._userAgent._subscriptions[this.id]; - // Clear timers - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - // Dispose subscriber request - this.subscriberRequest.dispose(); - // Make sure to dispose of our parent, then unsubscribe the - // subscription dialog (if need be) and resolve when it has terminated. - return super.dispose().then(() => { - // If we have never subscribed there is nothing to wait on. - // If we are already transitioned to terminated there is no need to unsubscribe again. - if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { - return; - } - if (!this._dialog) { - throw new Error("Dialog undefined."); - } - if (this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending || - this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { - const dialog = this._dialog; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - return new Promise((resolve, reject) => { - dialog.delegate = { - onTerminated: () => resolve() - }; - dialog.unsubscribe(); - }); - } - }); - } - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - subscribe(options = {}) { - switch (this.subscriberRequest.state) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: - // we can end up here when retrying so only state transition if in SubscriptionState.Initial state - if (this.state === _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Initial) { - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].NotifyWait); - } - this.subscriberRequest.subscribe().then((result) => { - if (result.success) { - if (result.success.subscription) { - this._dialog = result.success.subscription; - this._dialog.delegate = { - onNotify: (request) => this.onNotify(request), - onRefresh: (request) => this.onRefresh(request), - onTerminated: () => { - // If a call to unsubscribe will state transition to SubscriptionState.Terminated, - // but we can end up here after that if the NOTIFY never arrives and timer N fires. - if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated) { - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); - } - } - }; - } - this.onNotify(result.success.request); - } - else if (result.failure) { - this.unsubscribe(); - } - }); - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: - if (this._dialog) { - const request = this._dialog.refresh(); - request.delegate = { - onAccept: (response) => this.onAccepted(response), - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect: (response) => this.unsubscribe(), - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onReject: (response) => this.unsubscribe() - }; - } - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: - break; - default: - break; - } - return Promise.resolve(); - } - /** - * {@inheritDoc Subscription.unsubscribe} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - unsubscribe(options = {}) { - if (this.disposed) { - return Promise.resolve(); - } - switch (this.subscriberRequest.state) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: - if (this._dialog) { - this._dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: - if (this._dialog) { - this._dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: - break; - default: - throw new Error("Unknown state."); - } - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); - return Promise.resolve(); - } - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - _refresh() { - if (this.subscriberRequest.state === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { - return this.subscribe(); - } - return Promise.resolve(); - } - /** @internal */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onAccepted(response) { - // NOTE: If you think you should do something with this response, - // please make sure you understand what it is you are doing and why. - // Per the RFC, the first NOTIFY is all that actually matters. - } - /** @internal */ - onNotify(request) { - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - request.accept(); - return; - } - // State transition if needed. - if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed); - } - // Delegate notification. - if (this.delegate && this.delegate.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_2__["Notification"](request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - // If the "Subscription-State" value is SubscriptionState.Terminated, the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for SubscriptionState.Terminated -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of SubscriptionState.Terminated, and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log(`Terminated subscription with reason ${subscriptionState.reason}`); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initSubscriberRequest(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initSubscriberRequest(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(() => { - this.subscribe(); - }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.unsubscribe(); - break; - default: - break; - } - } - } - /** @internal */ - onRefresh(request) { - request.delegate = { - onAccept: (response) => this.onAccepted(response) - }; - } - initSubscriberRequest() { - const options = { - extraHeaders: this.extraHeaders, - body: this.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(this.body) : undefined - }; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.subscriberRequest = new SubscriberRequest(this._userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); - this.subscriberRequest.delegate = { - onAccept: (response) => this.onAccepted(response) - }; - return this.subscriberRequest; - } -} -class SubscriberRequest { - constructor(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.Subscriber"); - this.delegate = delegate; - const allowHeader = "Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__["AllowedMethods"].toString(); - const extraHeaders = ((options && options.extraHeaders) || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - const body = options && options.body; - this.message = core.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - dispose() { - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - this.request = undefined; - } - } - /** Subscription state. */ - get state() { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait; - } - else { - return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial; - } - } - /** - * Establish subscription. - * @param options Options bucket. - */ - subscribe() { - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise((resolve) => { - if (!this.message) { - throw new Error("Message undefined."); - } - this.request = this.core.subscribe(this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: (response) => { - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: (requestWithSubscription) => { - this.subscription = requestWithSubscription.subscription; - if (this.subscription) { - this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: () => { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: (response) => { - resolve({ failure: { response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: (response) => { - resolve({ failure: { response } }); - } - }); - }); - } -} - - -/***/ }), -/* 149 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; }); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); -/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(150); - - -/** - * A subscription provides {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -class Subscription { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - constructor(userAgent, options = {}) { - this._disposed = false; - this._state = _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial; - this._logger = userAgent.getLogger("sip.Subscription"); - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); - this._userAgent = userAgent; - this.delegate = options.delegate; - } - /** - * Destructor. - */ - dispose() { - if (this._disposed) { - return Promise.resolve(); - } - this._disposed = true; - this._stateEventEmitter.removeAllListeners(); - return Promise.resolve(); - } - /** - * The subscribed subscription dialog. - */ - get dialog() { - return this._dialog; - } - /** - * True if disposed. - * @internal - */ - get disposed() { - return this._disposed; - } - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - get state() { - return this._state; - } - /** - * Emits when the subscription `state` property changes. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** @internal */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: - if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - invalidTransition(); - } - break; - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: - if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - invalidTransition(); - } - break; - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed: - if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - invalidTransition(); - } - break; - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Guard against duplicate transition - if (this._state === newState) { - return; - } - // Transition - this._state = newState; - this._logger.log(`Subscription ${this._dialog ? this._dialog.id : undefined} transitioned to ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - this.dispose(); - } - } -} - - -/***/ }), -/* 150 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); -/** - * {@link Subscription} state. - * @remarks - * The {@link Subscription} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * _______________________________________ - * Subscription | v - * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated - * |____________________________^ - * ``` - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Subscribed"] = "Subscribed"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState || (SubscriptionState = {})); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 152 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 153 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 154 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 155 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 156 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return TransportState; }); -/** - * {@link Transport} state. - * - * @remarks - * The {@link Transport} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ______________________________ - * | ____________ | - * Transport v v | | - * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting - * ^ ^ |_____________________^ | | - * | |_____________________________| | - * |_____________________________________________| - * ``` - * @public - */ -var TransportState; -(function (TransportState) { - /** - * The `connect()` method was called. - */ - TransportState["Connecting"] = "Connecting"; - /** - * The `connect()` method resolved. - */ - TransportState["Connected"] = "Connected"; - /** - * The `disconnect()` method was called. - */ - TransportState["Disconnecting"] = "Disconnecting"; - /** - * The `connect()` method was rejected, or - * the `disconnect()` method completed, or - * network connectivity was lost. - */ - TransportState["Disconnected"] = "Disconnected"; -})(TransportState || (TransportState = {})); - - -/***/ }), -/* 157 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 158 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return UserAgentState; }); -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "Started" --> "Stopped" - * 2. "Stopped" --> "Started" - * ``` - * @public - */ -var UserAgentState; -(function (UserAgentState) { - UserAgentState["Started"] = "Started"; - UserAgentState["Stopped"] = "Stopped"; -})(UserAgentState || (UserAgentState = {})); - - -/***/ }), -/* 159 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return UserAgent; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); -/* harmony import */ var _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(108); -/* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(113); -/* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(123); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(115); -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(116); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(119); -/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(158); - - - - - - - - - - - - -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -class UserAgent { - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - constructor(options = {}) { - /** @internal */ - this._publishers = {}; - /** @internal */ - this._registerers = {}; - /** @internal */ - this._sessions = {}; - /** @internal */ - this._subscriptions = {}; - this._state = _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped; - /** Unload listener. */ - this.unloadListener = () => { - this.stop(); - }; - // state emitter - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_5__["EmitterImpl"](); - // initialize delegate - this.delegate = options.delegate; - // initialize configuration - this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions()), { sipjsId: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(5) }), { uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous." + Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(6), "anonymous.invalid") }), { viaHost: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); - // viaHost is hack - if (this.options.hackIpInContact) { - if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { - const from = 1; - const to = 254; - const octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - this.options.viaHost = "192.0.2." + octet; - } - else if (this.options.hackIpInContact) { - this.options.viaHost = this.options.hackIpInContact; - } - } - // initialize logger & logger factory - this.loggerFactory = new _core__WEBPACK_IMPORTED_MODULE_0__["LoggerFactory"](); - this.logger = this.loggerFactory.getLogger("sip.UserAgent"); - this.loggerFactory.builtinEnabled = this.options.logBuiltinEnabled; - this.loggerFactory.connector = this.options.logConnector; - switch (this.options.logLevel) { - case "error": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].error; - break; - case "warn": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn; - break; - case "log": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; - break; - case "debug": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug; - break; - default: - break; - } - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - Object.keys(this.options).forEach((key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value = this.options[key]; - switch (key) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + key + ": " + value); - break; - case "authorizationPassword": - this.logger.log("· " + key + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + key + ": " + value.name); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - }); - } - // guard deprecated transport options (remove this in version 16.x) - if (this.options.transportOptions) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const optionsDeprecated = this.options.transportOptions; - const maxReconnectionAttemptsDeprecated = optionsDeprecated.maxReconnectionAttempts; - const reconnectionTimeoutDeprecated = optionsDeprecated.reconnectionTimeout; - if (maxReconnectionAttemptsDeprecated !== undefined) { - const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (reconnectionTimeoutDeprecated !== undefined) { - const deprecatedMessage = `The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // hack - if (options.reconnectionDelay === undefined && reconnectionTimeoutDeprecated !== undefined) { - this.options.reconnectionDelay = reconnectionTimeoutDeprecated; - } - if (options.reconnectionAttempts === undefined && maxReconnectionAttemptsDeprecated !== undefined) { - this.options.reconnectionAttempts = maxReconnectionAttemptsDeprecated; - } - } - // guard deprecated user agent options (remove this in version 16.x) - if (options.reconnectionDelay !== undefined) { - const deprecatedMessage = `The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (options.reconnectionAttempts !== undefined) { - const deprecatedMessage = `The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // Initialize Transport - this._transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); - this.initTransportCallbacks(); - // Initialize Contact - this._contact = this.initContact(); - // Initialize UserAgentCore - this._userAgentCore = this.initCore(); - if (this.options.autoStart) { - this.start(); - } - } - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - static makeURI(uri) { - return _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(uri); - } - /** Default user agent options. */ - static defaultOptions() { - return { - allowLegacyNotifications: false, - authorizationHa1: "", - authorizationPassword: "", - authorizationUsername: "", - autoStart: false, - autoStop: true, - delegate: {}, - displayName: "", - forceRport: false, - hackAllowUnregisteredOptionTags: false, - hackIpInContact: false, - hackViaTcp: false, - hackWssInTransport: false, - logBuiltinEnabled: true, - logConfiguration: true, - logConnector: () => { - /* noop */ - }, - logLevel: "log", - noAnswerTimeout: 60, - preloadedRouteSet: [], - reconnectionAttempts: 0, - reconnectionDelay: 4, - sessionDescriptionHandlerFactory: Object(_platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__["defaultSessionDescriptionHandlerFactory"])(), - sessionDescriptionHandlerFactoryOptions: {}, - sipExtension100rel: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, - sipExtensionReplaces: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, - sipExtensionExtraSupported: [], - sipjsId: "", - transportConstructor: _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__["Transport"], - transportOptions: {}, - uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid"), - userAgentString: "SIP.js/" + _version__WEBPACK_IMPORTED_MODULE_4__["LIBRARY_VERSION"], - viaHost: "" - }; - } - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - static stripUndefinedProperties(options) { - return Object.keys(options).reduce((object, key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (options[key] !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object[key] = options[key]; - } - return object; - }, {}); - } - /** - * User agent configuration. - */ - get configuration() { - return this.options; - } - /** - * User agent contact. - */ - get contact() { - return this._contact; - } - /** - * User agent state. - */ - get state() { - return this._state; - } - /** - * User agent state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * User agent transport. - */ - get transport() { - return this._transport; - } - /** - * User agent core. - */ - get userAgentCore() { - return this._userAgentCore; - } - /** - * The logger. - */ - getLogger(category, label) { - return this.loggerFactory.getLogger(category, label); - } - /** - * The logger factory. - */ - getLoggerFactory() { - return this.loggerFactory; - } - /** - * True if transport is connected. - */ - isConnected() { - return this.transport.isConnected(); - } - /** - * Reconnect the transport. - */ - reconnect() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - return Promise.reject(new Error("User agent stopped.")); - } - // Make sure we don't call synchronously - return Promise.resolve().then(() => this.transport.connect()); - } - /** - * Start the user agent. - * - * @remarks - * Resolves if transport connects, otherwise rejects. - * - * @example - * ```ts - * userAgent.start() - * .then(() => { - * // userAgent.isConnected() === true - * }) - * .catch((error: Error) => { - * // userAgent.isConnected() === false - * }); - * ``` - */ - start() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { - this.logger.warn(`User agent already started`); - return Promise.resolve(); - } - this.logger.log(`Starting ${this.configuration.uri}`); - // Transition state - this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started); - // TODO: Review this as it is not clear it has any benefit and at worst causes additional load the server. - // On unload it may be best to simply in most scenarios to do nothing. Furthermore and regardless, this - // kind of behavior seems more appropriate to be managed by the consumer of the API than the API itself. - // Should this perhaps be deprecated? - // - // Add window unload event listener - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && typeof window.addEventListener === "function" && !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return this.transport.connect(); - } - /** - * Stop the user agent. - * - * @remarks - * Resolves when the user agent has completed a graceful shutdown. - * ```txt - * 1) Sessions terminate. - * 2) Registerers unregister. - * 3) Subscribers unsubscribe. - * 4) Publishers unpublish. - * 5) Transport disconnects. - * 6) User Agent Core resets. - * ``` - * NOTE: While this is a "graceful shutdown", it can also be very slow one if you - * are waiting for the returned Promise to resolve. The disposal of the clients and - * dialogs is done serially - waiting on one to finish before moving on to the next. - * This can be slow if there are lot of subscriptions to unsubscribe for example. - * - * THE SLOW PACE IS INTENTIONAL! - * While one could spin them all down in parallel, this could slam the remote server. - * It is bad practice to denial of service attack (DoS attack) servers!!! - * Moreover, production servers will automatically blacklist clients which send too - * many requests in too short a period of time - dropping any additional requests. - * - * If a different approach to disposing is needed, one can implement whatever is - * needed and execute that prior to calling `stop()`. Alternatively one may simply - * not wait for the Promise returned by `stop()` to complete. - */ - async stop() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - this.logger.warn(`User agent already stopped`); - return Promise.resolve(); - } - this.logger.log(`Stopping ${this.configuration.uri}`); - // Transition state - this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped); - // TODO: See comments with associated complimentary code in start(). Should this perhaps be deprecated? - // Remove window unload event listener - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - // Be careful here to use a local references as start() can be called - // again before we complete and we don't want to touch new clients - // and we don't want to step on the new instances (or vice versa). - const publishers = Object.assign({}, this._publishers); - const registerers = Object.assign({}, this._registerers); - const sessions = Object.assign({}, this._sessions); - const subscriptions = Object.assign({}, this._subscriptions); - const transport = this.transport; - const userAgentCore = this.userAgentCore; - // - // At this point we have completed the state transition and everything - // following will effectively run async and MUST NOT cause any issues - // if UserAgent.start() is called while the following code continues. - // - // TODO: Minor optimization. - // The disposal in all cases involves, in part, sending messages which - // is not worth doing if the transport is not connected as we know attempting - // to send messages will be futile. But none of these disposal methods check - // if that's is the case and it would be easy for them to do so at this point. - // Dispose of Registerers - this.logger.log(`Dispose of registerers`); - for (const id in registerers) { - if (registerers[id]) { - await registerers[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._registerers[id]; - throw error; - }); - } - } - // Dispose of Sessions - this.logger.log(`Dispose of sessions`); - for (const id in sessions) { - if (sessions[id]) { - await sessions[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._sessions[id]; - throw error; - }); - } - } - // Dispose of Subscriptions - this.logger.log(`Dispose of subscriptions`); - for (const id in subscriptions) { - if (subscriptions[id]) { - await subscriptions[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._subscriptions[id]; - throw error; - }); - } - } - // Dispose of Publishers - this.logger.log(`Dispose of publishers`); - for (const id in publishers) { - if (publishers[id]) { - await publishers[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._publishers[id]; - throw error; - }); - } - } - // Dispose of the transport (disconnecting) - this.logger.log(`Dispose of transport`); - await transport.dispose().catch((error) => { - this.logger.error(error.message); - throw error; - }); - // Dispose of the user agent core (resetting) - this.logger.log(`Dispose of core`); - userAgentCore.dispose(); - } - /** - * Used to avoid circular references. - * @internal - */ - _makeInviter(targetURI, options) { - return new _inviter__WEBPACK_IMPORTED_MODULE_7__["Inviter"](this, targetURI, options); - } - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - attemptReconnection(reconnectionAttempt = 1) { - const reconnectionAttempts = this.options.reconnectionAttempts; - const reconnectionDelay = this.options.reconnectionDelay; - if (reconnectionAttempt > reconnectionAttempts) { - this.logger.log(`Maximum reconnection attempts reached`); - return; - } - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); - setTimeout(() => { - this.reconnect() - .then(() => { - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); - this.attemptReconnection(++reconnectionAttempt); - }); - }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); - } - /** - * Initialize contact. - */ - initContact() { - const contactName = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(8); // FIXME: should be configurable - const contactTransport = this.options.hackWssInTransport ? "wss" : "ws"; // FIXME: clearly broken for non ws transports - const contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", contactName, this.options.viaHost, undefined, { transport: contactTransport }), - toString: (contactToStringOptions = {}) => { - const anonymous = contactToStringOptions.anonymous || false; - const outbound = contactToStringOptions.outbound || false; - let contactString = "<"; - if (anonymous) { - contactString += this.contact.tempGruu || `sip:anonymous@anonymous.invalid;transport=${contactTransport}`; - } - else { - contactString += this.contact.pubGruu || this.contact.uri; - } - if (outbound) { - contactString += ";ob"; - } - contactString += ">"; - return contactString; - } - }; - return contact; - } - /** - * Initialize user agent core. - */ - initCore() { - // supported options - let supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (this.options.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { - supportedOptionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { - supportedOptionTags.push("replaces"); - } - if (this.options.sipExtensionExtraSupported) { - supportedOptionTags.push(...this.options.sipExtensionExtraSupported); - } - if (!this.options.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter((optionTag) => _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["UserAgentRegisteredOptionTags"][optionTag]); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - // FIXME: TODO: This was ported, but this is and was just plain broken. - const supportedOptionTagsResponse = supportedOptionTags.slice(); - if (this.contact.pubGruu || this.contact.tempGruu) { - supportedOptionTagsResponse.push("gruu"); - } - // core configuration - const userAgentCoreConfiguration = { - aor: this.options.uri, - contact: this.contact, - displayName: this.options.displayName, - loggerFactory: this.loggerFactory, - hackViaTcp: this.options.hackViaTcp, - routeSet: this.options.preloadedRouteSet, - supportedOptionTags, - supportedOptionTagsResponse, - sipjsId: this.options.sipjsId, - userAgentHeaderFieldValue: this.options.userAgentString, - viaForceRport: this.options.forceRport, - viaHost: this.options.viaHost, - authenticationFactory: () => { - const username = this.options.authorizationUsername - ? this.options.authorizationUsername - : this.options.uri.user; // if authorization username not provided, use uri user as username - const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; - const ha1 = this.options.authorizationHa1 ? this.options.authorizationHa1 : undefined; - return new _core__WEBPACK_IMPORTED_MODULE_0__["DigestAuthentication"](this.getLoggerFactory(), ha1, username, password); - }, - transportAccessor: () => this.transport - }; - const userAgentCoreDelegate = { - onInvite: (incomingInviteRequest) => { - var _a; - const invitation = new _invitation__WEBPACK_IMPORTED_MODULE_6__["Invitation"](this, incomingInviteRequest); - incomingInviteRequest.delegate = { - onCancel: (cancel) => { - invitation._onCancel(cancel); - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTransportError: (error) => { - // A server transaction MUST NOT discard transaction state based only on - // encountering a non-recoverable transport error when sending a - // response. Instead, the associated INVITE server transaction state - // machine MUST remain in its current state. (Timers will eventually - // cause it to transition to the "Terminated" state). - // https://tools.ietf.org/html/rfc6026#section-7.1 - // As noted in the comment above, we are to leaving it to the transaction - // timers to eventually cause the transaction to sort itself out in the case - // of a transport failure in an invite server transaction. This delegate method - // is here simply here for completeness and to make it clear that it provides - // nothing more than informational hook into the core. That is, if you think - // you should be trying to deal with a transport error here, you are likely wrong. - this.logger.error("A transport error has occurred while handling an incoming INVITE request."); - } - }; - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - if (this.options.sipExtensionReplaces !== _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported) { - const message = incomingInviteRequest.message; - const replaces = message.parseHeader("replaces"); - if (replaces) { - const callId = replaces.call_id; - if (typeof callId !== "string") { - throw new Error("Type of call id is not string"); - } - const toTag = replaces.replaces_to_tag; - if (typeof toTag !== "string") { - throw new Error("Type of to tag is not string"); - } - const fromTag = replaces.replaces_from_tag; - if (typeof fromTag !== "string") { - throw new Error("type of from tag is not string"); - } - const targetDialogId = callId + toTag + fromTag; - const targetDialog = this.userAgentCore.dialogs.get(targetDialogId); - // If no match is found, the UAS rejects the INVITE and returns a 481 - // Call/Transaction Does Not Exist response. Likewise, if the Replaces - // header field matches a dialog which was not created with an INVITE, - // the UAS MUST reject the request with a 481 response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog) { - invitation.reject({ statusCode: 481 }); - return; - } - // If the Replaces header field matches a confirmed dialog, it checks - // for the presence of the "early-only" flag in the Replaces header - // field. (This flag allows the UAC to prevent a potentially - // undesirable race condition described in Section 7.1.) If the flag is - // present, the UA rejects the request with a 486 Busy response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog.early && replaces.early_only === true) { - invitation.reject({ statusCode: 486 }); - return; - } - // Provide a handle on the session being replaced. - const targetSession = this._sessions[callId + fromTag] || this._sessions[callId + toTag] || undefined; - if (!targetSession) { - throw new Error("Session does not exist."); - } - invitation._replacee = targetSession; - } - } - // Delegate invitation handling. - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) { - if (invitation.autoSendAnInitialProvisionalResponse) { - invitation.progress().then(() => { - var _a; - if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) === undefined) { - throw new Error("onInvite undefined."); - } - this.delegate.onInvite(invitation); - }); - return; - } - this.delegate.onInvite(invitation); - return; - } - // A common scenario occurs when the callee is currently not willing or - // able to take additional calls at this end system. A 486 (Busy Here) - // SHOULD be returned in such a scenario. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - invitation.reject({ statusCode: 486 }); - }, - onMessage: (incomingMessageRequest) => { - if (this.delegate && this.delegate.onMessage) { - const message = new _message__WEBPACK_IMPORTED_MODULE_8__["Message"](incomingMessageRequest); - this.delegate.onMessage(message); - } - else { - // Accept the MESSAGE request, but do nothing with it. - incomingMessageRequest.accept(); - } - }, - onNotify: (incomingNotifyRequest) => { - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - if (this.delegate && this.delegate.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_9__["Notification"](incomingNotifyRequest); - this.delegate.onNotify(notification); - } - else { - // Per the above which obsoletes https://tools.ietf.org/html/rfc3265, - // the use of out of dialog NOTIFY is obsolete, but... - if (this.options.allowLegacyNotifications) { - incomingNotifyRequest.accept(); // Accept the NOTIFY request, but do nothing with it. - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - } - }, - onRefer: (incomingReferRequest) => { - this.logger.warn("Received an out of dialog REFER request"); - // TOOD: this.delegate.onRefer(...) - if (this.delegate && this.delegate.onReferRequest) { - this.delegate.onReferRequest(incomingReferRequest); - } - else { - incomingReferRequest.reject({ statusCode: 405 }); - } - }, - onRegister: (incomingRegisterRequest) => { - this.logger.warn("Received an out of dialog REGISTER request"); - // TOOD: this.delegate.onRegister(...) - if (this.delegate && this.delegate.onRegisterRequest) { - this.delegate.onRegisterRequest(incomingRegisterRequest); - } - else { - incomingRegisterRequest.reject({ statusCode: 405 }); - } - }, - onSubscribe: (incomingSubscribeRequest) => { - this.logger.warn("Received an out of dialog SUBSCRIBE request"); - // TOOD: this.delegate.onSubscribe(...) - if (this.delegate && this.delegate.onSubscribeRequest) { - this.delegate.onSubscribeRequest(incomingSubscribeRequest); - } - else { - incomingSubscribeRequest.reject({ statusCode: 405 }); - } - } - }; - return new _core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"](userAgentCoreConfiguration, userAgentCoreDelegate); - } - initTransportCallbacks() { - this.transport.onConnect = () => this.onTransportConnect(); - this.transport.onDisconnect = (error) => this.onTransportDisconnect(error); - this.transport.onMessage = (message) => this.onTransportMessage(message); - } - onTransportConnect() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - return; - } - if (this.delegate && this.delegate.onConnect) { - this.delegate.onConnect(); - } - } - onTransportDisconnect(error) { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - return; - } - if (this.delegate && this.delegate.onDisconnect) { - this.delegate.onDisconnect(error); - } - // Only attempt to reconnect if network/server dropped the connection. - if (error && this.options.reconnectionAttempts > 0) { - this.attemptReconnection(); - } - } - onTransportMessage(messageString) { - const message = _core__WEBPACK_IMPORTED_MODULE_0__["Parser"].parseMessage(messageString, this.getLogger("sip.Parser")); - if (!message) { - this.logger.warn("Failed to parse incoming message. Dropping."); - return; - } - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped && message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - this.logger.warn(`Received ${message.method} request while stopped. Dropping.`); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - const hasMinimumHeaders = () => { - const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (const header of mandatoryHeaders) { - if (!message.hasHeader(header)) { - this.logger.warn(`Missing mandatory header field : ${header}.`); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn(`Request missing mandatory header field. Dropping.`); - return; - } - // FIXME: This is non-standard and should be a configurable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.options.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); - const contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Response Checks - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn(`Response missing mandatory header field. Dropping.`); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.options.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); - const contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - } - /** - * Transition state. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - transitionState(newState, error) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate state transition - switch (this._state) { - case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started: - if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - invalidTransition(); - } - break; - case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped: - if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { - invalidTransition(); - } - break; - default: - throw new Error("Unknown state."); - } - // Update state - this.logger.log(`Transitioned from ${this._state} to ${newState}`); - this._state = newState; - this._stateEventEmitter.emit(this._state); - } -} - - -/***/ }), -/* 160 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"]; }); - -/* harmony import */ var _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(162); -/* harmony import */ var _media_stream_factory__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_media_stream_factory__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__) if(["defaultMediaStreamFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(163); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__["defaultPeerConnectionConfiguration"]; }); - -/* harmony import */ var _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(164); -/* harmony import */ var _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(165); -/* harmony import */ var _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(166); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__["defaultSessionDescriptionHandlerFactory"]; }); - -/* harmony import */ var _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(168); -/* harmony import */ var _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(169); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(170); -/* harmony import */ var _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(167); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_9__["SessionDescriptionHandler"]; }); - -/** - * A SessionDescriptionHandler for web browsers. - * @packageDocumentation - */ - - - - - - - - - - - - -/***/ }), -/* 161 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return defaultMediaStreamFactory; }); -/** - * Function which returns a MediaStreamFactory. - * @public - */ -function defaultMediaStreamFactory() { - return (constraints) => { - // if no audio or video, return a media stream without tracks - if (!constraints.audio && !constraints.video) { - return Promise.resolve(new MediaStream()); - } - // getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, - // navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, - // a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. - // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Privacy_and_security - if (navigator.mediaDevices === undefined) { - return Promise.reject(new Error("Media devices not available in insecure contexts.")); - } - return navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices, constraints); - }; -} - - -/***/ }), -/* 162 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 163 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return defaultPeerConnectionConfiguration; }); -/** - * Function which returns an RTCConfiguration. - * @public - */ -function defaultPeerConnectionConfiguration() { - const configuration = { - bundlePolicy: "balanced", - certificates: undefined, - iceCandidatePoolSize: 0, - iceServers: [{ urls: "stun:stun.l.google.com:19302" }], - iceTransportPolicy: "all", - peerIdentity: undefined, - rtcpMuxPolicy: "require" - }; - return configuration; -} - - -/***/ }), -/* 164 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 165 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 166 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return defaultSessionDescriptionHandlerFactory; }); -/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); -/* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(163); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(167); - - - -/** - * Function which returns a SessionDescriptionHandlerFactory. - * @remarks - * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. - * The ICE gathering timeout defaults to 5000ms. - * @param mediaStreamFactory - MediaStream factory. - * @public - */ -function defaultSessionDescriptionHandlerFactory(mediaStreamFactory) { - return (session, options) => { - // provide a default media stream factory if need be - if (mediaStreamFactory === undefined) { - mediaStreamFactory = Object(_media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"])(); - } - // make sure we allow `0` to be passed in so timeout can be disabled - const iceGatheringTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) !== undefined ? options === null || options === void 0 ? void 0 : options.iceGatheringTimeout : 5000; - // merge passed factory options into default session description configuration - const sessionDescriptionHandlerConfiguration = { - iceGatheringTimeout, - peerConnectionConfiguration: Object.assign(Object.assign({}, Object(_peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__["defaultPeerConnectionConfiguration"])()), options === null || options === void 0 ? void 0 : options.peerConnectionConfiguration) - }; - const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler"); - return new _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"](logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration); - }; -} - - -/***/ }), -/* 167 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return SessionDescriptionHandler; }); -/** - * A base class implementing a WebRTC session description handler for sip.js. - * @remarks - * It is expected/intended to be extended by specific WebRTC based applications. - * @privateRemarks - * So do not put application specific implementation in here. - * @public - */ -class SessionDescriptionHandler { - /** - * Constructor - * @param logger - A logger - * @param mediaStreamFactory - A factory to provide a MediaStream - * @param options - Options passed from the SessionDescriptionHandleFactory - */ - constructor(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration) { - logger.debug("SessionDescriptionHandler.constructor"); - this.logger = logger; - this.mediaStreamFactory = mediaStreamFactory; - this.sessionDescriptionHandlerConfiguration = sessionDescriptionHandlerConfiguration; - this._localMediaStream = new MediaStream(); - this._remoteMediaStream = new MediaStream(); - this._peerConnection = new RTCPeerConnection(sessionDescriptionHandlerConfiguration === null || sessionDescriptionHandlerConfiguration === void 0 ? void 0 : sessionDescriptionHandlerConfiguration.peerConnectionConfiguration); - this.initPeerConnectionEventHandlers(); - } - /** - * The local media stream currently being sent. - * - * @remarks - * The local media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * local media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get localMediaStream() { - return this._localMediaStream; - } - /** - * The remote media stream currently being received. - * - * @remarks - * The remote media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * remote media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get remoteMediaStream() { - return this._remoteMediaStream; - } - /** - * The data channel. Undefined before it is created. - */ - get dataChannel() { - return this._dataChannel; - } - /** - * The peer connection. Undefined if peer connection has closed. - * - * @remarks - * While access to the underlying `RTCPeerConnection` is provided, note that - * using methods with modify it may break the operation of this class. - * In particular, this class depends on exclusive access to the - * event handler properties. If you need access to the peer connection - * events, either register for events using `addEventListener()` on - * the `RTCPeerConnection` or set the `peerConnectionDelegate` on - * this `SessionDescriptionHandler`. - */ - get peerConnection() { - return this._peerConnection; - } - /** - * A delegate which provides access to the peer connection event handlers. - * - * @remarks - * Setting the peer connection event handlers directly is not supported - * and may break this class. As this class depends on exclusive access - * to them, a delegate may be set which provides alternative access to - * the event handlers in a fashion which is supported. - */ - get peerConnectionDelegate() { - return this._peerConnectionDelegate; - } - set peerConnectionDelegate(delegate) { - this._peerConnectionDelegate = delegate; - } - // The addtrack event does not get fired when JavaScript code explicitly adds tracks to the stream (by calling addTrack()). - // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - static dispatchAddTrackEvent(stream, track) { - stream.dispatchEvent(new MediaStreamTrackEvent("addtrack", { track })); - } - // The removetrack event does not get fired when JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). - // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onremovetrack - static dispatchRemoveTrackEvent(stream, track) { - stream.dispatchEvent(new MediaStreamTrackEvent("removetrack", { track })); - } - /** - * Stop tracks and close peer connection. - */ - close() { - this.logger.debug("SessionDescriptionHandler.close"); - if (this._peerConnection === undefined) { - return; - } - this._peerConnection.getReceivers().forEach((receiver) => { - receiver.track && receiver.track.stop(); - }); - this._peerConnection.getSenders().forEach((sender) => { - sender.track && sender.track.stop(); - }); - if (this._dataChannel) { - this._dataChannel.close(); - } - this._peerConnection.close(); - this._peerConnection = undefined; - } - /** - * Creates an offer or answer. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - getDescription(options, modifiers) { - var _a, _b; - this.logger.debug("SessionDescriptionHandler.getDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // Callback on data channel creation - this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; - // ICE will restart upon applying an offer created with the iceRestart option - const iceRestart = (_a = options === null || options === void 0 ? void 0 : options.offerOptions) === null || _a === void 0 ? void 0 : _a.iceRestart; - // ICE gathering timeout may be set on a per call basis, otherwise the configured default is used - const iceTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) === undefined - ? (_b = this.sessionDescriptionHandlerConfiguration) === null || _b === void 0 ? void 0 : _b.iceGatheringTimeout : options === null || options === void 0 ? void 0 : options.iceGatheringTimeout; - return this.getLocalMediaStream(options) - .then(() => this.createDataChannel(options)) - .then(() => this.createLocalOfferOrAnswer(options)) - .then((sessionDescription) => this.applyModifiers(sessionDescription, modifiers)) - .then((sessionDescription) => this.setLocalSessionDescription(sessionDescription)) - .then(() => this.waitForIceGatheringComplete(iceRestart, iceTimeout)) - .then(() => this.getLocalSessionDescription()) - .then((sessionDescription) => { - return { - body: sessionDescription.sdp, - contentType: "application/sdp" - }; - }) - .catch((error) => { - this.logger.error("SessionDescriptionHandler.getDescription failed - " + error); - throw error; - }); - } - /** - * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. - * @param contentType - The content type that is in the SIP Message. - */ - hasDescription(contentType) { - this.logger.debug("SessionDescriptionHandler.hasDescription"); - return contentType === "application/sdp"; - } - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones - A string containing DTMF digits. - * @param options - Options object to be used by sendDtmf. - */ - sendDtmf(tones, options) { - this.logger.debug("SessionDescriptionHandler.sendDtmf"); - if (this._peerConnection === undefined) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"); - return false; - } - const senders = this._peerConnection.getSenders(); - if (senders.length === 0) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"); - return false; - } - const dtmfSender = senders[0].dtmf; - if (!dtmfSender) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"); - return false; - } - const duration = options === null || options === void 0 ? void 0 : options.duration; - const interToneGap = options === null || options === void 0 ? void 0 : options.interToneGap; - try { - dtmfSender.insertDTMF(tones, duration, interToneGap); - } - catch (e) { - this.logger.error(e); - return false; - } - this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: " + tones.toString()); - return true; - } - /** - * Sets an offer or answer. - * @param sdp - The session description. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - setDescription(sdp, options, modifiers) { - this.logger.debug("SessionDescriptionHandler.setDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // Callback on data channel creation - this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; - // SDP type - const type = this._peerConnection.signalingState === "have-local-offer" ? "answer" : "offer"; - return this.getLocalMediaStream(options) - .then(() => this.applyModifiers({ sdp, type }, modifiers)) - .then((sessionDescription) => this.setRemoteSessionDescription(sessionDescription)) - .catch((error) => { - this.logger.error("SessionDescriptionHandler.setDescription failed - " + error); - throw error; - }); - } - /** - * Applies modifiers to SDP prior to setting the local or remote description. - * @param sdp - SDP to modify. - * @param modifiers - Modifiers to apply. - */ - applyModifiers(sdp, modifiers) { - this.logger.debug("SessionDescriptionHandler.applyModifiers"); - if (!modifiers || modifiers.length === 0) { - return Promise.resolve(sdp); - } - return modifiers - .reduce((cur, next) => cur.then(next), Promise.resolve(sdp)) - .then((modified) => { - this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"); - if (!modified.sdp || !modified.type) { - throw new Error("Invalid SDP."); - } - return { sdp: modified.sdp, type: modified.type }; - }); - } - /** - * Create a data channel. - * @remarks - * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. - * Only creates a data channel if creating a local offer. - * Only if one does not already exist. - * @param options - Session description handler options. - */ - createDataChannel(options) { - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // only create a data channel if requested - if ((options === null || options === void 0 ? void 0 : options.dataChannel) !== true) { - return Promise.resolve(); - } - // do not create a data channel if we already have one - if (this._dataChannel) { - return Promise.resolve(); - } - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable, assume we are creating a local offer so create a data channel - this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel"); - try { - this._dataChannel = this._peerConnection.createDataChannel((options === null || options === void 0 ? void 0 : options.dataChannelLabel) || "", options === null || options === void 0 ? void 0 : options.dataChannelOptions); - if (this.onDataChannel) { - this.onDataChannel(this._dataChannel); - } - return Promise.resolve(); - } - catch (error) { - return Promise.reject(error); - } - case "have-remote-offer": - return Promise.resolve(); - case "have-local-offer": - case "have-local-pranswer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - } - /** - * Depending on current signaling state, create a local offer or answer. - * @param options - Session description handler options. - */ - createLocalOfferOrAnswer(options) { - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable, assume we are creating a local offer - this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"); - return this._peerConnection.createOffer(options === null || options === void 0 ? void 0 : options.offerOptions); - case "have-remote-offer": - // if we have a remote offer, assume we are creating a local answer - this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"); - return this._peerConnection.createAnswer(options === null || options === void 0 ? void 0 : options.answerOptions); - case "have-local-offer": - case "have-local-pranswer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - } - /** - * Get a media stream from the media stream factory and set the local media stream. - * @param options - Session description handler options. - */ - getLocalMediaStream(options) { - this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - let constraints = Object.assign({}, options === null || options === void 0 ? void 0 : options.constraints); - // if we already have a local media stream... - if (this.localMediaStreamConstraints) { - // ignore constraint "downgrades" - constraints.audio = constraints.audio || this.localMediaStreamConstraints.audio; - constraints.video = constraints.video || this.localMediaStreamConstraints.video; - // if constraints have not changed, do not get a new media stream - if (JSON.stringify(this.localMediaStreamConstraints.audio) === JSON.stringify(constraints.audio) && - JSON.stringify(this.localMediaStreamConstraints.video) === JSON.stringify(constraints.video)) { - return Promise.resolve(); - } - } - else { - // if no constraints have been specified, default to audio for initial media stream - if (constraints.audio === undefined && constraints.video === undefined) { - constraints = { audio: true }; - } - } - this.localMediaStreamConstraints = constraints; - return this.mediaStreamFactory(constraints, this).then((mediaStream) => this.setLocalMediaStream(mediaStream)); - } - /** - * Sets the peer connection's sender tracks and local media stream tracks. - * - * @remarks - * Only the first audio and video tracks of the provided MediaStream are utilized. - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param stream - Media stream containing tracks to be utilized. - */ - setLocalMediaStream(stream) { - this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"); - if (!this._peerConnection) { - throw new Error("Peer connection undefined."); - } - const pc = this._peerConnection; - const localStream = this._localMediaStream; - const trackUpdates = []; - const updateTrack = (newTrack) => { - const kind = newTrack.kind; - if (kind !== "audio" && kind !== "video") { - throw new Error(`Unknown new track kind ${kind}.`); - } - const sender = pc.getSenders().find((sender) => sender.track && sender.track.kind === kind); - if (sender) { - trackUpdates.push(new Promise((resolve) => { - this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${kind} track`); - resolve(); - }).then(() => sender - .replaceTrack(newTrack) - .then(() => { - const oldTrack = localStream.getTracks().find((localTrack) => localTrack.kind === kind); - if (oldTrack) { - oldTrack.stop(); - localStream.removeTrack(oldTrack); - SessionDescriptionHandler.dispatchRemoveTrackEvent(localStream, oldTrack); - } - localStream.addTrack(newTrack); - SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); - }) - .catch((error) => { - this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${kind} track`); - throw error; - }))); - } - else { - trackUpdates.push(new Promise((resolve) => { - this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${kind} track`); - resolve(); - }).then(() => { - // Review: could make streamless tracks a configurable option? - // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack#Usage_notes - try { - pc.addTrack(newTrack, localStream); - } - catch (error) { - this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${kind} track`); - throw error; - } - localStream.addTrack(newTrack); - SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); - })); - } - }; - // update peer connection audio tracks - const audioTracks = stream.getAudioTracks(); - if (audioTracks.length) { - updateTrack(audioTracks[0]); - } - // update peer connection video tracks - const videoTracks = stream.getVideoTracks(); - if (videoTracks.length) { - updateTrack(videoTracks[0]); - } - return trackUpdates.reduce((p, x) => p.then(() => x), Promise.resolve()); - } - /** - * Gets the peer connection's local session description. - */ - getLocalSessionDescription() { - this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - const sdp = this._peerConnection.localDescription; - if (!sdp) { - return Promise.reject(new Error("Failed to get local session description")); - } - return Promise.resolve(sdp); - } - /** - * Sets the peer connection's local session description. - * @param sessionDescription - sessionDescription The session description. - */ - setLocalSessionDescription(sessionDescription) { - this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - return this._peerConnection.setLocalDescription(sessionDescription); - } - /** - * Sets the peer connection's remote session description. - * @param sessionDescription - The session description. - */ - setRemoteSessionDescription(sessionDescription) { - this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - const sdp = sessionDescription.sdp; - let type; - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable assume this is a remote offer - type = "offer"; - break; - case "have-local-offer": - // if we made an offer, assume this is a remote answer - type = "answer"; - break; - case "have-local-pranswer": - case "have-remote-offer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - if (!sdp) { - this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"); - return Promise.reject(new Error("SDP is undefined")); - } - return this._peerConnection.setRemoteDescription({ sdp, type }); - } - /** - * Sets a remote media stream track. - * - * @remarks - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param track - Media stream track to be utilized. - */ - setRemoteTrack(track) { - this.logger.debug("SessionDescriptionHandler.setRemoteTrack"); - const remoteStream = this._remoteMediaStream; - if (remoteStream.getTrackById(track.id)) { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${track.kind} track`); - } - else if (track.kind === "audio") { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); - remoteStream.getAudioTracks().forEach((track) => { - track.stop(); - remoteStream.removeTrack(track); - SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); - }); - remoteStream.addTrack(track); - SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); - } - else if (track.kind === "video") { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); - remoteStream.getVideoTracks().forEach((track) => { - track.stop(); - remoteStream.removeTrack(track); - SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); - }); - remoteStream.addTrack(track); - SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); - } - } - /** - * Called when ICE gathering completes and resolves any waiting promise. - */ - iceGatheringComplete() { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"); - // clear timer if need be - if (this.iceGatheringCompleteTimeoutId !== undefined) { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"); - clearTimeout(this.iceGatheringCompleteTimeoutId); - this.iceGatheringCompleteTimeoutId = undefined; - } - // resolve and cleanup promise if need be - if (this.iceGatheringCompletePromise !== undefined) { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"); - this.iceGatheringCompleteResolve && this.iceGatheringCompleteResolve(); - this.iceGatheringCompletePromise = undefined; - this.iceGatheringCompleteResolve = undefined; - this.iceGatheringCompleteReject = undefined; - } - } - /** - * Wait for ICE gathering to complete. - * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). - * @param timeout - Milliseconds after which waiting times out. No timeout if 0. - */ - waitForIceGatheringComplete(restart = false, timeout = 0) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"); - if (this._peerConnection === undefined) { - return Promise.reject("Peer connection closed."); - } - // guard already complete - if (!restart && this._peerConnection.iceGatheringState === "complete") { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"); - return Promise.resolve(); - } - // only one may be waiting, reject any prior - if (this.iceGatheringCompletePromise !== undefined) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"); - this.iceGatheringCompleteReject && this.iceGatheringCompleteReject(new Error("Promise superseded.")); - this.iceGatheringCompletePromise = undefined; - this.iceGatheringCompleteResolve = undefined; - this.iceGatheringCompleteReject = undefined; - } - this.iceGatheringCompletePromise = new Promise((resolve, reject) => { - this.iceGatheringCompleteResolve = resolve; - this.iceGatheringCompleteReject = reject; - if (timeout > 0) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in " + timeout); - this.iceGatheringCompleteTimeoutId = setTimeout(() => { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"); - this.iceGatheringComplete(); - }, timeout); - } - }); - return this.iceGatheringCompletePromise; - } - /** - * Initializes the peer connection event handlers - */ - initPeerConnectionEventHandlers() { - this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"); - if (!this._peerConnection) - throw new Error("Peer connection undefined."); - const peerConnection = this._peerConnection; - peerConnection.onconnectionstatechange = (event) => { - var _a; - const newState = peerConnection.connectionState; - this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onconnectionstatechange) { - this._peerConnectionDelegate.onconnectionstatechange(event); - } - }; - peerConnection.ondatachannel = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.ondatachannel`); - this._dataChannel = event.channel; - if (this.onDataChannel) { - this.onDataChannel(this._dataChannel); - } - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ondatachannel) { - this._peerConnectionDelegate.ondatachannel(event); - } - }; - peerConnection.onicecandidate = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onicecandidate`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidate) { - this._peerConnectionDelegate.onicecandidate(event); - } - }; - peerConnection.onicecandidateerror = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onicecandidateerror`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidateerror) { - this._peerConnectionDelegate.onicecandidateerror(event); - } - }; - peerConnection.oniceconnectionstatechange = (event) => { - var _a; - const newState = peerConnection.iceConnectionState; - this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.oniceconnectionstatechange) { - this._peerConnectionDelegate.oniceconnectionstatechange(event); - } - }; - peerConnection.onicegatheringstatechange = (event) => { - var _a; - const newState = peerConnection.iceGatheringState; - this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${newState}`); - if (newState === "complete") { - this.iceGatheringComplete(); // complete waiting for ICE gathering to complete - } - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicegatheringstatechange) { - this._peerConnectionDelegate.onicegatheringstatechange(event); - } - }; - peerConnection.onnegotiationneeded = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onnegotiationneeded`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onnegotiationneeded) { - this._peerConnectionDelegate.onnegotiationneeded(event); - } - }; - peerConnection.onsignalingstatechange = (event) => { - var _a; - const newState = peerConnection.signalingState; - this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onsignalingstatechange) { - this._peerConnectionDelegate.onsignalingstatechange(event); - } - }; - peerConnection.onstatsended = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onstatsended`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onstatsended) { - this._peerConnectionDelegate.onstatsended(event); - } - }; - peerConnection.ontrack = (event) => { - var _a; - const kind = event.track.kind; - const enabled = event.track.enabled ? "enabled" : "disabled"; - this.logger.debug(`SessionDescriptionHandler.ontrack ${kind} ${enabled}`); - this.setRemoteTrack(event.track); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ontrack) { - this._peerConnectionDelegate.ontrack(event); - } - }; - } -} - - -/***/ }), -/* 168 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 169 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 170 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 171 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(172); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return _transport__WEBPACK_IMPORTED_MODULE_0__["Transport"]; }); - -/* harmony import */ var _transport_options__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(173); -/* harmony import */ var _transport_options__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_transport_options__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport_options__WEBPACK_IMPORTED_MODULE_1__) if(["Transport","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport_options__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/** - * A Transport implementation for web browsers. - * @packageDocumentation - */ - - - - -/***/ }), -/* 172 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return Transport; }); -/* harmony import */ var _api_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); -/* harmony import */ var _api_exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _api_transport_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(156); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); - - - - -/** - * Transport for SIP over secure WebSocket (WSS). - * @public - */ -class Transport { - constructor(logger, options) { - this._state = _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected; - this.transitioningState = false; - // state emitter - this._stateEventEmitter = new _api_emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); - // logger - this.logger = logger; - // guard deprecated options (remove this in version 16.x) - if (options) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const optionsDeprecated = options; - const wsServersDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.wsServers; - const maxReconnectionAttemptsDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.maxReconnectionAttempts; - if (wsServersDeprecated !== undefined) { - const deprecatedMessage = `The transport option "wsServers" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (maxReconnectionAttemptsDeprecated !== undefined) { - const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // hack - if (wsServersDeprecated && !options.server) { - if (typeof wsServersDeprecated === "string") { - options.server = wsServersDeprecated; - } - if (wsServersDeprecated instanceof Array) { - options.server = wsServersDeprecated[0]; - } - } - } - // initialize configuration - this.configuration = Object.assign(Object.assign({}, Transport.defaultOptions), options); - // validate server URL - const url = this.configuration.server; - const parsed = _core__WEBPACK_IMPORTED_MODULE_3__["Grammar"].parse(url, "absoluteURI"); - if (parsed === -1) { - this.logger.error(`Invalid WebSocket Server URL "${url}"`); - throw new Error("Invalid WebSocket Server URL"); - } - if (!["wss", "ws", "udp"].includes(parsed.scheme)) { - this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); - throw new Error("Invalid scheme in WebSocket Server URL"); - } - this._protocol = parsed.scheme.toUpperCase(); - } - dispose() { - return this.disconnect(); - } - /** - * The protocol. - * - * @remarks - * Formatted as defined for the Via header sent-protocol transport. - * https://tools.ietf.org/html/rfc3261#section-20.42 - */ - get protocol() { - return this._protocol; - } - /** - * The URL of the WebSocket Server. - */ - get server() { - return this.configuration.server; - } - /** - * Transport state. - */ - get state() { - return this._state; - } - /** - * Transport state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * The WebSocket. - */ - get ws() { - return this._ws; - } - /** - * Connect to network. - * Resolves once connected. Otherwise rejects with an Error. - */ - connect() { - return this._connect(); - } - /** - * Disconnect from network. - * Resolves once disconnected. Otherwise rejects with an Error. - */ - disconnect() { - return this._disconnect(); - } - /** - * Returns true if the `state` equals "Connected". - * @remarks - * This is equivalent to `state === TransportState.Connected`. - */ - isConnected() { - return this.state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected; - } - /** - * Sends a message. - * Resolves once message is sent. Otherwise rejects with an Error. - * @param message - Message to send. - */ - send(message) { - // Error handling is independent of whether the message was a request or - // response. - // - // If the transport user asks for a message to be sent over an - // unreliable transport, and the result is an ICMP error, the behavior - // depends on the type of ICMP error. Host, network, port or protocol - // unreachable errors, or parameter problem errors SHOULD cause the - // transport layer to inform the transport user of a failure in sending. - // Source quench and TTL exceeded ICMP errors SHOULD be ignored. - // - // If the transport user asks for a request to be sent over a reliable - // transport, and the result is a connection failure, the transport - // layer SHOULD inform the transport user of a failure in sending. - // https://tools.ietf.org/html/rfc3261#section-18.4 - return this._send(message); - } - _connect() { - this.logger.log(`Connecting ${this.server}`); - switch (this.state) { - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: - // If `state` is "Connecting", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); - } - if (!this.connectPromise) { - throw new Error("Connect promise must be defined."); - } - return this.connectPromise; // Already connecting - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: - // If `state` is "Connected", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); - } - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - return Promise.resolve(); // Already connected - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: - // If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: - // If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - default: - throw new Error("Unknown state"); - } - let ws; - try { - // WebSocket() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket - ws = new WebSocket(this.server, "sip"); - ws.binaryType = "arraybuffer"; // set data type of received binary messages - ws.addEventListener("close", (ev) => this.onWebSocketClose(ev, ws)); - ws.addEventListener("error", (ev) => this.onWebSocketError(ev, ws)); - ws.addEventListener("open", (ev) => this.onWebSocketOpen(ev, ws)); - ws.addEventListener("message", (ev) => this.onWebSocketMessage(ev, ws)); - this._ws = ws; - } - catch (error) { - this._ws = undefined; - this.logger.error("WebSocket construction failed."); - this.logger.error(error); - return new Promise((resolve, reject) => { - this.connectResolve = resolve; - this.connectReject = reject; - // The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); - }); - } - this.connectPromise = new Promise((resolve, reject) => { - this.connectResolve = resolve; - this.connectReject = reject; - this.connectTimeout = setTimeout(() => { - this.logger.warn("Connect timed out. " + - "Exceeded time set in configuration.connectionTimeout: " + - this.configuration.connectionTimeout + - "s."); - ws.close(1000); // careful here to use a local reference instead of this._ws - }, this.configuration.connectionTimeout * 1000); - }); - return this.connectPromise; - } - _disconnect() { - this.logger.log(`Disconnecting ${this.server}`); - switch (this.state) { - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: - // If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: - // If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: - // If `state` is "Disconnecting", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); - } - if (!this.disconnectPromise) { - throw new Error("Disconnect promise must be defined."); - } - return this.disconnectPromise; // Already disconnecting - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: - // If `state` is "Disconnected", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); - } - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - return Promise.resolve(); // Already disconnected - default: - throw new Error("Unknown state"); - } - if (!this._ws) { - throw new Error("WebSocket must be defined."); - } - const ws = this._ws; - this.disconnectPromise = new Promise((resolve, reject) => { - this.disconnectResolve = resolve; - this.disconnectReject = reject; - try { - // WebSocket.close() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close - ws.close(1000); // careful here to use a local reference instead of this._ws - } - catch (error) { - // Treating this as a coding error as it apparently can only happen - // if you pass close() invalid parameters (so it should never happen) - this.logger.error("WebSocket close failed."); - this.logger.error(error); - throw error; - } - }); - return this.disconnectPromise; - } - _send(message) { - if (this.configuration.traceSip === true) { - this.logger.log("Sending WebSocket message:\n\n" + message + "\n"); - } - if (this._state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - return Promise.reject(new Error("Not connected.")); - } - if (!this._ws) { - throw new Error("WebSocket undefined."); - } - try { - // WebSocket.send() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send - this._ws.send(message); - } - catch (error) { - if (error instanceof Error) { - return Promise.reject(error); - } - return Promise.reject(new Error("WebSocket send failed.")); - } - return Promise.resolve(); - } - /** - * WebSocket "onclose" event handler. - * @param ev - Event. - */ - onWebSocketClose(ev, ws) { - if (ws !== this._ws) { - return; - } - const message = `WebSocket closed ${this.server} (code: ${ev.code})`; - const error = !this.disconnectPromise ? new Error(message) : undefined; - if (error) { - this.logger.warn("WebSocket closed unexpectedly"); - } - this.logger.log(message); - // We are about to transition to disconnected, so clear our web socket - this._ws = undefined; - // The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); - } - /** - * WebSocket "onerror" event handler. - * @param ev - Event. - */ - onWebSocketError(ev, ws) { - if (ws !== this._ws) { - return; - } - this.logger.error("WebSocket error occurred."); - } - /** - * WebSocket "onmessage" event handler. - * @param ev - Event. - */ - onWebSocketMessage(ev, ws) { - if (ws !== this._ws) { - return; - } - const data = ev.data; - let finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket message with CRLF Keep Alive response"); - } - return; - } - if (!data) { - this.logger.warn("Received empty message, discarding..."); - return; - } - if (typeof data !== "string") { - // WebSocket binary message. - try { - finishedData = new TextDecoder().decode(new Uint8Array(data)); - // TextDecoder (above) is not supported by old browsers, but it correctly decodes UTF-8. - // The line below is an ISO 8859-1 (Latin 1) decoder, so just UTF-8 code points that are 1 byte. - // It's old code and works in old browsers (IE), so leaving it here in a comment in case someone needs it. - // finishedData = String.fromCharCode.apply(null, (new Uint8Array(data) as unknown as Array)); - } - catch (err) { - this.logger.error(err); - this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket binary message:\n\n" + finishedData + "\n"); - } - } - else { - // WebSocket text message. - finishedData = data; - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket text message:\n\n" + finishedData + "\n"); - } - } - if (this.state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - this.logger.warn("Received message while not connected, discarding..."); - return; - } - if (this.onMessage) { - try { - this.onMessage(finishedData); - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onMessage callback"); - throw e; // rethrow unhandled exception - } - } - } - /** - * WebSocket "onopen" event handler. - * @param ev - Event. - */ - onWebSocketOpen(ev, ws) { - if (ws !== this._ws) { - return; - } - if (this._state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - this.logger.log(`WebSocket opened ${this.server}`); - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected); - } - } - /** - * Helper function to generate an Error. - * @param state - State transitioning to. - */ - transitionLoopDetectedError(state) { - let message = `A state transition loop has been detected.`; - message += ` An attempt to transition from ${this._state} to ${state} before the prior transition completed.`; - message += ` Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?`; - this.logger.error(message); - return new _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]("Loop detected."); - } - /** - * Transition transport state. - * @internal - */ - transitionState(newState, error) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - if (this.transitioningState) { - throw this.transitionLoopDetectedError(newState); - } - this.transitioningState = true; - // Validate state transition - switch (this._state) { - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected && - newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && - newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { - invalidTransition(); - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { - invalidTransition(); - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { - invalidTransition(); - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - invalidTransition(); - } - break; - default: - throw new Error("Unknown state."); - } - // Update state - const oldState = this._state; - this._state = newState; - // Local copies of connect promises (guarding against callbacks changing them indirectly) - // const connectPromise = this.connectPromise; - const connectResolve = this.connectResolve; - const connectReject = this.connectReject; - // Reset connect promises if no longer connecting - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - this.connectPromise = undefined; - this.connectResolve = undefined; - this.connectReject = undefined; - } - // Local copies of disconnect promises (guarding against callbacks changing them indirectly) - // const disconnectPromise = this.disconnectPromise; - const disconnectResolve = this.disconnectResolve; - const disconnectReject = this.disconnectReject; - // Reset disconnect promises if no longer disconnecting - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { - this.disconnectPromise = undefined; - this.disconnectResolve = undefined; - this.disconnectReject = undefined; - } - // Clear any outstanding connect timeout - if (this.connectTimeout) { - clearTimeout(this.connectTimeout); - this.connectTimeout = undefined; - } - this.logger.log(`Transitioned from ${oldState} to ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Transition to Connected - if (newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - this.startSendingKeepAlives(); - if (this.onConnect) { - try { - this.onConnect(); - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onConnect callback"); - throw e; // rethrow unhandled exception - } - } - } - // Transition from Connected - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - this.stopSendingKeepAlives(); - if (this.onDisconnect) { - try { - if (error) { - this.onDisconnect(error); - } - else { - this.onDisconnect(); - } - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onDisconnect callback"); - throw e; // rethrow unhandled exception - } - } - } - // Complete connect promise - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - if (!connectResolve) { - throw new Error("Connect resolve undefined."); - } - if (!connectReject) { - throw new Error("Connect reject undefined."); - } - newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected ? connectResolve() : connectReject(error || new Error("Connect aborted.")); - } - // Complete disconnect promise - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { - if (!disconnectResolve) { - throw new Error("Disconnect resolve undefined."); - } - if (!disconnectReject) { - throw new Error("Disconnect reject undefined."); - } - newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected - ? disconnectResolve() - : disconnectReject(error || new Error("Disconnect aborted.")); - } - this.transitioningState = false; - } - // TODO: Review "KeepAlive Stuff". - // It is not clear if it works and there are no tests for it. - // It was blindly lifted the keep alive code unchanged from earlier transport code. - // - // From the RFC... - // - // SIP WebSocket Clients and Servers may keep their WebSocket - // connections open by sending periodic WebSocket "Ping" frames as - // described in [RFC6455], Section 5.5.2. - // ... - // The indication and use of the CRLF NAT keep-alive mechanism defined - // for SIP connection-oriented transports in [RFC5626], Section 3.5.1 or - // [RFC6223] are, of course, usable over the transport defined in this - // specification. - // https://tools.ietf.org/html/rfc7118#section-6 - // - // and... - // - // The Ping frame contains an opcode of 0x9. - // https://tools.ietf.org/html/rfc6455#section-5.5.2 - // - // ============================== - // KeepAlive Stuff - // ============================== - clearKeepAliveTimeout() { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - } - /** - * Send a keep-alive (a double-CRLF sequence). - */ - sendKeepAlive() { - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return Promise.resolve(); - } - this.keepAliveDebounceTimeout = setTimeout(() => { - this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - } - /** - * Start sending keep-alives. - */ - startSendingKeepAlives() { - // Compute an amount of time in seconds to wait before sending another keep-alive. - const computeKeepAliveTimeout = (upperBound) => { - const lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); - }; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(() => { - this.sendKeepAlive(); - this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - } - /** - * Stop sending keep-alives. - */ - stopSendingKeepAlives() { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - } -} -Transport.defaultOptions = { - server: "", - connectionTimeout: 5, - keepAliveInterval: 0, - keepAliveDebounce: 10, - traceSip: true -}; - - -/***/ }), -/* 173 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 174 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); - -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(160); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler__WEBPACK_IMPORTED_MODULE_1__) if(["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _simple_user__WEBPACK_IMPORTED_MODULE_2__) if(["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _simple_user__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport__WEBPACK_IMPORTED_MODULE_3__) if(["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - - - -/***/ }), -/* 175 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); - -/** - * SessionDescriptionHandlerModifer functions for web browsers. - * @packageDocumentation - */ - - - -/***/ }), -/* 176 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return stripTcpCandidates; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return stripTelephoneEvent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return cleanJitsiSdpImageattr; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return stripG722; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return stripRtpPayload; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return stripVideo; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return addMidLines; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return holdModifier; }); -const stripPayload = (sdp, payload) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const mediaDescs = []; - const lines = sdp.split(/\r\n/); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let currentMediaDesc; - for (let i = 0; i < lines.length;) { - const line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - const rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (const mediaDesc of mediaDescs) { - const mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (let j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -const stripMediaDescription = (sdp, description) => { - const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - const groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - let midLineToRemove; - sdp = sdp.split(/^m=/gm).filter((section) => { - if (section.substr(0, description.length) === description) { - midLineToRemove = section.match(/^a=mid:.*$/gm); - if (midLineToRemove) { - const step = midLineToRemove[0].match(/:.+$/g); - if (step) { - midLineToRemove = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - const groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - let groupLinePortion = groupLine[0]; - // eslint-disable-next-line no-useless-escape - const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -/** - * Modifier. - * @public - */ -function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function stripRtpPayload(payload) { - return (description) => { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -/** - * Modifier. - * @public - */ -function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function addMidLines(description) { - let sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - const mlines = sdp.match(/^m=.*$/gm); - const sdpArray = sdp.split(/^m=.*$/gm); - if (mlines) { - mlines.forEach((elem, idx) => { - mlines[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray.forEach((elem, idx) => { - if (mlines && mlines[idx]) { - sdpArray[idx] = elem + mlines[idx]; - } - }); - sdp = sdpArray.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -/** - * The modifier that should be used when the session would like to place the call on hold. - * @param description - The description that will be modified. - */ -function holdModifier(description) { - if (!description.sdp || !description.type) { - throw new Error("Invalid SDP"); - } - let sdp = description.sdp; - const type = description.type; - if (sdp) { - if (!/a=(sendrecv|sendonly|recvonly|inactive)/.test(sdp)) { - sdp = sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - sdp = sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - sdp = sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - } - return Promise.resolve({ sdp, type }); -} - - -/***/ }), -/* 177 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return _simple_user__WEBPACK_IMPORTED_MODULE_0__["SimpleUser"]; }); - -/* harmony import */ var _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(179); -/* harmony import */ var _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__) if(["SimpleUser","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _simple_user_options__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(180); -/* harmony import */ var _simple_user_options__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_simple_user_options__WEBPACK_IMPORTED_MODULE_2__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _simple_user_options__WEBPACK_IMPORTED_MODULE_2__) if(["SimpleUser","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _simple_user_options__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/** - * A simple SIP user implementation for web browsers. - * @packageDocumentation - */ - - - - - -/***/ }), -/* 178 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return SimpleUser; }); -/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(175); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); - - - - -/** - * A simple SIP user class. - * @remarks - * While this class is completely functional for simple use cases, it is not intended - * to provide an interface which is suitable for most (must less all) applications. - * While this class has many limitations (for example, it only handles a single concurrent session), - * it is, however, intended to serve as a simple example of using the SIP.js API. - * @public - */ -class SimpleUser { - /** - * Constructs a new instance of the `SimpleUser` class. - * @param server - SIP WebSocket Server URL. - * @param options - Options bucket. See {@link SimpleUserOptions} for details. - */ - constructor(server, options = {}) { - this.attemptingReconnection = false; - this.connectRequested = false; - this.held = false; - this.registerer = undefined; - this.registerRequested = false; - this.session = undefined; - // Delegate - this.delegate = options.delegate; - // Copy options - this.options = Object.assign({}, options); - // UserAgentOptions - const userAgentOptions = Object.assign({}, options.userAgentOptions); - // Transport - if (!userAgentOptions.transportConstructor) { - userAgentOptions.transportConstructor = _transport__WEBPACK_IMPORTED_MODULE_3__["Transport"]; - } - // TransportOptions - if (!userAgentOptions.transportOptions) { - userAgentOptions.transportOptions = { - server - }; - } - // URI - if (!userAgentOptions.uri) { - // If an AOR was provided, convert it to a URI - if (options.aor) { - const uri = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(options.aor); - if (!uri) { - throw new Error(`Failed to create valid URI from ${options.aor}`); - } - userAgentOptions.uri = uri; - } - } - // UserAgent - this.userAgent = new _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"](userAgentOptions); - // UserAgent's delegate - this.userAgent.delegate = { - // Handle connection with server established - onConnect: () => { - this.logger.log(`[${this.id}] Connected`); - if (this.delegate && this.delegate.onServerConnect) { - this.delegate.onServerConnect(); - } - if (this.registerer && this.registerRequested) { - this.logger.log(`[${this.id}] Registering...`); - this.registerer.register().catch((e) => { - this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`); - this.logger.error(e.toString()); - }); - } - }, - // Handle connection with server lost - onDisconnect: (error) => { - this.logger.log(`[${this.id}] Disconnected`); - if (this.delegate && this.delegate.onServerDisconnect) { - this.delegate.onServerDisconnect(error); - } - if (this.session) { - this.logger.log(`[${this.id}] Hanging up...`); - this.hangup() // cleanup hung calls - .catch((e) => { - this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`); - this.logger.error(e.toString()); - }); - } - if (this.registerer) { - this.logger.log(`[${this.id}] Unregistering...`); - this.registerer - .unregister() // cleanup invalid registrations - .catch((e) => { - this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`); - this.logger.error(e.toString()); - }); - } - // Only attempt to reconnect if network/server dropped the connection. - if (error) { - this.attemptReconnection(); - } - }, - // Handle incoming invitations - onInvite: (invitation) => { - this.logger.log(`[${this.id}] Received INVITE`); - // Guard against a pre-existing session. This implementation only supports one session at a time. - // However an incoming INVITE request may be received at any time and/or while in the process - // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. - if (this.session) { - this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`); - invitation - .reject() - .then(() => { - this.logger.log(`[${this.id}] Rejected INVITE`); - }) - .catch((error) => { - this.logger.error(`[${this.id}] Failed to reject INVITE`); - this.logger.error(error.toString()); - }); - return; - } - // Use our configured constraints as options for any Inviter created as result of a REFER - const referralInviterOptions = { - sessionDescriptionHandlerOptions: { constraints: this.constraints } - }; - // Initialize our session - this.initSession(invitation, referralInviterOptions); - // Delegate - if (this.delegate && this.delegate.onCallReceived) { - this.delegate.onCallReceived(); - } - else { - this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`); - invitation - .reject() - .then(() => { - this.logger.log(`[${this.id}] Rejected INVITE`); - }) - .catch((error) => { - this.logger.error(`[${this.id}] Failed to reject INVITE`); - this.logger.error(error.toString()); - }); - } - }, - // Handle incoming messages - onMessage: (message) => { - message.accept().then(() => { - if (this.delegate && this.delegate.onMessageReceived) { - this.delegate.onMessageReceived(message.request.body); - } - }); - } - }; - // Use the SIP.js logger - this.logger = this.userAgent.getLogger("sip.SimpleUser"); - // Monitor network connectivity and attempt reconnection when we come online - window.addEventListener("online", () => { - this.logger.log(`[${this.id}] Online`); - this.attemptReconnection(); - }); - } - /** - * Instance identifier. - * @internal - */ - get id() { - return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; - } - /** The local media stream. Undefined if call not answered. */ - get localMediaStream() { - var _a; - const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; - if (!sdh) { - return undefined; - } - if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session description handler not instance of web SessionDescriptionHandler"); - } - return sdh.localMediaStream; - } - /** The remote media stream. Undefined if call not answered. */ - get remoteMediaStream() { - var _a; - const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; - if (!sdh) { - return undefined; - } - if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session description handler not instance of web SessionDescriptionHandler"); - } - return sdh.remoteMediaStream; - } - /** - * The local audio track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localAudioTrack() { - var _a; - return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); - } - /** - * The local video track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localVideoTrack() { - var _a; - return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); - } - /** - * The remote audio track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteAudioTrack() { - var _a; - return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); - } - /** - * The remote video track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteVideoTrack() { - var _a; - return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); - } - /** - * Connect. - * @remarks - * Start the UserAgent's WebSocket Transport. - */ - connect() { - this.logger.log(`[${this.id}] Connecting UserAgent...`); - this.connectRequested = true; - if (this.userAgent.state !== _api__WEBPACK_IMPORTED_MODULE_0__["UserAgentState"].Started) { - return this.userAgent.start(); - } - return this.userAgent.reconnect(); - } - /** - * Disconnect. - * @remarks - * Stop the UserAgent's WebSocket Transport. - */ - disconnect() { - this.logger.log(`[${this.id}] Disconnecting UserAgent...`); - this.connectRequested = false; - return this.userAgent.stop(); - } - /** - * Return true if connected. - */ - isConnected() { - return this.userAgent.isConnected(); - } - /** - * Start receiving incoming calls. - * @remarks - * Send a REGISTER request for the UserAgent's AOR. - * Resolves when the REGISTER request is sent, otherwise rejects. - */ - register(registererOptions, registererRegisterOptions) { - this.logger.log(`[${this.id}] Registering UserAgent...`); - this.registerRequested = true; - if (!this.registerer) { - this.registerer = new _api__WEBPACK_IMPORTED_MODULE_0__["Registerer"](this.userAgent, registererOptions); - this.registerer.stateChange.addListener((state) => { - switch (state) { - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Initial: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Registered: - if (this.delegate && this.delegate.onRegistered) { - this.delegate.onRegistered(); - } - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Unregistered: - if (this.delegate && this.delegate.onUnregistered) { - this.delegate.onUnregistered(); - } - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Terminated: - this.registerer = undefined; - break; - default: - throw new Error("Unknown registerer state."); - } - }); - } - return this.registerer.register(registererRegisterOptions).then(() => { - return; - }); - } - /** - * Stop receiving incoming calls. - * @remarks - * Send an un-REGISTER request for the UserAgent's AOR. - * Resolves when the un-REGISTER request is sent, otherwise rejects. - */ - unregister(registererUnregisterOptions) { - this.logger.log(`[${this.id}] Unregistering UserAgent...`); - this.registerRequested = false; - if (!this.registerer) { - return Promise.resolve(); - } - return this.registerer.unregister(registererUnregisterOptions).then(() => { - return; - }); - } - /** - * Make an outgoing call. - * @remarks - * Send an INVITE request to create a new Session. - * Resolves when the INVITE request is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if Session is established. - * @param destination - The target destination to call. A SIP address to send the INVITE to. - * @param inviterOptions - Optional options for Inviter constructor. - * @param inviterInviteOptions - Optional options for Inviter.invite(). - */ - call(destination, inviterOptions, inviterInviteOptions) { - this.logger.log(`[${this.id}] Beginning Session...`); - if (this.session) { - return Promise.reject(new Error("Session already exists.")); - } - const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); - if (!target) { - return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); - } - // Use our configured constraints as InviterOptions if none provided - if (!inviterOptions) { - inviterOptions = {}; - } - if (!inviterOptions.sessionDescriptionHandlerOptions) { - inviterOptions.sessionDescriptionHandlerOptions = {}; - } - if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { - inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; - } - // Create a new Inviter for the outgoing Session - const inviter = new _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"](this.userAgent, target, inviterOptions); - // Send INVITE - return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => { - return; - }); - } - /** - * Hangup a call. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - hangup() { - this.logger.log(`[${this.id}] Hangup...`); - return this.terminate(); - } - /** - * Answer an incoming call. - * @remarks - * Accept an incoming INVITE request creating a new Session. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if and when call is established. - * @param invitationAcceptOptions - Optional options for Inviter.accept(). - */ - answer(invitationAcceptOptions) { - this.logger.log(`[${this.id}] Accepting Invitation...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { - return Promise.reject(new Error("Session not instance of Invitation.")); - } - // Use our configured constraints as InvitationAcceptOptions if none provided - if (!invitationAcceptOptions) { - invitationAcceptOptions = {}; - } - if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { - invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; - } - if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { - invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; - } - return this.session.accept(invitationAcceptOptions); - } - /** - * Decline an incoming call. - * @remarks - * Reject an incoming INVITE request. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - decline() { - this.logger.log(`[${this.id}] rejecting Invitation...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { - return Promise.reject(new Error("Session not instance of Invitation.")); - } - return this.session.reject(); - } - /** - * Hold call - * @remarks - * Send a re-INVITE with new offer indicating "hold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - hold() { - this.logger.log(`[${this.id}] holding session...`); - return this.setHold(true); - } - /** - * Unhold call. - * @remarks - * Send a re-INVITE with new offer indicating "unhold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - unhold() { - this.logger.log(`[${this.id}] unholding session...`); - return this.setHold(false); - } - /** - * Hold state. - * @remarks - * True if session media is on hold. - */ - isHeld() { - return this.held; - } - /** - * Mute call. - * @remarks - * Disable sender's media tracks. - */ - mute() { - this.logger.log(`[${this.id}] disabling media tracks...`); - this.setMute(true); - } - /** - * Unmute call. - * @remarks - * Enable sender's media tracks. - */ - unmute() { - this.logger.log(`[${this.id}] enabling media tracks...`); - this.setMute(false); - } - /** - * Mute state. - * @remarks - * True if sender's media track is disabled. - */ - isMuted() { - const track = this.localAudioTrack || this.localVideoTrack; - return track ? !track.enabled : false; - } - /** - * Send DTMF. - * @remarks - * Send an INFO request with content type application/dtmf-relay. - * @param tone - Tone to send. - */ - sendDTMF(tone) { - this.logger.log(`[${this.id}] sending DTMF...`); - // As RFC 6086 states, sending DTMF via INFO is not standardized... - // - // Companies have been using INFO messages in order to transport - // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are - // proprietary and have not been standardized. - // https://tools.ietf.org/html/rfc6086#section-2 - // - // It is however widely supported based on this draft: - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 - // Validate tone - if (!/^[0-9A-D#*,]$/.exec(tone)) { - return Promise.reject(new Error("Invalid DTMF tone.")); - } - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - // The UA MUST populate the "application/dtmf-relay" body, as defined - // earlier, with the button pressed and the duration it was pressed - // for. Technically, this actually requires the INFO to be generated - // when the user *releases* the button, however if the user has still - // not released a button after 5 seconds, which is the maximum duration - // supported by this mechanism, the UA should generate the INFO at that - // time. - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3 - this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`); - const dtmf = tone; - const duration = 2000; - const body = { - contentDisposition: "render", - contentType: "application/dtmf-relay", - content: "Signal=" + dtmf + "\r\nDuration=" + duration - }; - const requestOptions = { body }; - return this.session.info({ requestOptions }).then(() => { - return; - }); - } - /** - * Send a message. - * @remarks - * Send a MESSAGE request. - * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. - */ - message(destination, message) { - this.logger.log(`[${this.id}] sending message...`); - const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); - if (!target) { - return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); - } - return new _api__WEBPACK_IMPORTED_MODULE_0__["Messager"](this.userAgent, target, message).message(); - } - /** Media constraints. */ - get constraints() { - var _a; - let constraints = { audio: true, video: false }; // default to audio only calls - if ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.constraints) { - constraints = Object.assign({}, this.options.media.constraints); - } - return constraints; - } - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - attemptReconnection(reconnectionAttempt = 1) { - const reconnectionAttempts = this.options.reconnectionAttempts || 3; - const reconnectionDelay = this.options.reconnectionDelay || 4; - if (!this.connectRequested) { - this.logger.log(`[${this.id}] Reconnection not currently desired`); - return; // If intentionally disconnected, don't reconnect. - } - if (this.attemptingReconnection) { - this.logger.log(`[${this.id}] Reconnection attempt already in progress`); - } - if (reconnectionAttempt > reconnectionAttempts) { - this.logger.log(`[${this.id}] Reconnection maximum attempts reached`); - return; - } - if (reconnectionAttempt === 1) { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); - } - else { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`); - } - this.attemptingReconnection = true; - setTimeout(() => { - if (!this.connectRequested) { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`); - this.attemptingReconnection = false; - return; // If intentionally disconnected, don't reconnect. - } - this.userAgent - .reconnect() - .then(() => { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); - this.attemptingReconnection = false; - }) - .catch((error) => { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); - this.logger.error(error.message); - this.attemptingReconnection = false; - this.attemptReconnection(++reconnectionAttempt); - }); - }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); - } - /** Helper function to remove media from html elements. */ - cleanupMedia() { - if (this.options.media) { - if (this.options.media.local) { - if (this.options.media.local.video) { - this.options.media.local.video.srcObject = null; - this.options.media.local.video.pause(); - } - } - if (this.options.media.remote) { - if (this.options.media.remote.audio) { - this.options.media.remote.audio.srcObject = null; - this.options.media.remote.audio.pause(); - } - if (this.options.media.remote.video) { - this.options.media.remote.video.srcObject = null; - this.options.media.remote.video.pause(); - } - } - } - } - /** Helper function to enable/disable media tracks. */ - enableSenderTracks(enable) { - if (!this.session) { - throw new Error("Session does not exist."); - } - const sessionDescriptionHandler = this.session.sessionDescriptionHandler; - if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); - } - const peerConnection = sessionDescriptionHandler.peerConnection; - if (!peerConnection) { - throw new Error("Peer connection closed."); - } - peerConnection.getSenders().forEach((sender) => { - if (sender.track) { - sender.track.enabled = enable; - } - }); - } - /** - * Setup session delegate and state change handler. - * @param session - Session to setup - * @param referralInviterOptions - Options for any Inviter created as result of a REFER. - */ - initSession(session, referralInviterOptions) { - // Set session - this.session = session; - // Call session created callback - if (this.delegate && this.delegate.onCallCreated) { - this.delegate.onCallCreated(); - } - // Setup session state change handler - this.session.stateChange.addListener((state) => { - if (this.session !== session) { - return; // if our session has changed, just return - } - this.logger.log(`[${this.id}] session state changed to ${state}`); - switch (state) { - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: - this.setupLocalMedia(); - this.setupRemoteMedia(); - if (this.delegate && this.delegate.onCallAnswered) { - this.delegate.onCallAnswered(); - } - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: - // fall through - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: - this.session = undefined; - this.cleanupMedia(); - if (this.delegate && this.delegate.onCallHangup) { - this.delegate.onCallHangup(); - } - break; - default: - throw new Error("Unknown session state."); - } - }); - // Setup delegate - this.session.delegate = { - onInfo: (info) => { - // As RFC 6086 states, sending DTMF via INFO is not standardized... - // - // Companies have been using INFO messages in order to transport - // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are - // proprietary and have not been standardized. - // https://tools.ietf.org/html/rfc6086#section-2 - // - // It is however widely supported based on this draft: - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 - var _a; - // FIXME: TODO: We should reject correctly... - // - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - // https://tools.ietf.org/html/rfc6086#section-4.2.2 - // No delegate - if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) { - info.reject(); - return; - } - // Invalid content type - const contentType = info.request.getHeader("content-type"); - if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) { - info.reject(); - return; - } - // Invalid body - const body = info.request.body.split("\r\n", 2); - if (body.length !== 2) { - info.reject(); - return; - } - // Invalid tone - let tone; - const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; - if (toneRegExp.test(body[0])) { - tone = body[0].replace(toneRegExp, "$2"); - } - if (!tone) { - info.reject(); - return; - } - // Invalid duration - let duration; - const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - if (durationRegExp.test(body[1])) { - duration = parseInt(body[1].replace(durationRegExp, "$2"), 10); - } - if (!duration) { - info.reject(); - return; - } - info - .accept() - .then(() => { - if (this.delegate && this.delegate.onCallDTMFReceived) { - if (!tone || !duration) { - throw new Error("Tone or duration undefined."); - } - this.delegate.onCallDTMFReceived(tone, duration); - } - }) - .catch((error) => { - this.logger.error(error.message); - }); - }, - onRefer: (referral) => { - referral - .accept() - .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) - .catch((error) => { - this.logger.error(error.message); - }); - } - }; - } - /** Helper function to init send then send invite. */ - sendInvite(inviter, inviterOptions, inviterInviteOptions) { - // Initialize our session - this.initSession(inviter, inviterOptions); - // Send the INVITE - return inviter.invite(inviterInviteOptions).then(() => { - this.logger.log(`[${this.id}] sent INVITE`); - }); - } - /** - * Puts Session on hold. - * @param hold - Hold on if true, off if false. - */ - setHold(hold) { - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - // Just resolve if we are already in correct state - if (this.held === hold) { - return Promise.resolve(); - } - const sessionDescriptionHandler = this.session.sessionDescriptionHandler; - if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); - } - const options = { - requestDelegate: { - onAccept: () => { - this.held = hold; - if (this.delegate && this.delegate.onCallHold) { - this.delegate.onCallHold(this.held); - } - }, - onReject: () => { - this.logger.warn(`[${this.id}] re-invite request was rejected`); - if (this.delegate && this.delegate.onCallHold) { - this.delegate.onCallHold(this.held); - } - } - } - }; - // Use hold modifier to produce the appropriate SDP offer to place call on hold - options.sessionDescriptionHandlerModifiers = hold ? [_modifiers__WEBPACK_IMPORTED_MODULE_1__["holdModifier"]] : []; - // Send re-INVITE - return this.session - .invite(options) - .then(() => { - this.enableSenderTracks(!hold); // mute/unmute - }) - .catch((error) => { - if (error instanceof _api__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]) { - this.logger.error(`[${this.id}] A hold request is already in progress.`); - } - throw error; - }); - } - /** - * Puts Session on mute. - * @param mute - Mute on if true, off if false. - */ - setMute(mute) { - if (!this.session) { - this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`); - return; - } - if (this.session.state !== _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established) { - this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`); - return; - } - this.enableSenderTracks(!mute); - } - /** Helper function to attach local media to html elements. */ - setupLocalMedia() { - var _a, _b; - if (!this.session) { - throw new Error("Session does not exist."); - } - const mediaElement = (_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.local) === null || _b === void 0 ? void 0 : _b.video; - if (mediaElement) { - const localStream = this.localMediaStream; - if (!localStream) { - throw new Error("Local media stream undefiend."); - } - mediaElement.srcObject = localStream; - mediaElement.volume = 0; - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play local media`); - this.logger.error(error.message); - }); - } - } - /** Helper function to attach remote media to html elements. */ - setupRemoteMedia() { - var _a, _b, _c, _d; - if (!this.session) { - throw new Error("Session does not exist."); - } - const mediaElement = ((_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.remote) === null || _b === void 0 ? void 0 : _b.video) || ((_d = (_c = this.options.media) === null || _c === void 0 ? void 0 : _c.remote) === null || _d === void 0 ? void 0 : _d.audio); - if (mediaElement) { - const remoteStream = this.remoteMediaStream; - if (!remoteStream) { - throw new Error("Remote media stream undefiend."); - } - mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action - mediaElement.srcObject = remoteStream; - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play remote media`); - this.logger.error(error.message); - }); - remoteStream.onaddtrack = () => { - this.logger.log(`[${this.id}] Remote media onaddtrack`); - mediaElement.load(); // Safari hack, as it doesn't work otheriwse - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play remote media`); - this.logger.error(error.message); - }); - }; - } - } - /** - * End a session. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when Session is terminated. - */ - terminate() { - this.logger.log(`[${this.id}] Terminating...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - switch (this.session.state) { - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: - if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { - return this.session.cancel().then(() => { - this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`); - }); - } - else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { - return this.session.reject().then(() => { - this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); - }); - } - else { - throw new Error("Unknown session type."); - } - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: - if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { - return this.session.cancel().then(() => { - this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`); - }); - } - else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { - return this.session.reject().then(() => { - this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); - }); - } - else { - throw new Error("Unknown session type."); - } - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: - return this.session.bye().then(() => { - this.logger.log(`[${this.id}] Session ended (sent BYE)`); - }); - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: - break; - default: - throw new Error("Unknown state"); - } - this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`); - return Promise.resolve(); - } -} - - -/***/ }), -/* 179 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 180 */ -/***/ (function(module, exports) { - - - -/***/ }) -/******/ ]); -}); \ No newline at end of file diff --git a/dist/sip-0.17.1.min.js b/dist/sip-0.17.1.min.js deleted file mode 100644 index de47189e9..000000000 --- a/dist/sip-0.17.1.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,(function(){return function(e){var t={};function s(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,s),i.l=!0,i.exports}return s.m=e,s.c=t,s.d=function(e,t,r){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(s.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)s.d(r,i,function(t){return e[t]}.bind(null,i));return r},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=176)}([function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(r||(r={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(r||(r={}))},function(e,t,s){"use strict";s.r(t);var r=s(62);for(var i in r)"default"!==i&&function(e){s.d(t,e,(function(){return r[e]}))}(i);var n=s(51);s.d(t,"Exception",(function(){return n.a})),s.d(t,"TransactionStateError",(function(){return n.b})),s.d(t,"TransportError",(function(){return n.c}));var o=s(124);s.d(t,"Levels",(function(){return o.a})),s.d(t,"LoggerFactory",(function(){return o.c})),s.d(t,"Logger",(function(){return o.b}));var a=s(3);for(var i in a)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(i);var c=s(52);for(var i in c)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return c[e]}))}(i);var d=s(63);for(var i in d)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return d[e]}))}(i);var h=s(9);for(var i in h)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(i);var u=s(128);for(var i in u)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return u[e]}))}(i);var l=s(89);s.d(t,"ByeUserAgentClient",(function(){return l.a})),s.d(t,"ByeUserAgentServer",(function(){return l.b})),s.d(t,"CancelUserAgentClient",(function(){return l.c})),s.d(t,"InfoUserAgentClient",(function(){return l.d})),s.d(t,"InfoUserAgentServer",(function(){return l.e})),s.d(t,"InviteUserAgentClient",(function(){return l.f})),s.d(t,"InviteUserAgentServer",(function(){return l.g})),s.d(t,"MessageUserAgentClient",(function(){return l.h})),s.d(t,"MessageUserAgentServer",(function(){return l.i})),s.d(t,"NotifyUserAgentClient",(function(){return l.j})),s.d(t,"NotifyUserAgentServer",(function(){return l.k})),s.d(t,"PublishUserAgentClient",(function(){return l.n})),s.d(t,"PrackUserAgentClient",(function(){return l.l})),s.d(t,"PrackUserAgentServer",(function(){return l.m})),s.d(t,"ReInviteUserAgentClient",(function(){return l.o})),s.d(t,"ReInviteUserAgentServer",(function(){return l.p})),s.d(t,"ReSubscribeUserAgentClient",(function(){return l.q})),s.d(t,"ReSubscribeUserAgentServer",(function(){return l.r})),s.d(t,"ReferUserAgentClient",(function(){return l.s})),s.d(t,"ReferUserAgentServer",(function(){return l.t})),s.d(t,"RegisterUserAgentClient",(function(){return l.u})),s.d(t,"RegisterUserAgentServer",(function(){return l.v})),s.d(t,"SubscribeUserAgentClient",(function(){return l.w})),s.d(t,"SubscribeUserAgentServer",(function(){return l.x})),s.d(t,"UserAgentClient",(function(){return l.y})),s.d(t,"UserAgentServer",(function(){return l.z}));var g=s(11);s.d(t,"Timers",(function(){return g.a}));var p=s(132);for(var i in p)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","ByeUserAgentClient","ByeUserAgentServer","CancelUserAgentClient","InfoUserAgentClient","InfoUserAgentServer","InviteUserAgentClient","InviteUserAgentServer","MessageUserAgentClient","MessageUserAgentServer","NotifyUserAgentClient","NotifyUserAgentServer","PublishUserAgentClient","PrackUserAgentClient","PrackUserAgentServer","ReInviteUserAgentClient","ReInviteUserAgentServer","ReSubscribeUserAgentClient","ReSubscribeUserAgentServer","ReferUserAgentClient","ReferUserAgentServer","RegisterUserAgentClient","RegisterUserAgentServer","SubscribeUserAgentClient","SubscribeUserAgentServer","UserAgentClient","UserAgentServer","Timers","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(i)},function(e,t,s){"use strict";s.r(t);var r=s(33);s.d(t,"Grammar",(function(){return r.a})),s.d(t,"NameAddrHeader",(function(){return r.b})),s.d(t,"Parameters",(function(){return r.c})),s.d(t,"URI",(function(){return r.d}));var i=s(105);for(var n in i)["Grammar","NameAddrHeader","Parameters","URI","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(84);s.d(t,"fromBodyLegacy",(function(){return o.a})),s.d(t,"isBody",(function(){return o.c})),s.d(t,"getBody",(function(){return o.b}));var a=s(175);s.d(t,"DigestAuthentication",(function(){return a.a}));var c=s(40);s.d(t,"IncomingMessage",(function(){return c.a}));var d=s(35);s.d(t,"IncomingRequestMessage",(function(){return d.a}));var h=s(119);for(var n in h)["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(n);var u=s(27);s.d(t,"IncomingResponseMessage",(function(){return u.a}));var l=s(120);for(var n in l)["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(n);var g=s(46);s.d(t,"OutgoingRequestMessage",(function(){return g.a}));var p=s(121);for(var n in p)["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","OutgoingRequestMessage","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(n);var f=s(85);s.d(t,"constructOutgoingResponse",(function(){return f.a}));var m=s(122);s.d(t,"Parser",(function(){return m.a}))},function(e,t,s){"use strict";var r,i;s.d(t,"a",(function(){return r})),s.d(t,"b",(function(){return i})),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(r||(r={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(i||(i={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(r||(r={}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return i})),s.d(t,"b",(function(){return n})),s.d(t,"d",(function(){return o})),s.d(t,"c",(function(){return a})),s.d(t,"e",(function(){return c}));const r={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function i(e,t=32){let s="";for(let r=0;r{this.transaction&&this.transaction.state===n.a.Proceeding&&new a(o.a,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let r,i;if(401===s?(r=e.parseHeader("www-authenticate"),i="authorization"):(r=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!r)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==r.stale))return this.logger.warn(s+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,r))return!0;this.challenged=!0,r.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new i.a;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new i.a;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===n.a.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));const r=500,i={T1:r,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(r||(r={}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return d}));var r=s(28),i=s(85),n=s(6),o=s(17),a=s(0),c=s(20);class d{constructor(e,t,s,r){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=r,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:Object(n.d)(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new r.a(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new r.a(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new r.a(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError("Invalid statusCode: "+s);const i=new Array;return e.forEach(e=>i.push("Contact: "+e.toString())),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new r.a(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}trying(e){if(!this.tryingable)throw new r.a(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding||this.transaction.state===a.a.Accepted;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying||this.transaction.state===a.a.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying||this.transaction.state===a.a.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying||this.transaction.state===a.a.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=Object(i.a)(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===a.a.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(r||(r={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(r||(r={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Started="Started",e.Stopped="Stopped"}(r||(r={}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(3),i=s(11),n=s(41),o=s(0);class a extends n.a{constructor(e,t,s){super(e,t,s,o.a.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case o.a.Proceeding:if(e.method===r.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case o.a.Accepted:if(e.method===r.C.INVITE)return;break;case o.a.Completed:if(e.method===r.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===r.C.ACK)return void this.stateTransition(o.a.Confirmed);break;case o.a.Confirmed:case o.a.Terminated:if(e.method===r.C.INVITE||e.method===r.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case o.a.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(o.a.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(o.a.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case o.a.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case o.a.Completed:case o.a.Confirmed:case o.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===o.a.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case o.a.Proceeding:t();break;case o.a.Accepted:case o.a.Completed:this.state!==o.a.Proceeding&&t();break;case o.a.Confirmed:this.state!==o.a.Completed&&t();break;case o.a.Terminated:this.state!==o.a.Accepted&&this.state!==o.a.Completed&&this.state!==o.a.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===o.a.Accepted&&(this.L=setTimeout(()=>this.timerL(),i.a.TIMER_L)),e===o.a.Completed&&(this.H=setTimeout(()=>this.timerH(),i.a.TIMER_H)),e===o.a.Confirmed&&(this.I=setTimeout(()=>this.timerI(),i.a.TIMER_I)),e===o.a.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},i.a.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===o.a.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(o.a.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(o.a.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===o.a.Accepted&&this.stateTransition(o.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(11),i=s(43),n=s(0);class o extends i.a{constructor(e,t,s){super(e,t,s,n.a.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),r.a.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case n.a.Trying:if(t>=100&&t<=199)return this.stateTransition(n.a.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(n.a.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(n.a.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Completed:case n.a.Terminated:return;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(n.a.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case n.a.Trying:s();break;case n.a.Proceeding:this.state!==n.a.Trying&&s();break;case n.a.Completed:this.state!==n.a.Trying&&this.state!==n.a.Proceeding&&s();break;case n.a.Terminated:this.state!==n.a.Trying&&this.state!==n.a.Proceeding&&this.state!==n.a.Completed&&(t||s());break;default:s()}e===n.a.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),r.a.TIMER_K)),e===n.a.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==n.a.Trying&&this.state!==n.a.Proceeding||(this.onRequestTimeout(),this.stateTransition(n.a.Terminated))}timerK(){this.state===n.a.Completed&&this.stateTransition(n.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(11),i=s(41),n=s(0);class o extends i.a{constructor(e,t,s){super(e,t,s,n.a.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case n.a.Trying:break;case n.a.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case n.a.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case n.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}}receiveResponse(e,t){if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case n.a.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(n.a.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(n.a.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case n.a.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(n.a.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case n.a.Completed:return;case n.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(n.a.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case n.a.Trying:s();break;case n.a.Proceeding:this.state!==n.a.Trying&&s();break;case n.a.Completed:this.state!==n.a.Trying&&this.state!==n.a.Proceeding&&s();break;case n.a.Terminated:this.state!==n.a.Proceeding&&this.state!==n.a.Completed&&(t||s());break;default:s()}e===n.a.Completed&&(this.J=setTimeout(()=>this.timerJ(),r.a.TIMER_J)),e===n.a.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===n.a.Completed&&this.stateTransition(n.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(3);const i=[r.C.ACK,r.C.BYE,r.C.CANCEL,r.C.INFO,r.C.INVITE,r.C.MESSAGE,r.C.NOTIFY,r.C.OPTIONS,r.C.PRACK,r.C.REFER,r.C.REGISTER,r.C.SUBSCRIBE]},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),s.d(t,"b",(function(){return i})),function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(r||(r={}));const i={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(39);class i extends r.a{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new i(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(11),i=s(43),n=s(0);class o extends i.a{constructor(e,t,s){super(e,t,s,n.a.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),r.a.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case n.a.Calling:if(t>=100&&t<=199)return this.stateTransition(n.a.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(n.a.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(n.a.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(n.a.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(n.a.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case n.a.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case n.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(n.a.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,r=this.request.cseq,i=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${i}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${r} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case n.a.Calling:s();break;case n.a.Proceeding:this.state!==n.a.Calling&&s();break;case n.a.Accepted:case n.a.Completed:this.state!==n.a.Calling&&this.state!==n.a.Proceeding&&s();break;case n.a.Terminated:this.state!==n.a.Calling&&this.state!==n.a.Accepted&&this.state!==n.a.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),n.a.Proceeding,e===n.a.Completed&&(this.D=setTimeout(()=>this.timerD(),r.a.TIMER_D)),e===n.a.Accepted&&(this.M=setTimeout(()=>this.timerM(),r.a.TIMER_M)),e===n.a.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===n.a.Calling&&(this.onRequestTimeout(),this.stateTransition(n.a.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===n.a.Completed&&this.stateTransition(n.a.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===n.a.Accepted&&this.stateTransition(n.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(23),i=s(3);class n{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof r.a))throw new Error("Contact not instance of NameAddrHeader.");const n=i.uri,o=e.cseq,a=e.callId,c=e.fromTag,d=t.toTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!d)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const h=e.from.uri,u=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+c+d,early:t.statusCode<200,callId:a,localTag:c,remoteTag:d,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:h,remoteURI:u,remoteTarget:n,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),n=e.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof r.a))throw new Error("Contact not instance of NameAddrHeader.");const o=n.uri,a=e.cseq,c=e.callId,d=t,h=e.fromTag,u=e.from.uri;return{id:c+d+h,early:s,callId:c,localTag:d,remoteTag:h,localSequenceNumber:void 0,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:u,remoteTarget:o,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==i.C.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,r=this.remoteTag,i=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,d=this.routeSet,h=t&&t.extraHeaders,u=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,i,s,{callId:o,cseq:a,fromTag:n,toTag:r,routeSet:d},h,u)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===i.C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(40);class i extends r.a{constructor(){super()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Transaction state error.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(r.a,i,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return g}));var r=s(2),i=s(28),n=s(11),o=s(6),a=s(58),c=s(90),d=s(59),h=s(34),u=s(1),l=s(22);class g extends h.a{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const n=s.getHeader("supported");if(n&&n.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(u.a.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===u.a.Initial&&(t.reject({statusCode:487}),this.stateTransition(u.a.Terminated))},e)}const o=this.request.getHeader("P-Asserted-Identity");o&&(this._assertedIdentity=r.Grammar.nameAddrHeaderParse(o)),this._contact=this.userAgent.contact.toString();const a=s.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case u.a.Initial:case u.a.Establishing:return this.reject().then(()=>super.dispose());case u.a.Established:case u.a.Terminating:case u.a.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==u.a.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(u.a.Establishing),this.sendAccept().then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(u.a.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==u.a.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===l.a.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==u.a.Initial&&this.state!==u.a.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:Object(o.b)(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const n=e.body?Object(r.fromBodyLegacy)(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:n}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n}),this.stateTransition(u.a.Terminated),Promise.resolve()}_onCancel(e){this.logger.log("Invitation._onCancel"),this.state===u.a.Initial||this.state===u.a.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(u.a.Terminated)):this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Object(r.getBody)(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case r.SignalingState.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case r.SignalingState.Stable:return this.setAnswer(t,s).then(()=>{});case r.SignalingState.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case r.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case r.SignalingState.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof a.a?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof c.a?this.logger.error("A session description handler occurred while sending response"):e instanceof d.a?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof i.a&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===u.a.Initial||this.state===u.a.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(u.a.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(u.a.Terminated)}sendAccept(){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,e)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),n=e.body?Object(r.fromBodyLegacy)(e.body):void 0;if(183===t&&!n)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:r,extraHeaders:i,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();let o;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(o=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:r,extraHeaders:i,body:o}))).then(t=>{let c,h;this._dialog=t.session,t.session.delegate={onPrack:s=>{c=s,clearTimeout(u),clearTimeout(p),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(c).then(s=>{try{h=c.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:c,prackResponse:h,progressResponse:t})}catch(e){a(e)}}).catch(e=>a(e)))}};const u=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(p),this.reject({statusCode:504}).then(()=>a(new d.a)).catch(e=>a(e)))},64*n.a.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:r,extraHeaders:i,body:o})}catch(e){return this.waitingForPrack=!1,void a(e)}p=setTimeout(l,g*=2)};let g=n.a.T1,p=setTimeout(l,g)}).catch(e=>{this.waitingForPrack=!1,a(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new d.a),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}getDescription(e,t){var s,r;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const i=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(r=this.sessionDescriptionHandlerConfiguration)||void 0===r?void 0:r.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(i,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const r=s[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,i,n)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:r},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],n=e=>{const n=e.kind;if("audio"!==n&&"video"!==n)throw new Error(`Unknown new track kind ${n}.`);const o=t.getSenders().find(e=>e.track&&e.track.kind===n);o?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${n} track`),e()}).then(()=>o.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===n);t&&(t.stop(),s.removeTrack(t),r.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),r.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${n} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${n} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${n} track`),e}s.addTrack(e),r.dispatchAddTrackEvent(s,e)}))},o=e.getAudioTracks();o.length&&n(o[0]);const a=e.getVideoTracks();return a.length&&n(a[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;case"have-local-pranswer":case"have-remote-offer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),r.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),r.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),r.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),r.dispatchAddTrackEvent(t,e))}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const r=e.connectionState;this.logger.debug("SessionDescriptionHandler.onconnectionstatechange "+r),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const r=e.iceConnectionState;this.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange "+r),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const r=e.iceGatheringState;this.logger.debug("SessionDescriptionHandler.onicegatheringstatechange "+r),"complete"===r&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const r=e.signalingState;this.logger.debug("SessionDescriptionHandler.onsignalingstatechange "+r),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.onstatsended=e=>{var t;this.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onstatsended)&&this._peerConnectionDelegate.onstatsended(e)},e.ontrack=e=>{var t;const s=e.track.kind,r=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${r}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}},function(e,t,s){"use strict";var r=s(50);s.d(t,"a",(function(){return r.a}));var i=s(23);s.d(t,"b",(function(){return i.a}));var n=s(39);s.d(t,"c",(function(){return n.a}));var o=s(45);s.d(t,"d",(function(){return o.a}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return f}));var r=s(2),i=s(6),n=s(21),o=s(66),a=s(18),c=s(47),d=s(58),h=s(67),u=s(44),l=s(29),g=s(79),p=s(1);class f{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=p.a.Initial,this.delegate=t.delegate,this._stateEventEmitter=new a.a,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case p.a.Initial:case p.a.Establishing:break;case p.a.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case p.a.Terminating:case p.a.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case p.a.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case p.a.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case p.a.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case p.a.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case p.a.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error("Invalid session state "+this.state))}info(e={}){if(this.state!==p.a.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==p.a.Established)return Promise.reject(new Error("Invalid session state "+this.state));if(this.pendingReinvite)return Promise.reject(new c.a("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=Object(r.getBody)(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(p.a.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,r).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===p.a.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(p.a.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,r).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==p.a.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(p.a.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==p.a.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+n.a.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==p.a.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==p.a.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const s=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return r.extraHeaders=r.extraHeaders?r.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,s,r)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case r.SessionState.Initial:case r.SessionState.Early:throw new Error("Invalid dialog state "+s.sessionState);case r.SessionState.AckWait:return this.stateTransition(p.a.Terminating),new Promise(r=>{s.delegate={onAck:()=>{const i=s.bye(e,t);return this.stateTransition(p.a.Terminated),r(i),Promise.resolve()},onAckTimeout:()=>{const i=s.bye(e,t);this.stateTransition(p.a.Terminated),r(i)}}});case r.SessionState.Confirmed:{const r=s.bye(e,t);return this.stateTransition(p.a.Terminated),Promise.resolve(r)}case r.SessionState.Terminated:throw new Error("Invalid dialog state "+s.sessionState);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:r})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==p.a.Established&&this.state!==p.a.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};switch(this.pendingReinviteAck=!1,t.signalingState){case r.SignalingState.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated),Promise.resolve()}case r.SignalingState.Stable:{const i=Object(r.getBody)(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(p.a.Terminated)}):Promise.resolve()}case r.SignalingState.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated),Promise.resolve()}case r.SignalingState.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated),Promise.resolve()}case r.SignalingState.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===p.a.Established){if(this.delegate&&this.delegate.onBye){const t=new o.a(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(p.a.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===p.a.Established)if(this.delegate&&this.delegate.onInfo){const t=new h.a(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==p.a.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=r.Grammar.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const r=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,200)}).catch(s=>{if(this.logger.error(s.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState!==r.SignalingState.Stable)this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(s=>{this.logger.error(s.message),this.logger.error("Failed to rollback offer on re-INVITE request");const r=e.reject({statusCode:488});if(this.state!==p.a.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(p.a.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,488)});else{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===p.a.Established)if(this.delegate&&this.delegate.onMessage){const t=new u.a(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===p.a.Established)if(this.onNotify){const t=new l.a(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new l.a(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===p.a.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==p.a.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new g.a(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=Object(r.getBody)(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case r.SignalingState.Initial:return this.getOffer(e);case r.SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case r.SignalingState.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case r.SignalingState.Stable:return this.state!==p.a.Established?Promise.resolve(void 0):this.getOffer(e);case r.SignalingState.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>Object(r.fromBodyLegacy)(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new d.a)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,r,i).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,n=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new d.a)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,n).then(()=>s.getDescription(i,n)).then(e=>Object(r.fromBodyLegacy)(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case p.a.Initial:e!==p.a.Establishing&&e!==p.a.Established&&e!==p.a.Terminating&&e!==p.a.Terminated&&t();break;case p.a.Establishing:e!==p.a.Established&&e!==p.a.Terminating&&e!==p.a.Terminated&&t();break;case p.a.Established:e!==p.a.Terminating&&e!==p.a.Terminated&&t();break;case p.a.Terminating:e!==p.a.Terminated&&t();break;case p.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===p.a.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let r=Object(i.b)(e);return!r&&t&&(r=t),"SIP;cause="+s+';text="'+r+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof r.URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),i=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${r}?Replaces=${encodeURIComponent(`${i};to-tag=${n};from-tag=${o}`)}>`}return t}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(40);class i extends r.a{constructor(){super()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return c}));var r=s(2),i=s(6),n=s(34),o=s(1),a=s(22);class c extends n.a{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=Object(i.d)(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const n=Object.assign({},s);n.params=Object.assign({},s.params);const o=s.anonymous||!1,c=e.contact.toString({anonymous:o,outbound:o?!e.contact.tempGruu:!e.contact.pubGruu});o&&e.configuration.uri&&(n.params.fromDisplayName="Anonymous",n.params.fromUri="sip:anonymous@anonymous.invalid");let d=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(d="string"==typeof n.params.fromUri?r.Grammar.URIParse(n.params.fromUri):n.params.fromUri),!d)throw new TypeError("Invalid from URI: "+n.params.fromUri);let h=t;if(n.params.toUri&&(h="string"==typeof n.params.toUri?r.Grammar.URIParse(n.params.toUri):n.params.toUri),!h)throw new TypeError("Invalid to URI: "+n.params.toUri);const u=Object.assign({},n.params);u.fromTag=this.fromTag;const l=(n.extraHeaders||[]).slice();o&&e.configuration.uri&&(l.push("P-Preferred-Identity: "+e.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+c),l.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===a.a.Required&&l.push("Require: 100rel"),e.configuration.sipExtensionReplaces===a.a.Required&&l.push("Require: replaces"),n.extraHeaders=l;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(r.C.INVITE,t,d,h,u,l,void 0),this._contact=c,this._referralInviterOptions=n,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case o.a.Initial:case o.a.Establishing:return this.cancel().then(()=>super.dispose());case o.a.Established:case o.a.Terminating:case o.a.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==o.a.Initial&&this.state!==o.a.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(o.a.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e){return"SIP;cause="+e+';text="'+(Object(i.b)(e)||t)+'"'}}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(o.a.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==o.a.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(o.a.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(o.a.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.stateTransition(o.a.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(o.a.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof n.a))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==o.a.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error("Invalid session state "+this.state));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=r.Grammar.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case r.SignalingState.Initial:case r.SignalingState.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(o.a.Terminated),Promise.reject(new Error("Bad Media Description"));case r.SignalingState.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(o.a.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(o.a.Terminated),t})}case r.SignalingState.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(o.a.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(o.a.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(o.a.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,r).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(o.a.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(o.a.Terminated),t})}case r.SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==o.a.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error("Invalid session state "+this.state));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=r.Grammar.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const n=s.getHeader("require"),a=s.getHeader("rseq"),c=!!(n&&n.includes("100rel")&&a?Number(a):void 0),d=[];switch(c&&d.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case r.SignalingState.Initial:return c&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:d})),Promise.resolve();case r.SignalingState.HaveLocalOffer:return c&&e.prack({extraHeaders:d}),Promise.resolve();case r.SignalingState.HaveRemoteOffer:if(!c)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:d,body:s})}).catch(e=>{throw this.stateTransition(o.a.Terminated),e})}case r.SignalingState.Stable:if(c&&e.prack({extraHeaders:d}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(o.a.Terminated),e})}return Promise.resolve();case r.SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===o.a.Establishing||this.state===o.a.Terminating?this.stateTransition(o.a.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===o.a.Establishing||this.state===o.a.Terminating?this.stateTransition(o.a.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===o.a.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"An error occurred during state transition.")}}},function(e,t,s){"use strict";var r=s(58);s.d(t,"a",(function(){return r.a}));var i=s(47);s.d(t,"b",(function(){return i.a}));var n=s(90);s.d(t,"c",(function(){return n.a}));var o=s(59);s.d(t,"d",(function(){return o.a}));var a=s(37);s.d(t,"e",(function(){return a.a}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())}deleteParam(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(50),i=s(6);class n{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=Object(i.c)(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[Object(i.c)(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Object(i.c)(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[Object(i.c)(e)]}parseHeader(e,t=0){if(e=Object(i.c)(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const s=this.headers[e][t],n=s.raw;if(s.parsed)return s.parsed;const o=r.a.parse(n,e.replace(/-/g,"_"));return-1===o?void this.headers[e].splice(t,1):(s.parsed=o,o)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[Object(i.c)(e)]=[{raw:t}]}toString(){return this.data}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(42);class i extends r.a{constructor(e,t,s,r,i){super(t,s,e.viaBranch,r,i),this._request=e,this.user=s}get request(){return this._request}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(60);class i{constructor(e,t,s,r,i){this._transport=e,this._user=t,this._id=s,this._state=r,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof r.a)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new r.a(e.message):new r.a,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(42);class i extends r.a{constructor(e,t,s,r,n){super(t,s,i.makeId(e),r,n),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(39);class i extends r.a{constructor(e,t,s,r,i,n){if(super(i),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');e=e||"sip";for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:r},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:r}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new i(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),r=s.length;let i="";for(let e=0;e{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=["Retry-After: "+(Math.floor(10*Math.random())+1)];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==d.b.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===r.C.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof i.a))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case r.C.BYE:{const t=new f.a(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case r.C.INFO:{const t=new v.a(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info :"]})}break;case r.C.INVITE:{const t=new I.a(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case r.C.MESSAGE:{const t=new w.a(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case r.C.NOTIFY:{const t=new T.a(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case r.C.PRACK:{const t=new R.a(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case r.C.REFER:{const t=new $.a(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof l.a)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),r=t&&t.includes("100rel")&&s?Number(s):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0}signalingStateRollback(){this._signalingState!==d.b.HaveLocalOffer&&this.signalingState!==d.b.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=d.b.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Object(n.b)(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===d.b.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof o.a)switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.HaveRemoteOffer:case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof a.a)switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.HaveRemoteOffer:case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof c.a)switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:break;case d.b.HaveRemoteOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Object(n.c)(e))switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:break;case d.b.HaveRemoteOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof u.a){const e=this.initialTransaction;let t=h.a.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,h.a.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const r=()=>{e.state===g.a.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(r)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof u.a){const e=this.reinviteUserAgentServer.transaction;let t=h.a.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,h.a.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const r=()=>{e.state===g.a.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(r)}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return v}));var r=s(2),i=s(91),n=s(15),o=s(6),a=s(100),c=s(86),d=s(83),h=s(18),u=s(31),l=s(36),g=s(44),p=s(29),f=s(22),m=s(16);class v{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=m.a.Stopped,this.unloadListener=()=>{this.stop()},this._stateEventEmitter=new h.a,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},v.defaultOptions()),{sipjsId:Object(o.a)(5)}),{uri:new r.URI("sip","anonymous."+Object(o.a)(6),"anonymous.invalid")}),{viaHost:Object(o.a)(12)+".invalid"}),v.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new i.a,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=n.a.error;break;case"warn":this.loggerFactory.level=n.a.warn;break;case"log":this.loggerFactory.level=n.a.log;break;case"debug":this.loggerFactory.level=n.a.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+e+": "+t);break;case"authorizationPassword":this.logger.log("\xb7 "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+e+": "+t.name);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,r=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==r&&(this.options.reconnectionDelay=r),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._userAgentCore=this.initCore(),this.options.autoStart&&this.start()}static makeURI(e){return r.Grammar.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,hackWssInTransport:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sessionDescriptionHandlerFactory:Object(a.a)(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:f.a.Unsupported,sipExtensionReplaces:f.a.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:c.a,transportOptions:{},uri:new r.URI("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/"+d.a,viaHost:""}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===m.a.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){if(this.state===m.a.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting "+this.configuration.uri),this.transitionState(m.a.Started),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this.transport.connect()}async stop(){if(this.state===m.a.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log("Stopping "+this.configuration.uri),this.transitionState(m.a.Stopped),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)}const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),r=Object.assign({},this._subscriptions),i=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in r)r[e]&&await r[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await i.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose()}_makeInviter(e,t){return new l.a(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=Object(o.a)(8),t=this.options.hackWssInTransport?"wss":"ws";return{pubGruu:void 0,tempGruu:void 0,uri:new r.URI("sip",e,this.options.viaHost,void 0,{transport:t}),toString:(e={})=>{const s=e.anonymous||!1,r=e.outbound||!1;let i="<";return i+=s?this.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport="+t:this.contact.pubGruu||this.contact.uri,r&&(i+=";ob"),i+=">",i}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===f.a.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===f.a.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>f.b[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new r.DigestAuthentication(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport},i={onInvite:e=>{var t;const s=new u.a(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==f.a.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const r=t.replaces_to_tag;if("string"!=typeof r)throw new Error("Type of to tag is not string");const i=t.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const n=e+r+i,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+i]||this._sessions[e+r]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new g.a(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new p.a(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}};return new r.UserAgentCore(s,i)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==m.a.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==m.a.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=r.Parser.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===m.a.Stopped&&t instanceof r.IncomingRequestMessage)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof r.IncomingRequestMessage){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=Object(o.e)(t.body),r=t.getHeader("content-length");if(r&&e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=Object(o.e)(t.body),r=t.getHeader("content-length");if(r&&e{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case m.a.Started:e!==m.a.Stopped&&s();break;case m.a.Stopped:e!==m.a.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(23),i=s(45);class n extends Error{constructor(e,t,s,r){super(),this.message=e,this.expected=t,this.found=s,this.location=r,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,n)}static buildMessage(e,t){function s(e){return e.charCodeAt(0).toString(16).toUpperCase()}function r(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(n);let s,r;if(t.sort(),t.length>0){for(s=1,r=1;s",w(">",!1),"\\",w("\\",!1),"[",w("[",!1),"]",w("]",!1),"{",w("{",!1),"}",w("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,S([["!","'"]],!1,!1),/^[*-[]/,S([["*","["]],!1,!1),/^[\]-~]/,S([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,S([["#","["]],!1,!1),/^[\0-\t]/,S([["\0","\t"]],!1,!1),/^[\x0B-\f]/,S([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,S([["\x0e","\x7f"]],!1,!1),function(){(t=t||{data:{}}).data.uri=new i.a(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new i.a(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",w("sips",!0),"sip",w("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(v().slice(0,-1))},function(){(t=t||{data:{}}).data.password=v()},function(){return(t=t||{data:{}}).data.host=v(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",v()},/^[a-zA-Z0-9_\-]/,S([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,S([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",w("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",w("25",!1),/^[0-5]/,S([["0","5"]],!1,!1),"2",w("2",!1),/^[0-4]/,S([["0","4"]],!1,!1),"1",w("1",!1),/^[1-9]/,S([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",w("transport=",!0),"udp",w("udp",!0),"tcp",w("tcp",!0),"sctp",w("sctp",!0),"tls",w("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",w("user=",!0),"phone",w("phone",!0),"ip",w("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",w("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",w("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",w("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",w("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new i.a(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",w("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},w("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",w("INVITE",!1),"ACK",w("ACK",!1),"VXACH",w("VXACH",!1),"OPTIONS",w("OPTIONS",!1),"BYE",w("BYE",!1),"CANCEL",w("CANCEL",!1),"REGISTER",w("REGISTER",!1),"SUBSCRIBE",w("SUBSCRIBE",!1),"NOTIFY",w("NOTIFY",!1),"REFER",w("REFER",!1),"PUBLISH",w("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=v(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=v()},function(){(t=t||{data:{}}).data=v()},function(){var e,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),I(";).# &;,"),I('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),I('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),I('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),I(';.." &"'),I("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),I('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I('4\\""5!7].# &;3'),I('4^""5!7_'),I('4`""5!7a'),I(';!.) &4b""5!7c'),I('%$;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x9e#0\x9b*;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),I('%$;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x92#0\x8f*;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),I('2T""6T7U.\xe3 &2V""6V7W.\xd7 &2f""6f7g.\xcb &2h""6h7i.\xbf &2:""6:7;.\xb3 &2D""6D7E.\xa7 &22""6273.\x9b &28""6879.\x8f &2j""6j7k.\x83 &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),I('%$;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/\u0134#0\u0131*;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),I("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),I("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),I("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),I("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),I("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),I('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),I('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),I("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),I("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),I("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),I("%;//0#;&/'$8\":~\" )(\"'#&'#"),I("%;&/0#;//'$8\":~\" )(\"'#&'#"),I("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),I('4\x7f""5!7\x80.A &4\x81""5!7\x82.5 &4\x83""5!7\x84.) &;3.# &;.'),I("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),I("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"),I(';..G &2L""6L7M.; &4\x86""5!7\x87./ &4\x83""5!7\x84.# &;3'),I('%2j""6j7k/J#4\x88""5!7\x89.5 &4\x8a""5!7\x8b.) &4\x8c""5!7\x8d/#$+")("\'#&\'#'),I("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8e$ )($'#(#'#(\"'#&'#"),I("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8f& )(&'#(%'#($'#(#'#(\"'#&'#"),I('%3\x90""5$7\x91.) &3\x92""5#7\x93/\' 8!:\x94!! )'),I('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:\x95# )(#\'#("\'#&\'#'),I("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),I('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),I('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:\x96! )'),I('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:\x97! )"),I('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:\x98# )(#\'#("\'#&\'#'),I('$4\x99""5!7\x9a/,#0)*4\x99""5!7\x9a&&&#'),I('%4$""5!7%/?#$4\x9b""5!7\x9c0)*4\x9b""5!7\x9c&/#$+")("\'#&\'#'),I('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:\x9d# )(#\'#("\'#&\'#'),I('%%;Z/\xb3#28""6879/\xa4$;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0790 &%2\x9e""6\x9e7\x9f/\xa4#;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u06f9 &%2\x9e""6\x9e7\x9f/\x8c#;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u067a &%2\x9e""6\x9e7\x9f/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0613 &%2\x9e""6\x9e7\x9f/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u05c4 &%2\x9e""6\x9e7\x9f/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.\u058d &%2\x9e""6\x9e7\x9f/,#;[/#$+")("\'#&\'#.\u056e &%2\x9e""6\x9e7\x9f/,#;Z/#$+")("\'#&\'#.\u054f &%;Z/\x9b#2\x9e""6\x9e7\x9f/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u04c7 &%;Z/\xaa#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x83$2\x9e""6\x9e7\x9f/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0430 &%;Z/\xb9#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x92$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2\x9e""6\x9e7\x9f/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u038a &%;Z/\xc8#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa1$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2\x9e""6\x9e7\x9f/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u02d5 &%;Z/\xd7#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0211 &%;Z/\xfe#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xd7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0126 &%;Z/\u011c#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xf5$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xce$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x80$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2\x9e""6\x9e7\x9f/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!:\xa0! )'),I('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),I("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xa1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),I('%2\xa2""6\xa27\xa3/2#4\xa4""5!7\xa5/#$+")("\'#&\'#.\x98 &%2\xa6""6\xa67\xa7/;#4\xa8""5!7\xa9/,$;!/#$+#)(#\'#("\'#&\'#.j &%2\xaa""6\xaa7\xab/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4\xac""5!7\xad/,#;!/#$+")("\'#&\'#.# &;!'),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\xae!! )'),I('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),I(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),I('%3\xaf""5*7\xb0/a#3\xb1""5#7\xb2.G &3\xb3""5#7\xb4.; &3\xb5""5$7\xb6./ &3\xb7""5#7\xb8.# &;6/($8":\xb9"! )("\'#&\'#'),I('%3\xba""5%7\xbb/I#3\xbc""5%7\xbd./ &3\xbe""5"7\xbf.# &;6/($8":\xc0"! )("\'#&\'#'),I('%3\xc1""5\'7\xc2/1#;\x90/($8":\xc3"! )("\'#&\'#'),I('%3\xc4""5$7\xc5/1#;\xf0/($8":\xc6"! )("\'#&\'#'),I('%3\xc7""5&7\xc8/1#;T/($8":\xc9"! )("\'#&\'#'),I('%3\xca""5"7\xcb/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":\xcc" )("\'#&\'#'),I('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":\xcd""! )("\'#&\'#'),I('%$;j/�#*;j&&&#/"!&,)'),I('%$;j/�#*;j&&&#/"!&,)'),I(";k.) &;+.# &;-"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),I('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),I('%;n/A#2>""6>7?/2$;o/)$8#:\xce#"" )(#\'#("\'#&\'#'),I("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),I("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),I(";\x91.# &;r"),I("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"),I(";M.# &;t"),I("%;\x7f/E#28\"\"6879/6$;u.# &;x/'$8#:\xcf# )(#'#(\"'#&'#"),I('%;v.# &;w/J#%26""6677/,#;\x83/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I('%2\xd0""6\xd07\xd1/:#;\x80/1$;w." &"/#$+#)(#\'#("\'#&\'#'),I('%24""6475/,#;{/#$+")("\'#&\'#'),I("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),I(";*.) &;+.# &;-"),I(';+.\x8f &;-.\x89 &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),I('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I("$;~0#*;~&"),I(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),I('%%;"/\x87#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:\xd2! )'),I(";\x81.# &;\x82"),I('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),I('$;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/\x8c#0\x89*;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),I("$;y0#*;y&"),I('%3\x92""5#7\xd3/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:\xd4% )(%\'#($\'#(#\'#("\'#&\'#'),I('2\xd5""6\xd57\xd6'),I('2\xd7""6\xd77\xd8'),I('2\xd9""6\xd97\xda'),I('2\xdb""6\xdb7\xdc'),I('2\xdd""6\xdd7\xde'),I('2\xdf""6\xdf7\xe0'),I('2\xe1""6\xe17\xe2'),I('2\xe3""6\xe37\xe4'),I('2\xe5""6\xe57\xe6'),I('2\xe7""6\xe77\xe8'),I('2\xe9""6\xe97\xea'),I("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8a.A &;\x8b.; &;\x8c.5 &;\x8f./ &;\x8d.) &;\x8e.# &;6/& 8!:\xeb! )"),I("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%;\x93/' 8!:\xec!! )"),I("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),I("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xed! )"),I("%;\xb6/Y#$%;A/,#;\xb6/#$+\")(\"'#&'#06*%;A/,#;\xb6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":\xee" )("\'#&\'#'),I("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xef! )"),I("%;L.# &;\x99/]#$%;B/,#;\x9b/#$+\")(\"'#&'#06*%;B/,#;\x9b/#$+\")(\"'#&'#&/'$8\":\xf0\" )(\"'#&'#"),I("%;\x9a.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),I("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xf1!! )"),I(";\x9c.) &;\x9d.# &;\xa0"),I("%3\xf2\"\"5!7\xf3/:#;$;\xcf/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%$;!/�#*;!&&&#/' 8!:\u014b!! )"),I("%;\xd1/]#$%;A/,#;\xd1/#$+\")(\"'#&'#06*%;A/,#;\xd1/#$+\")(\"'#&'#&/'$8\":\u014c\" )(\"'#&'#"),I("%;\x99/]#$%;B/,#;\xa0/#$+\")(\"'#&'#06*%;B/,#;\xa0/#$+\")(\"'#&'#&/'$8\":\u014d\" )(\"'#&'#"),I('%;L.O &;\x99.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#;\xa0/#$+")("\'#&\'#06*%;B/,#;\xa0/#$+")("\'#&\'#&/\'$8":\u014e" )("\'#&\'#'),I("%;\xd4/]#$%;B/,#;\xd5/#$+\")(\"'#&'#06*%;B/,#;\xd5/#$+\")(\"'#&'#&/'$8\":\u014f\" )(\"'#&'#"),I("%;\x96/& 8!:\u0150! )"),I('%3\u0151""5(7\u0152/:#;$;6/5$;;/,$;\xec/#$+%)(%'#($'#(#'#(\"'#&'#"),I('%3\x92""5#7\xd3.# &;6/\' 8!:\u018b!! )'),I('%3\xb1""5#7\u018c.G &3\xb3""5#7\u018d.; &3\xb7""5#7\u018e./ &3\xb5""5$7\u018f.# &;6/\' 8!:\u0190!! )'),I('%;\xee/D#%;C/,#;\xef/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:\u0191! )"),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\u0192!! )'),I('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:\u0193!! )'),I(";\xbe"),I('%;\x9e/^#$%;B/,#;\xf3/#$+")("\'#&\'#06*%;B/,#;\xf3/#$+")("\'#&\'#&/($8":\u0194"!!)("\'#&\'#'),I(";\xf4.# &;\xa0"),I('%2\u0195""6\u01957\u0196/L#;""6>7?'),I('%;\u0100/b#28""6879/S$;\xfb/J$%2\u01a3""6\u01a37\u01a4/,#;\xec/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I('%3\u01a5""5%7\u01a6.) &3\u01a7""5$7\u01a8/\' 8!:\u01a1!! )'),I('%3\xb1""5#7\xb2.6 &3\xb3""5#7\xb4.* &$;+0#*;+&/\' 8!:\u01a9!! )'),I("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01aa) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),I("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),I("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"),I("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"),I("%;q/T#$;m0#*;m&/D$%; /,#;\xf8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),I('%2\u01ab""6\u01ab7\u01ac.) &2\u01ad""6\u01ad7\u01ae/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#0<*%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),I(";\x99.# &;L"),I("%2\u01af\"\"6\u01af7\u01b0/5#;p&&(p=h,f=[]),f.push(e))}function y(e,t,s){return new n(n.buildMessage(e,t),e,t,s)}function I(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},g=function t(r){const i=d[r];let n=0;const o=[];let a=i.length;const l=[],g=[];let p;for(;;){for(;nh?(a=n+3+i[n+1],n+=3):(a=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 18:l.push(a),o.push(n+4+i[n+2]+i[n+3]),e.substr(h,c[i[n+1]].length)===c[i[n+1]]?(a=n+4+i[n+2],n+=4):(a=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 19:l.push(a),o.push(n+4+i[n+2]+i[n+3]),e.substr(h,c[i[n+1]].length).toLowerCase()===c[i[n+1]]?(a=n+4+i[n+2],n+=4):(a=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 20:l.push(a),o.push(n+4+i[n+2]+i[n+3]),c[i[n+1]].test(e.charAt(h))?(a=n+4+i[n+2],n+=4):(a=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 21:g.push(e.substr(h,i[n+1])),h+=i[n+1],n+=2;break;case 22:g.push(c[i[n+1]]),h+=c[i[n+1]].length,n+=2;break;case 23:g.push(s),0===m&&R(c[i[n+1]]),n+=2;break;case 24:u=g[g.length-1-i[n+1]],n+=2;break;case 25:u=h,n++;break;case 26:p=i.slice(n+4,n+4+i[n+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-i[n+2],i[n+2],c[i[n+1]].apply(null,p)),n+=4+i[n+3];break;case 27:g.push(t(i[n+1])),n+=2;break;case 28:m++,n++;break;case 29:m--,n++;break;default:throw new Error("Invalid opcode: "+i[n]+".")}if(!(l.length>0))break;a=l.pop(),n=o.pop()}return g[0]}(a),g!==s&&h===e.length)return g;throw g!==s&&h=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))switch(super.receiveRequest(e),e.method){case i.C.NOTIFY:this.onNotify(e);break;default:this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+a.a.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){if(this.subscriptionState!==n.a.Pending&&this.subscriptionState!==n.a.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const s=new d.a(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(()=>this.timerN(),o.a.TIMER_N),s}terminate(){this.stateTransition(n.a.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+a.a.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const r=s.state,i=s.expires?Math.max(s.expires,0):void 0;switch(r){case"pending":this.stateTransition(n.a.Pending,i);break;case"active":this.stateTransition(n.a.Active,i);break;case"terminated":this.stateTransition(n.a.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const o=new c.a(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case n.a.Initial:case n.a.NotifyWait:return void s();case n.a.Pending:if(this.subscriptionState!==n.a.NotifyWait&&this.subscriptionState!==n.a.Pending)return void s();break;case n.a.Active:case n.a.Terminated:if(this.subscriptionState!==n.a.NotifyWait&&this.subscriptionState!==n.a.Pending&&this.subscriptionState!==n.a.Active)return void s();break;default:return void s()}e===n.a.Pending&&t&&(this.subscriptionExpires=t),e===n.a.Active&&t&&(this.subscriptionExpires=t),e===n.a.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==n.a.Terminated&&(this.stateTransition(n.a.Terminated),this.onTerminated())}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(15);class i{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(r.a.error,e)}warn(e){this.genericLog(r.a.warn,e)}log(e){this.genericLog(r.a.log,e)}debug(e){this.genericLog(r.a.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Unsupported content type.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(){super("The session has terminated.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Unspecified transport error.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return h}));var r=s(26),i=s(48),n=s(28),o=s(4),a=s(17),c=s(21),d=s(13);class h extends d.a{constructor(e,t,s){super(a.a,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new n.a(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof a.a))throw new Error("Transaction not instance of InviteClientTransaction.");const t=r.a.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new i.a(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact.toString(),d="Allow: "+c.a.toString();if(!e.body)if(this.confirmedDialog.signalingState===o.b.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===o.b.Initial||this.confirmedDialog.signalingState===o.b.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(d),e.extraHeaders.push(s);const h=super.accept(e),u=this.confirmedDialog,l=Object.assign(Object.assign({},h),{session:u});return e.body&&this.confirmedDialog.signalingState!==o.b.Stable&&this.confirmedDialog.signalingStateTransition(e.body),l}progress(e={statusCode:180}){if(!this.progressable)throw new n.a(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof a.a))throw new Error("Transaction not instance of InviteClientTransaction.");const t=r.a.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new i.a(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const c=super.progress(e),d=this.earlyDialog,h=Object.assign(Object.assign({},c),{session:d});return e.body&&this.earlyDialog.signalingState!==o.b.Stable&&this.earlyDialog.signalingStateTransition(e.body),h}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}},function(e,t,s){"use strict";s.r(t);var r=s(26);s.d(t,"Dialog",(function(){return r.a}));var i=s(123);for(var n in i)["Dialog","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(48);s.d(t,"SessionDialog",(function(){return o.a}));var a=s(56);s.d(t,"SubscriptionDialog",(function(){return a.a}))},function(e,t,s){"use strict";s.r(t);var r=s(8);s.d(t,"SubscriptionState",(function(){return r.a}));var i=s(126);for(var n in i)["SubscriptionState","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n)},function(e,t,s){"use strict";s.r(t);var r=s(81);s.d(t,"defaultMediaStreamFactory",(function(){return r.a}));var i=s(164);for(var n in i)["defaultMediaStreamFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(82);s.d(t,"defaultPeerConnectionConfiguration",(function(){return o.a}));var a=s(165);for(var n in a)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(n);var c=s(166);for(var n in c)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return c[e]}))}(n);var d=s(100);s.d(t,"defaultSessionDescriptionHandlerFactory",(function(){return d.a}));var h=s(167);for(var n in h)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(n);var u=s(168);for(var n in u)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return u[e]}))}(n);var l=s(169);for(var n in l)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(n);var g=s(32);s.d(t,"SessionDescriptionHandler",(function(){return g.a}))},function(e,t,s){"use strict";s.r(t);var r=s(86);s.d(t,"Transport",(function(){return r.a}));var i=s(174);for(var n in i)["Transport","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n)},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.BYE,s);super(i.a,e.userAgentCore,n,t),e.dispose()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.INFO,s);super(i.a,e.userAgentCore,n,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(24),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.INVITE,s);super(i.a,e.userAgentCore,n,t),this.delegate=t,e.signalingStateTransition(n),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.NOTIFY,s);super(i.a,e.userAgentCore,n,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.PRACK,s);super(i.a,e.userAgentCore,n,t),e.signalingStateTransition(n)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.REFER,s);super(i.a,e.userAgentCore,n,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(17),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>"Record-Route: "+e));const t=super.accept(e),s=this.dialog,r=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),r}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,r=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),r}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.SUBSCRIBE,s);super(i.a,e.userAgentCore,n,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(2);class i{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof r.NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){return this.referTo.uri.getHeader("replaces")}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&s.push("Replaces: "+decodeURIComponent(r));const i=this.referredBy;return i&&s.push("Referred-By: "+i),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(18),i=s(14);class n{constructor(e,t={}){this._disposed=!1,this._state=i.a.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new r.a,this._userAgent=e,this.delegate=t.delegate}dispose(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()}get dialog(){return this._dialog}get disposed(){return this._disposed}get state(){return this._state}get stateChange(){return this._stateEventEmitter}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case i.a.Initial:e!==i.a.NotifyWait&&e!==i.a.Terminated&&t();break;case i.a.NotifyWait:e!==i.a.Subscribed&&e!==i.a.Terminated&&t();break;case i.a.Subscribed:e!==i.a.Terminated&&t();break;case i.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log(`Subscription ${this._dialog?this._dialog.id:void 0} transitioned to ${this._state}`),this._stateEventEmitter.emit(this._state),e===i.a.Terminated&&this.dispose())}}},function(e,t,s){"use strict";function r(){return e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream)}s.d(t,"a",(function(){return r}))},function(e,t,s){"use strict";function r(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}}s.d(t,"a",(function(){return r}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));const r="0.17.1"},function(e,t,s){"use strict";s.d(t,"a",(function(){return a})),s.d(t,"c",(function(){return c})),s.d(t,"b",(function(){return d}));var r=s(35),i=s(27),n=s(46);function o(e){return"application/sdp"===e?"session":"render"}function a(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:o(s),contentType:s,content:t}}function c(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function d(e){let t,s,a;if(e instanceof r.a&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),a=e.body}if(e instanceof i.a&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),a=e.body}if(e instanceof n.a&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");a=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,a=e.body.body}if(c(e)&&(t=e.contentDisposition,s=e.contentType,a=e.content),a){if(s&&!t&&(t=o(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:a}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(6);function i(e,t){if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const s=t.reasonPhrase?t.reasonPhrase:Object(r.b)(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+s+"\r\n";t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+"\r\n",o="Call-ID: "+e.callId+"\r\n",a="CSeq: "+e.cseq+" "+e.method+"\r\n",c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+"\r\n","");let d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Object(r.d)()),d+=";tag="+e}d+="\r\n";let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+"\r\n");let u="";t.userAgent&&(u="User-Agent: "+t.userAgent+"\r\n");let l="";return t.extraHeaders&&(l=t.extraHeaders.reduce((e,t)=>e+t.trim()+"\r\n","")),i+=c,i+=n,i+=d,i+=a,i+=o,i+=h,i+=u,i+=l,t.body?(i+="Content-Type: "+t.body.contentType+"\r\n",i+="Content-Length: "+Object(r.e)(t.body.content)+"\r\n\r\n",i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(18),i=s(37),n=s(5),o=s(2);class a{constructor(e,t){if(this._state=n.a.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new r.a,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,r=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},a.defaultOptions),t);const s=this.configuration.server,i=o.Grammar.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===n.a.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log("Connecting "+this.server),this.state){case n.a.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case n.a.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case n.a.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(n.a.Connecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;case n.a.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(n.a.Connecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(n.a.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log("Disconnecting "+this.server),this.state){case n.a.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(n.a.Disconnecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;case n.a.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(n.a.Disconnecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;case n.a.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case n.a.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==n.a.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,r=this.disconnectPromise?void 0:new Error(s);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(n.a.Disconnected,r)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let r;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{r=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+r+"\n")}else r=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+r+"\n");if(this.state===n.a.Connected){if(this.onMessage)try{this.onMessage(r)}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===n.a.Connecting&&(this.logger.log("WebSocket opened "+this.server),this.transitionState(n.a.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new i.a("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case n.a.Connecting:e!==n.a.Connected&&e!==n.a.Disconnecting&&e!==n.a.Disconnected&&s();break;case n.a.Connected:e!==n.a.Disconnecting&&e!==n.a.Disconnected&&s();break;case n.a.Disconnecting:e!==n.a.Connecting&&e!==n.a.Disconnected&&s();break;case n.a.Disconnected:e!==n.a.Connecting&&s();break;default:throw new Error("Unknown state.")}const r=this._state;this._state=e;const i=this.connectResolve,o=this.connectReject;r===n.a.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const a=this.disconnectResolve,c=this.disconnectReject;if(r===n.a.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${r} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===n.a.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onConnect callback"),e}if(r===n.a.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onDisconnect callback"),e}if(r===n.a.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===n.a.Connected?i():o(t||new Error("Connect aborted."))}if(r===n.a.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!c)throw new Error("Disconnect reject undefined.");e===n.a.Disconnected?a():c(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}a.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0}},function(e,t,s){"use strict";s.r(t);var r=s(38);s.d(t,"ContentTypeUnsupportedError",(function(){return r.a})),s.d(t,"RequestPendingError",(function(){return r.b})),s.d(t,"SessionDescriptionHandlerError",(function(){return r.c})),s.d(t,"SessionTerminatedError",(function(){return r.d})),s.d(t,"StateTransitionError",(function(){return r.e}));var i=s(66);s.d(t,"Bye",(function(){return i.a}));var n=s(18);s.d(t,"EmitterImpl",(function(){return n.a}));var o=s(67);s.d(t,"Info",(function(){return o.a}));var a=s(102);for(var c in a)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(c);var d=s(103);for(var c in d)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return d[e]}))}(c);var h=s(104);for(var c in h)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(c);var u=s(31);s.d(t,"Invitation",(function(){return u.a}));var l=s(133);for(var c in l)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(c);var g=s(134);for(var c in g)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return g[e]}))}(c);var p=s(135);for(var c in p)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(c);var f=s(36);s.d(t,"Inviter",(function(){return f.a}));var m=s(44);s.d(t,"Message",(function(){return m.a}));var v=s(136);for(var c in v)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return v[e]}))}(c);var b=s(137);for(var c in b)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return b[e]}))}(c);var w=s(98);s.d(t,"Messager",(function(){return w.a}));var S=s(29);s.d(t,"Notification",(function(){return S.a}));var T=s(138);for(var c in T)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return T[e]}))}(c);var E=s(139);for(var c in E)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return E[e]}))}(c);var R=s(12);s.d(t,"PublisherState",(function(){return R.a}));var y=s(140);for(var c in y)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return y[e]}))}(c);var I=s(141);s.d(t,"Publisher",(function(){return I.a}));var C=s(79);s.d(t,"Referral",(function(){return C.a}));var $=s(142);for(var c in $)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return $[e]}))}(c);var A=s(143);for(var c in A)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return A[e]}))}(c);var D=s(7);s.d(t,"RegistererState",(function(){return D.a}));var H=s(144);for(var c in H)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return H[e]}))}(c);var x=s(99);s.d(t,"Registerer",(function(){return x.a}));var P=s(145);for(var c in P)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return P[e]}))}(c);var q=s(146);for(var c in q)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return q[e]}))}(c);var _=s(147);for(var c in _)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return _[e]}))}(c);var k=s(148);for(var c in k)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return k[e]}))}(c);var O=s(149);for(var c in O)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return O[e]}))}(c);var M=s(150);for(var c in M)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return M[e]}))}(c);var N=s(151);for(var c in N)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return N[e]}))}(c);var U=s(152);for(var c in U)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return U[e]}))}(c);var j=s(153);for(var c in j)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return j[e]}))}(c);var F=s(1);s.d(t,"SessionState",(function(){return F.a}));var L=s(34);s.d(t,"Session",(function(){return L.a}));var B=s(154);for(var c in B)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return B[e]}))}(c);var G=s(155);for(var c in G)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return G[e]}))}(c);var V=s(156);s.d(t,"Subscriber",(function(){return V.a}));var K=s(157);for(var c in K)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return K[e]}))}(c);var W=s(158);for(var c in W)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return W[e]}))}(c);var Y=s(14);s.d(t,"SubscriptionState",(function(){return Y.a}));var J=s(159);for(var c in J)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return J[e]}))}(c);var Z=s(160);for(var c in Z)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return Z[e]}))}(c);var z=s(80);s.d(t,"Subscription",(function(){return z.a}));var X=s(161);for(var c in X)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return X[e]}))}(c);var Q=s(5);s.d(t,"TransportState",(function(){return Q.a}));var ee=s(162);for(var c in ee)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","TransportState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return ee[e]}))}(c);var te=s(22);s.d(t,"SIPExtension",(function(){return te.a})),s.d(t,"UserAgentRegisteredOptionTags",(function(){return te.b}));var se=s(16);s.d(t,"UserAgentState",(function(){return se.a}));var re=s(49);s.d(t,"UserAgent",(function(){return re.a}))},function(e,t,s){"use strict";var r=s(101);s.d(t,"a",(function(){return r.a})),s.d(t,"b",(function(){return r.b})),s.d(t,"c",(function(){return r.c})),s.d(t,"d",(function(){return r.d})),s.d(t,"e",(function(){return r.e})),s.d(t,"f",(function(){return r.f})),s.d(t,"g",(function(){return r.g})),s.d(t,"h",(function(){return r.h}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return r.a})),s.d(t,"b",(function(){return i.a})),s.d(t,"c",(function(){return a})),s.d(t,"d",(function(){return c.a})),s.d(t,"e",(function(){return d.a})),s.d(t,"f",(function(){return h.a})),s.d(t,"g",(function(){return u.a})),s.d(t,"h",(function(){return l.a})),s.d(t,"i",(function(){return g.a})),s.d(t,"j",(function(){return p.a})),s.d(t,"k",(function(){return f.a})),s.d(t,"n",(function(){return m.a})),s.d(t,"l",(function(){return v.a})),s.d(t,"m",(function(){return b.a})),s.d(t,"o",(function(){return w.a})),s.d(t,"p",(function(){return S.a})),s.d(t,"q",(function(){return T.a})),s.d(t,"r",(function(){return y})),s.d(t,"s",(function(){return I.a})),s.d(t,"t",(function(){return C.a})),s.d(t,"u",(function(){return $.a})),s.d(t,"v",(function(){return A.a})),s.d(t,"w",(function(){return D.a})),s.d(t,"x",(function(){return H.a})),s.d(t,"y",(function(){return o.a})),s.d(t,"z",(function(){return R.a}));var r=s(68),i=s(74),n=s(19),o=s(10);class a extends o.a{constructor(e,t,s){super(n.a,e,t,s)}}var c=s(69),d=s(75),h=s(92),u=s(61),l=s(53),g=s(54),p=s(71),f=s(30),m=s(93),v=s(72),b=s(77),w=s(70),S=s(76),T=s(78),E=s(20),R=s(13);class y extends R.a{constructor(e,t,s){super(E.a,e.userAgentCore,t,s)}}var I=s(73),C=s(55),$=s(94),A=s(96),D=s(95),H=s(97)},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Unspecified session description handler error.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(15),i=s(57);class n{constructor(){this.builtinEnabled=!0,this._level=r.a.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:r.a.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new i.a(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new i.a(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(r.a[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case r.a.error:console.error(i);break;case r.a.warn:console.warn(i);break;case r.a.log:console.log(i);break;case r.a.debug:console.debug(i)}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return d}));var r=s(26),i=s(48),n=s(4),o=s(24),a=s(0),c=s(10);class d extends c.a{constructor(e,t,s){super(o.a,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===a.a.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=r.a.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof o.a))throw new Error("Transaction not instance of InviteClientTransaction.");s=new i.a(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==n.b.Initial&&s.signalingState!==n.b.HaveLocalOffer||s.signalingStateTransition(e);const a=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:a,prack:e=>a.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=r.a.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof o.a))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof o.a))throw new Error("Transaction not instance of InviteClientTransaction.");s=new i.a(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==n.b.Initial&&s.signalingState!==n.b.HaveLocalOffer||s.signalingStateTransition(e);const a=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:a,ack:e=>{const t=a.ack(e);return this.confirmedDialogAcks.set(a.id,t),t}});else{const e=a.ack();this.confirmedDialogAcks.set(a.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+t)}throw new Error(`Executing what should be an unreachable code path receiving ${t} response.`)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(19),i=s(10);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(19),i=s(10);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return c}));var r=s(56),i=s(8),n=s(11),o=s(19),a=s(10);class c extends a.a{constructor(e,t,s){const r=t.getHeader("Event");if(!r)throw new Error("Event undefined");const n=t.getHeader("Expires");if(!n)throw new Error("Expires undefined");super(o.a,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+r,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(n),this.subscriptionEvent=r,this.subscriptionState=i.a.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const n=s.state;switch(n){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state "+n),void e.reject({statusCode:489})}if("terminated"!==n){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=i.a.Pending;break;case"active":this.subscriptionState=i.a.Active;break;case"terminated":this.subscriptionState=i.a.Terminated;break;default:throw new Error(`Unrecognized state ${n}.`)}if(this.subscriptionState!==i.a.Terminated){const t=r.a.initialDialogStateForSubscription(this.message,e.message);this.dialog=new r.a(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),n.a.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ethis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s),this.core=e}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s),this.core=e}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(2);class i{constructor(e,t,s,i="text/plain",n={}){this.logger=e.getLogger("sip.Messager"),n.params=n.params||{};let o=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(o="string"==typeof n.params.fromUri?r.Grammar.URIParse(n.params.fromUri):n.params.fromUri),!o)throw new TypeError("Invalid from URI: "+n.params.fromUri);let a=t;if(n.params.toUri&&(a="string"==typeof n.params.toUri?r.Grammar.URIParse(n.params.toUri):n.params.toUri),!a)throw new TypeError("Invalid to URI: "+n.params.toUri);const c=n.params?Object.assign({},n.params):{},d=(n.extraHeaders||[]).slice(),h={contentDisposition:"render",contentType:i,content:s};this.request=e.userAgentCore.makeOutgoingRequestMessage(r.C.MESSAGE,t,o,a,c,d,h),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(2),i=s(18),n=s(47),o=s(7);class a{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=o.a.Initial,this._waiting=!1,this._stateEventEmitter=new i.a,this._waitingEventEmitter=new i.a,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},a.defaultOptions()),{registrar:s}),a.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=a.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===r.Grammar.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const n=this.options.registrar,c=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,d=this.options.params&&this.options.params.toUri||e.configuration.uri,h=this.options.params||{},u=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(r.C.REGISTER,n,c,d,h,u,void 0),this.expires=this.options.expires||a.defaultExpires,this.expires<0)throw new Error("Invalid expires.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"registrar":this.logger.log("\xb7 "+e+": "+t);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:a.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new r.URI("sip","anonymous","anonymous.invalid")}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===o.a.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===o.a.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new n.a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,n=this._contacts.length;if(!n)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;n--;){if(i=t.message.parseHeader("contact",n),!i)throw new Error("Contact undefined");if(i.uri.user===this.userAgent.contact.uri.user){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=r.Grammar.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=r.Grammar.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn("Failed to register, status code "+t.message.statusCode);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===o.a.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==o.a.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new n.a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===o.a.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error("Unregister rejected with status code "+t.message.statusCode),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},1e3*e-3e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==o.a.Registered&&this.stateTransition(o.a.Registered)}unregistered(){this.clearTimers(),this._state!==o.a.Unregistered&&this.stateTransition(o.a.Unregistered)}terminated(){this.clearTimers(),this._state!==o.a.Terminated&&this.stateTransition(o.a.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case o.a.Initial:e!==o.a.Registered&&e!==o.a.Unregistered&&e!==o.a.Terminated&&t();break;case o.a.Registered:e!==o.a.Unregistered&&e!==o.a.Terminated&&t();break;case o.a.Unregistered:e!==o.a.Registered&&e!==o.a.Terminated&&t();break;case o.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===o.a.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log("Waiting toggled to "+this._waiting),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===o.a.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}a.defaultExpires=600},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(81),i=s(82),n=s(32);function o(e){return(t,s)=>{void 0===e&&(e=Object(r.a)());const o={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},Object(i.a)()),null==s?void 0:s.peerConnectionConfiguration)},a=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new n.a(a,e,o)}}},function(e,t,s){"use strict";s.d(t,"f",(function(){return i})),s.d(t,"g",(function(){return n})),s.d(t,"b",(function(){return o})),s.d(t,"d",(function(){return a})),s.d(t,"e",(function(){return c})),s.d(t,"h",(function(){return d})),s.d(t,"a",(function(){return h})),s.d(t,"c",(function(){return u}));const r=(e,t)=>{const s=[],r=e.split(/\r\n/);let i;for(let e=0;e(t.sdp=r(t.sdp||"",e),Promise.resolve(t))}function d(e){return e.sdp=((e,t)=>{const s=new RegExp("m="+t+".*$","gm"),r=new RegExp("^a=group:.*$","gm");if(s.test(e)){let s;const i=(e=e.split(/^m=/gm).filter(e=>{if(e.substr(0,t.length)===t){if(s=e.match(/^a=mid:.*$/gm),s){const e=s[0].match(/:.+$/g);e&&(s=e[0].substr(1))}return!1}return!0}).join("m=")).match(r);if(i&&1===i.length){let t=i[0];const n=new RegExp(" *"+s+"[^ ]*","g");t=t.replace(n,""),e=e.split(r).join(t)}}return e})(e.sdp||"","video"),Promise.resolve(e)}function h(e){let t=e.sdp||"";if(-1===t.search(/^a=mid.*$/gm)){const s=t.match(/^m=.*$/gm),r=t.split(/^m=.*$/gm);s&&s.forEach((e,t)=>{s[t]=e+"\na=mid:"+t}),r.forEach((e,t)=>{s&&s[t]&&(r[t]=e+s[t])}),t=r.join(""),e.sdp=t}return Promise.resolve(e)}function u(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const s=e.type;return t&&(/a=(sendrecv|sendonly|recvonly|inactive)/.test(t)?(t=t.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),t=t.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):t=t.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n")),Promise.resolve({sdp:t,type:s})}},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(106);s.d(t,"C",(function(){return r.a}));var i=s(107);for(var n in i)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(108);for(var n in o)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n);var a=s(109);for(var n in a)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(n);var c=s(110);for(var n in c)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return c[e]}))}(n);var d=s(111);for(var n in d)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return d[e]}))}(n);var h=s(112);for(var n in h)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(n);var u=s(113);for(var n in u)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return u[e]}))}(n);var l=s(114);for(var n in l)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(n);var g=s(115);for(var n in g)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return g[e]}))}(n);var p=s(116);for(var n in p)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(n);var f=s(117);for(var n in f)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return f[e]}))}(n);var m=s(118);for(var n in m)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return m[e]}))}(n)},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));var r,i=s(50),n=s(35),o=s(27);!function(e){function t(e,t){let s=t,r=0,i=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===r;){if(i=e.indexOf("\r\n",s),-1===i)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?s=i+2:r=i}return r}function s(e,t,s,r){const n=t.indexOf(":",s),a=t.substring(s,n).trim(),c=t.substring(n+1,r).trim();let d;switch(a.toLowerCase()){case"via":case"v":e.addHeader("via",c),1===e.getHeaders("via").length?(d=e.parseHeader("Via"),d&&(e.via=d,e.viaBranch=d.branch)):d=0;break;case"from":case"f":e.setHeader("from",c),d=e.parseHeader("from"),d&&(e.from=d,e.fromTag=d.getParam("tag"));break;case"to":case"t":e.setHeader("to",c),d=e.parseHeader("to"),d&&(e.to=d,e.toTag=d.getParam("tag"));break;case"record-route":if(d=i.a.parse(c,"Record_Route"),-1===d){d=void 0;break}if(!(d instanceof Array)){d=void 0;break}d.forEach(t=>{e.addHeader("record-route",c.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",c),d=e.parseHeader("call-id"),d&&(e.callId=c);break;case"contact":case"m":if(d=i.a.parse(c,"Contact"),-1===d){d=void 0;break}if(!(d instanceof Array)){d=void 0;break}d.forEach(t=>{e.addHeader("contact",c.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",c),d=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",c),d=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",c),d=e.parseHeader("cseq"),d&&(e.cseq=d.value),e instanceof o.a&&(e.method=d.method);break;case"max-forwards":e.setHeader("max-forwards",c),d=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",c),d=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",c),d=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",c),d=e.parseHeader("refer-to"),d&&(e.referTo=d);break;default:e.addHeader(a.toLowerCase(),c),d=0}return void 0!==d||{error:"error parsing header '"+a+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,r){let a=0,c=e.indexOf("\r\n");if(-1===c)return void r.warn("no CRLF found, not a SIP message, discarded");const d=e.substring(0,c),h=i.a.parse(d,"Request_Response");let u,l;if(-1!==h){for(h.status_code?(u=new o.a,u.statusCode=h.status_code,u.reasonPhrase=h.reason_phrase):(u=new n.a,u.method=h.method,u.ruri=h.uri),u.data=e,a=c+2;;){if(c=t(e,a),-2===c){l=a+2;break}if(-1===c)return void r.error("malformed message");if(!0!==s(u,e,a,c))return void r.error(h.error);a=c+2}return u.hasHeader("content-length")?u.body=e.substr(l,Number(u.getHeader("content-length"))):u.body=e.substring(l),u}r.warn('error parsing first line of SIP message: "'+d+'"')}}(r||(r={}))},function(e,t){},function(e,t,s){"use strict";var r=s(15);s.d(t,"a",(function(){return r.a}));var i=s(91);s.d(t,"c",(function(){return i.a}));var n=s(57);s.d(t,"b",(function(){return n.a}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(129);s.d(t,"UserAgentCore",(function(){return r.a}));var i=s(130);for(var n in i)["UserAgentCore","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(131);for(var n in o)["UserAgentCore","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n)},function(e,t,s){"use strict";s.d(t,"a",(function(){return R}));var r=s(3),i=s(46),n=s(85),o=s(19),a=s(0),c=s(17),d=s(92),h=s(53),u=s(93),l=s(94),g=s(95),p=s(10),f=s(61),m=s(30),v=s(54),b=s(55),w=s(96),S=s(97),T=s(21);const E=["application/sdp","application/dtmf-relay"];class R{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new d.a(this,e,t)}message(e,t){return new h.a(this,e,t)}publish(e,t){return new u.a(this,e,t)}register(e,t){return new l.a(this,e,t)}subscribe(e,t){return new g.a(this,e,t)}request(e,t){return new p.a(o.a,this,e,t)}makeOutgoingRequestMessage(e,t,s,n,o,a,c){const d=this.configuration.sipjsId,h=this.configuration.displayName,u=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,g=this.configuration.supportedOptionTags.slice();e===r.C.REGISTER&&g.push("path","gruu"),e===r.C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&g.push("gruu");const p={callIdPrefix:d,forceRport:u,fromDisplayName:h,hackViaTcp:l,optionTags:g,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=Object.assign(Object.assign({},p),o);return new i.a(e,t,s,n,f,a,c)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:r});const i=Object(n.a)(e,t);return this.transport.send(i.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),i}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===r.C.ACK&&s&&s.transaction.state===a.a.Accepted&&s instanceof f.a?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==r.C.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof c.a&&s.transaction.state===a.a.Proceeding&&s instanceof f.a&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!T.a.includes(e.method)){const t="Allow: "+T.a.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==r.C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==r.C.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===r.C.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,r=this.subscribers.get(s);if(r){const t=new m.a(this,e);return void r.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===r.C.OPTIONS){const t="Allow: "+T.a.toString(),s="Accept: "+E.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==r.C.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case r.C.ACK:break;case r.C.BYE:this.replyStateless(e,{statusCode:481});break;case r.C.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case r.C.INFO:this.replyStateless(e,{statusCode:405});break;case r.C.INVITE:{const t=new f.a(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case r.C.MESSAGE:{const t=new v.a(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case r.C.NOTIFY:{const t=new m.a(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case r.C.OPTIONS:{const t="Allow: "+T.a.toString(),s="Accept: "+E.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case r.C.REFER:{const t=new b.a(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case r.C.REGISTER:{const t=new w.a(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case r.C.SUBSCRIBE:{const t=new S.a(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(2),i=s(18),n=s(12);class o{constructor(e,t,s,o={}){this.disposed=!1,this._state=n.a.Initial,this._stateEventEmitter=new i.a,this.userAgent=e,o.extraHeaders=(o.extraHeaders||[]).slice(),o.contentType=o.contentType||"text/plain","number"!=typeof o.expires||o.expires%1!=0?o.expires=3600:o.expires=Number(o.expires),"boolean"!=typeof o.unpublishOnClose&&(o.unpublishOnClose=!0),this.target=t,this.event=s,this.options=o,this.pubRequestExpires=o.expires,this.logger=e.getLogger("sip.Publisher");const a=o.params||{},c=a.fromUri?a.fromUri:e.userAgentCore.configuration.aor,d=a.toUri?a.toUri:t;let h;if(o.body&&o.contentType){h={contentDisposition:"render",contentType:o.contentType,content:o.body}}const u=(o.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage(r.C.PUBLISH,t,c,d,a,u,h),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===n.a.Published?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0,Promise.resolve()))}get state(){return this._state}get stateChange(){return this._stateEventEmitter}publish(e,t={}){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires){if(void 0===this.options.expires)throw new Error("Expires undefined.");this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0}return this.sendPublishRequest(),Promise.resolve()}unpublish(e={}){return this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest(),Promise.resolve()}receiveResponse(e){const t=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(t.toString()):break;case/^2[0-9]{2}$/.test(t.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){const t=Number(e.getHeader("Expires"));"number"==typeof t&&t>=0&&t<=this.pubRequestExpires?this.pubRequestExpires=t:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout(()=>this.refreshRequest(),900*this.pubRequestExpires),this.stateTransition(n.a.Published)):this.stateTransition(n.a.Unpublished);break;case/^412$/.test(t.toString()):if(void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires){if(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated);break;case/^423$/.test(t.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){const t=Number(e.getHeader("Min-Expires"));if("number"==typeof t||t>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=t,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)}send(){return this.userAgent.userAgentCore.publish(this.request,{onAccept:e=>this.receiveResponse(e.message),onProgress:e=>this.receiveResponse(e.message),onRedirect:e=>this.receiveResponse(e.message),onReject:e=>this.receiveResponse(e.message),onTrying:e=>this.receiveResponse(e.message)})}refreshRequest(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new Error("Etag undefined");if(0===this.pubRequestExpires)throw new Error("Expires zero");this.sendPublishRequest()}sendPublishRequest(){const e=Object.assign({},this.options);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);const t=this.target,s=this.options.params||{};let i,n;if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");i={body:this.pubRequestBody,contentType:this.options.contentType}}return i&&(n=Object(r.fromBodyLegacy)(i)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(r.C.PUBLISH,t,s.fromUri?s.fromUri:this.userAgent.userAgentCore.configuration.aor,s.toUri?s.toUri:this.target,s,e.extraHeaders,n),this.send()}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case n.a.Initial:e!==n.a.Published&&e!==n.a.Unpublished&&e!==n.a.Terminated&&t();break;case n.a.Published:e!==n.a.Unpublished&&e!==n.a.Terminated&&t();break;case n.a.Unpublished:e!==n.a.Published&&e!==n.a.Terminated&&t();break;case n.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===n.a.Terminated&&this.dispose()}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return c}));var r=s(2),i=s(21),n=s(29),o=s(80),a=s(14);class c extends o.a{constructor(e,t,s,r={}){super(e,r),this.body=void 0,this.logger=e.getLogger("sip.Subscriber"),r.body&&(this.body={body:r.body,contentType:r.contentType?r.contentType:"application/sdp"}),this.targetURI=t,this.event=s,void 0===r.expires?this.expires=3600:"number"!=typeof r.expires?(this.logger.warn('Option "expires" must be a number. Using default of 3600.'),this.expires=3600):this.expires=r.expires,this.extraHeaders=(r.extraHeaders||[]).slice(),this.subscriberRequest=this.initSubscriberRequest(),this.outgoingRequestMessage=this.subscriberRequest.message,this.id=this.outgoingRequestMessage.callId+this.outgoingRequestMessage.from.parameters.tag+this.event,this._userAgent._subscriptions[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),super.dispose().then(()=>{if(this.state===a.a.Subscribed){if(!this._dialog)throw new Error("Dialog undefined.");if(this._dialog.subscriptionState===r.SubscriptionState.Pending||this._dialog.subscriptionState===r.SubscriptionState.Active){const e=this._dialog;return new Promise((t,s)=>{e.delegate={onTerminated:()=>t()},e.unsubscribe()})}}}))}subscribe(e={}){switch(this.subscriberRequest.state){case r.SubscriptionState.Initial:this.state===a.a.Initial&&this.stateTransition(a.a.NotifyWait),this.subscriberRequest.subscribe().then(e=>{e.success?(e.success.subscription&&(this._dialog=e.success.subscription,this._dialog.delegate={onNotify:e=>this.onNotify(e),onRefresh:e=>this.onRefresh(e),onTerminated:()=>{this.state!==a.a.Terminated&&this.stateTransition(a.a.Terminated)}}),this.onNotify(e.success.request)):e.failure&&this.unsubscribe()});break;case r.SubscriptionState.NotifyWait:case r.SubscriptionState.Pending:break;case r.SubscriptionState.Active:if(this._dialog){this._dialog.refresh().delegate={onAccept:e=>this.onAccepted(e),onRedirect:e=>this.unsubscribe(),onReject:e=>this.unsubscribe()}}break;case r.SubscriptionState.Terminated:}return Promise.resolve()}unsubscribe(e={}){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case r.SubscriptionState.Initial:case r.SubscriptionState.NotifyWait:break;case r.SubscriptionState.Pending:case r.SubscriptionState.Active:this._dialog&&this._dialog.unsubscribe();break;case r.SubscriptionState.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(a.a.Terminated),Promise.resolve()}_refresh(){return this.subscriberRequest.state===r.SubscriptionState.Active?this.subscribe():Promise.resolve()}onAccepted(e){}onNotify(e){if(this.disposed)return void e.accept();if(this.state!==a.a.Subscribed&&this.stateTransition(a.a.Subscribed),this.delegate&&this.delegate.onNotify){const t=new n.a(e);this.delegate.onNotify(t)}else e.accept();const t=e.message.parseHeader("Subscription-State");if(t&&t.state)switch(t.state){case"terminated":if(t.reason)switch(this.logger.log("Terminated subscription with reason "+t.reason),t.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(t.params&&t.params["retry-after"]?this.retryAfterTimer=setTimeout(()=>{this.subscribe()},t.params["retry-after"]):this.subscribe())}this.unsubscribe()}}onRefresh(e){e.delegate={onAccept:e=>this.onAccepted(e)}}initSubscriberRequest(){const e={extraHeaders:this.extraHeaders,body:this.body?Object(r.fromBodyLegacy)(this.body):void 0};return this.subscriberRequest=new d(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,e),this.subscriberRequest.delegate={onAccept:e=>this.onAccepted(e)},this.subscriberRequest}}class d{constructor(e,t,s,n,o,a){this.core=e,this.target=t,this.event=s,this.expires=n,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=a;const c="Allow: "+i.a.toString(),d=(o&&o.extraHeaders||[]).slice();d.push(c),d.push("Event: "+this.event),d.push("Expires: "+this.expires),d.push("Contact: "+this.core.configuration.contact.toString());const h=o&&o.body;this.message=e.makeOutgoingRequestMessage(r.C.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},d,h)}dispose(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)}get state(){return this.subscription?this.subscription.subscriptionState:this.subscribed?r.SubscriptionState.NotifyWait:r.SubscriptionState.Initial}subscribe(){return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(e=>{if(!this.message)throw new Error("Message undefined.");this.request=this.core.subscribe(this.message,{onAccept:e=>{this.delegate&&this.delegate.onAccept&&this.delegate.onAccept(e)},onNotify:t=>{this.subscription=t.subscription,this.subscription&&(this.subscription.autoRefresh=!0),e({success:t})},onNotifyTimeout:()=>{e({failure:{}})},onRedirect:t=>{e({failure:{response:t}})},onReject:t=>{e({failure:{response:t}})}})}))}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(88);s.d(t,"stripTcpCandidates",(function(){return r.f})),s.d(t,"stripTelephoneEvent",(function(){return r.g})),s.d(t,"cleanJitsiSdpImageattr",(function(){return r.b})),s.d(t,"stripG722",(function(){return r.d})),s.d(t,"stripRtpPayload",(function(){return r.e})),s.d(t,"stripVideo",(function(){return r.h})),s.d(t,"addMidLines",(function(){return r.a})),s.d(t,"holdModifier",(function(){return r.c}));var i=s(64);for(var n in i)["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(170);for(var n in o)["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n);var a=s(65);for(var n in a)["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(n)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(171);s.d(t,"SimpleUser",(function(){return r.a}));var i=s(172);for(var n in i)["SimpleUser","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(173);for(var n in o)["SimpleUser","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n)},function(e,t,s){"use strict";s.d(t,"a",(function(){return f}));var r=s(49),i=s(16),n=s(99),o=s(7),a=s(36),c=s(31),d=s(98),h=s(1),u=s(47),l=s(101),g=s(32),p=s(86);class f{constructor(e,t={}){this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=Object.assign({},t);const s=Object.assign({},t.userAgentOptions);if(s.transportConstructor||(s.transportConstructor=p.a),s.transportOptions||(s.transportOptions={server:e}),!s.uri&&t.aor){const e=r.a.makeURI(t.aor);if(!e)throw new Error("Failed to create valid URI from "+t.aor);s.uri=e}this.userAgent=new r.a(s),this.userAgent.delegate={onConnect:()=>{this.logger.log(`[${this.id}] Connected`),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.registerer&&this.registerRequested&&(this.logger.log(`[${this.id}] Registering...`),this.registerer.register().catch(e=>{this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`),this.logger.error(e.toString())}))},onDisconnect:e=>{this.logger.log(`[${this.id}] Disconnected`),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),this.session&&(this.logger.log(`[${this.id}] Hanging up...`),this.hangup().catch(e=>{this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`),this.logger.error(e.toString())})),this.registerer&&(this.logger.log(`[${this.id}] Unregistering...`),this.registerer.unregister().catch(e=>{this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`),this.logger.error(e.toString())})),e&&this.attemptReconnection()},onInvite:e=>{if(this.logger.log(`[${this.id}] Received INVITE`),this.session)return this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())});const t={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,t),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived():(this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",()=>{this.logger.log(`[${this.id}] Online`),this.attemptReconnection()})}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof g.a))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}get remoteMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof g.a))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}get localAudioTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get localVideoTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}get remoteAudioTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get remoteVideoTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.connectRequested=!0,this.userAgent.state!==i.a.Started?this.userAgent.start():this.userAgent.reconnect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.connectRequested=!1,this.userAgent.stop()}isConnected(){return this.userAgent.isConnected()}register(e,t){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.registerRequested=!0,this.registerer||(this.registerer=new n.a(this.userAgent,e),this.registerer.stateChange.addListener(e=>{switch(e){case o.a.Initial:break;case o.a.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case o.a.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered();break;case o.a.Terminated:this.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(()=>{})}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):Promise.resolve()}call(e,t,s){if(this.logger.log(`[${this.id}] Beginning Session...`),this.session)return Promise.reject(new Error("Session already exists."));const i=r.a.makeURI(e);if(!i)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);const n=new a.a(this.userAgent,i,t);return this.sendInvite(n,t,s).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.terminate()}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.session instanceof c.a?(e||(e={}),e.sessionDescriptionHandlerOptions||(e.sessionDescriptionHandlerOptions={}),e.sessionDescriptionHandlerOptions.constraints||(e.sessionDescriptionHandlerOptions.constraints=this.constraints),this.session.accept(e)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.session instanceof c.a?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.setHold(!0)}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.setHold(!1)}isHeld(){return this.held}mute(){this.logger.log(`[${this.id}] disabling media tracks...`),this.setMute(!0)}unmute(){this.logger.log(`[${this.id}] enabling media tracks...`),this.setMute(!1)}isMuted(){const e=this.localAudioTrack||this.localVideoTrack;return!!e&&!e.enabled}sendDTMF(e){if(this.logger.log(`[${this.id}] sending DTMF...`),!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.session)return Promise.reject(new Error("Session does not exist."));this.logger.log(`[${this.id}] Sending DTMF tone: ${e}`);const t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(()=>{})}message(e,t){this.logger.log(`[${this.id}] sending message...`);const s=r.a.makeURI(e);return s?new d.a(this.userAgent,s,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}get constraints(){var e;let t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=Object.assign({},this.options.media.constraints)),t}attemptReconnection(e=1){const t=this.options.reconnectionAttempts||3,s=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log(`[${this.id}] Reconnection attempt already in progress`),e>t?this.logger.log(`[${this.id}] Reconnection maximum attempts reached`):(1===e?this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying in ${s} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.connectRequested)return this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(s=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - failed`),this.logger.error(s.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*s))):this.logger.log(`[${this.id}] Reconnection not currently desired`)}cleanupMedia(){this.options.media&&(this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause()),this.options.media.remote&&(this.options.media.remote.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause()),this.options.media.remote.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause())))}enableSenderTracks(e){if(!this.session)throw new Error("Session does not exist.");const t=this.session.sessionDescriptionHandler;if(!(t instanceof g.a))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s=t.peerConnection;if(!s)throw new Error("Peer connection closed.");s.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}initSession(e,t){this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(t=>{if(this.session===e)switch(this.logger.log(`[${this.id}] session state changed to ${t}`),t){case h.a.Initial:case h.a.Establishing:break;case h.a.Established:this.setupLocalMedia(),this.setupRemoteMedia(),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered();break;case h.a.Terminating:case h.a.Terminated:this.session=void 0,this.cleanupMedia(),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:e=>{var t;if(void 0===(null===(t=this.delegate)||void 0===t?void 0:t.onCallDTMFReceived))return void e.reject();const s=e.request.getHeader("content-type");if(!s||!/^application\/dtmf-relay/i.exec(s))return void e.reject();const r=e.request.body.split("\r\n",2);if(2!==r.length)return void e.reject();let i;const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(n.test(r[0])&&(i=r[0].replace(n,"$2")),!i)return void e.reject();let o;const a=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;a.test(r[1])&&(o=parseInt(r[1].replace(a,"$2"),10)),o?e.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!i||!o)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(i,o)}}).catch(e=>{this.logger.error(e.message)}):e.reject()},onRefer:e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(t),t)).catch(e=>{this.logger.error(e.message)})}}}sendInvite(e,t,s){return this.initSession(e,t),e.invite(s).then(()=>{this.logger.log(`[${this.id}] sent INVITE`)})}setHold(e){if(!this.session)return Promise.reject(new Error("Session does not exist."));if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof g.a))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const t={requestDelegate:{onAccept:()=>{this.held=e,this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)},onReject:()=>{this.logger.warn(`[${this.id}] re-invite request was rejected`),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)}}};return t.sessionDescriptionHandlerModifiers=e?[l.c]:[],this.session.invite(t).then(()=>{this.enableSenderTracks(!e)}).catch(e=>{throw e instanceof u.a&&this.logger.error(`[${this.id}] A hold request is already in progress.`),e})}setMute(e){this.session?this.session.state===h.a.Established?this.enableSenderTracks(!e):this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`):this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`)}setupLocalMedia(){var e,t;if(!this.session)throw new Error("Session does not exist.");const s=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(s){const e=this.localMediaStream;if(!e)throw new Error("Local media stream undefiend.");s.srcObject=e,s.volume=0,s.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play local media`),this.logger.error(e.message)})}}setupRemoteMedia(){var e,t,s,r;if(!this.session)throw new Error("Session does not exist.");const i=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(r=null===(s=this.options.media)||void 0===s?void 0:s.remote)||void 0===r?void 0:r.audio);if(i){const e=this.remoteMediaStream;if(!e)throw new Error("Remote media stream undefiend.");i.autoplay=!0,i.srcObject=e,i.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)}),e.onaddtrack=()=>{this.logger.log(`[${this.id}] Remote media onaddtrack`),i.load(),i.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)})}}}terminate(){if(this.logger.log(`[${this.id}] Terminating...`),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case h.a.Initial:if(this.session instanceof a.a)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`)});if(this.session instanceof c.a)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case h.a.Establishing:if(this.session instanceof a.a)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`)});if(this.session instanceof c.a)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case h.a.Established:return this.session.bye().then(()=>{this.logger.log(`[${this.id}] Session ended (sent BYE)`)});case h.a.Terminating:case h.a.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`),Promise.resolve()}}},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));class r{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=r.hexChars,s=r.hexOut;let i,n,o,a;for(a=0;a<4;a+=1)for(n=8*a,i=e[a],o=0;o<8;o+=2)s[n+1+o]=t.charAt(15&i),i>>>=4,s[n+0+o]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],r=e[1],i=e[2],n=e[3];s+=(r&i|~r&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[2]+606105819|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[3]-1044525330|0,r=(r<<22|r>>>10)+i|0,s+=(r&i|~r&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[6]-1473231341|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[7]-45705983|0,r=(r<<22|r>>>10)+i|0,s+=(r&i|~r&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[10]-42063|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[11]-1990404162|0,r=(r<<22|r>>>10)+i|0,s+=(r&i|~r&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[14]-1502002290|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[15]+1236535329|0,r=(r<<22|r>>>10)+i|0,s+=(r&n|i&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[11]+643717713|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[0]-373897302|0,r=(r<<20|r>>>12)+i|0,s+=(r&n|i&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[15]-660478335|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[4]-405537848|0,r=(r<<20|r>>>12)+i|0,s+=(r&n|i&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[3]-187363961|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[8]+1163531501|0,r=(r<<20|r>>>12)+i|0,s+=(r&n|i&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[7]+1735328473|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[12]-1926607734|0,r=(r<<20|r>>>12)+i|0,s+=(r^i^n)+t[5]-378558|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[11]+1839030562|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[14]-35309556|0,r=(r<<23|r>>>9)+i|0,s+=(r^i^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[7]-155497632|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[10]-1094730640|0,r=(r<<23|r>>>9)+i|0,s+=(r^i^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[3]-722521979|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[6]+76029189|0,r=(r<<23|r>>>9)+i|0,s+=(r^i^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[15]+530742520|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[2]-995338651|0,r=(r<<23|r>>>9)+i|0,s+=(i^(r|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[14]-1416354905|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[5]-57434055|0,r=(r<<21|r>>>11)+i|0,s+=(i^(r|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[10]-1051523|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[1]-2054922799|0,r=(r<<21|r>>>11)+i|0,s+=(i^(r|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[6]-1560198380|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[13]+1309151649|0,r=(r<<21|r>>>11)+i|0,s+=(i^(r|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[2]+718787259|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[9]-343485551|0,r=(r<<21|r>>>11)+i|0,e[0]=s+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(r.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,n,o=this._bufferLength;for(n=0;n>>6),t[o++]=63&i|128;else if(i<55296||i>56319)t[o++]=224+(i>>>12),t[o++]=i>>>6&63|128,t[o++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++n)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[o++]=240+(i>>>18),t[o++]=i>>>12&63|128,t[o++]=i>>>6&63|128,t[o++]=63&i|128}o>=64&&(this._dataLength+=64,r._md5cycle(this._state,s),o-=64,s[0]=s[16])}return this._bufferLength=o,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,n=this._bufferLength,o=0;for(;;){for(i=Math.min(e.length-o,64-n);i--;)t[n++]=e.charCodeAt(o++);if(n<64)break;this._dataLength+=64,r._md5cycle(this._state,s),n=0}return this._bufferLength=n,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,n=this._bufferLength,o=0;for(;;){for(i=Math.min(e.length-o,64-n);i--;)t[n++]=e[o++];if(n<64)break;this._dataLength+=64,r._md5cycle(this._state,s),n=0}return this._bufferLength=n,this}getState(){const e=this._state;return{buffer:String.fromCharCode.apply(null,this._buffer8),buflen:this._bufferLength,length:this._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(e){const t=e.buffer,s=e.state,r=this._state;let i;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=s[0],r[1]=s[1],r[2]=s[2],r[3]=s[3],i=0;i>2);let o;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(r.buffer32Identity.subarray(n),n),t>55&&(r._md5cycle(this._state,i),i.set(r.buffer32Identity)),o=8*this._dataLength,o<=4294967295)i[14]=o;else{const e=o.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return r._md5cycle(this._state,i),e?this._state:r._hex(this._state)}}r.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),r.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),r.hexChars="0123456789abcdef",r.hexOut=[],r.onePassHasher=new r,"5d41402abc4b2a76b9719d911017c592"!==r.hashStr("hello")&&console.error("Md5 self test failed.");var i=s(6);function n(e){return r.hashStr(e)}class o{constructor(e,t,s,r){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=Object(i.a)(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=n(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=n(this.method+":"+this.uri),this.response=n(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=n(this.method+":"+this.uri+":"+n(e||"")),this.response=n(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=n(this.method+":"+this.uri),this.response=n(t+":"+this.nonce+":"+s))}}},function(e,t,s){"use strict";s.r(t),s.d(t,"name",(function(){return h})),s.d(t,"version",(function(){return d}));var r=s(83),i=s(87);for(var n in i)["name","version","Core","Web","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(33);s.d(t,"Grammar",(function(){return o.a})),s.d(t,"NameAddrHeader",(function(){return o.b})),s.d(t,"Parameters",(function(){return o.c})),s.d(t,"URI",(function(){return o.d}));var a=s(2);s.d(t,"Core",(function(){return a}));var c=s(163);s.d(t,"Web",(function(){return c}));const d=r.a,h="sip.js"}])})); \ No newline at end of file diff --git a/dist/sip.js b/dist/sip.js deleted file mode 100644 index 6ae99fccb..000000000 --- a/dist/sip.js +++ /dev/null @@ -1,20708 +0,0 @@ -/*! - * - * SIP version 0.17.1 - * Copyright (c) 2014-2020 Junction Networks, Inc - * Homepage: https://sipjs.com - * License: https://sipjs.com/license/ - * - * - * ~~~SIP.js contains substantial portions of JsSIP under the following license~~~ - * Homepage: http://jssip.net - * Copyright (c) 2012-2013 José Luis Millán - Versatica - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * ~~~ end JsSIP license ~~~ - * - * - * - * - */ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["SIP"] = factory(); - else - root["SIP"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "name", function() { return name; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; }); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); -/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _api__WEBPACK_IMPORTED_MODULE_1__) if(["name","version","Core","Web","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _api__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Grammar"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["NameAddrHeader"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_2__["URI"]; }); - -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Core", function() { return _core__WEBPACK_IMPORTED_MODULE_3__; }); -/* harmony import */ var _platform_web__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(174); -/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Web", function() { return _platform_web__WEBPACK_IMPORTED_MODULE_4__; }); -// Helpful name and version exports - -const version = _version__WEBPACK_IMPORTED_MODULE_0__["LIBRARY_VERSION"]; -const name = "sip.js"; - -// Export api - -// Export grammar - -// Export namespaced core - - -// Export namespaced web - - - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LIBRARY_VERSION", function() { return LIBRARY_VERSION; }); -const LIBRARY_VERSION = "0.17.1"; - - -/***/ }), -/* 2 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionDescriptionHandlerError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["SessionTerminatedError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_0__["StateTransitionError"]; }); - -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(107); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return _bye__WEBPACK_IMPORTED_MODULE_1__["Bye"]; }); - -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(108); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return _emitter__WEBPACK_IMPORTED_MODULE_2__["EmitterImpl"]; }); - -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(109); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return _info__WEBPACK_IMPORTED_MODULE_3__["Info"]; }); - -/* harmony import */ var _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(110); -/* harmony import */ var _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invitation_accept_options__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(111); -/* harmony import */ var _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invitation_progress_options__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(112); -/* harmony import */ var _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invitation_reject_options__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(113); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return _invitation__WEBPACK_IMPORTED_MODULE_7__["Invitation"]; }); - -/* harmony import */ var _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(120); -/* harmony import */ var _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _inviter_cancel_options__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(121); -/* harmony import */ var _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _inviter_invite_options__WEBPACK_IMPORTED_MODULE_9__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _inviter_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(122); -/* harmony import */ var _inviter_options__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_inviter_options__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _inviter_options__WEBPACK_IMPORTED_MODULE_10__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _inviter_options__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(123); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return _inviter__WEBPACK_IMPORTED_MODULE_11__["Inviter"]; }); - -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(115); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return _message__WEBPACK_IMPORTED_MODULE_12__["Message"]; }); - -/* harmony import */ var _messager_message_options__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(124); -/* harmony import */ var _messager_message_options__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_messager_message_options__WEBPACK_IMPORTED_MODULE_13__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _messager_message_options__WEBPACK_IMPORTED_MODULE_13__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _messager_message_options__WEBPACK_IMPORTED_MODULE_13__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _messager_options__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(125); -/* harmony import */ var _messager_options__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_messager_options__WEBPACK_IMPORTED_MODULE_14__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _messager_options__WEBPACK_IMPORTED_MODULE_14__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _messager_options__WEBPACK_IMPORTED_MODULE_14__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _messager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(126); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return _messager__WEBPACK_IMPORTED_MODULE_15__["Messager"]; }); - -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(116); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; }); - -/* harmony import */ var _publisher_options__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(127); -/* harmony import */ var _publisher_options__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_publisher_options__WEBPACK_IMPORTED_MODULE_17__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publisher_options__WEBPACK_IMPORTED_MODULE_17__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publisher_options__WEBPACK_IMPORTED_MODULE_17__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(128); -/* harmony import */ var _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publisher_publish_options__WEBPACK_IMPORTED_MODULE_18__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(129); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return _publisher_state__WEBPACK_IMPORTED_MODULE_19__["PublisherState"]; }); - -/* harmony import */ var _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(130); -/* harmony import */ var _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publisher_unpublish_options__WEBPACK_IMPORTED_MODULE_20__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publisher__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(131); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return _publisher__WEBPACK_IMPORTED_MODULE_21__["Publisher"]; }); - -/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(117); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return _referral__WEBPACK_IMPORTED_MODULE_22__["Referral"]; }); - -/* harmony import */ var _registerer_options__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(132); -/* harmony import */ var _registerer_options__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_registerer_options__WEBPACK_IMPORTED_MODULE_23__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _registerer_options__WEBPACK_IMPORTED_MODULE_23__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _registerer_options__WEBPACK_IMPORTED_MODULE_23__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(133); -/* harmony import */ var _registerer_register_options__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_registerer_register_options__WEBPACK_IMPORTED_MODULE_24__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _registerer_register_options__WEBPACK_IMPORTED_MODULE_24__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(134); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return _registerer_state__WEBPACK_IMPORTED_MODULE_25__["RegistererState"]; }); - -/* harmony import */ var _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(135); -/* harmony import */ var _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _registerer_unregister_options__WEBPACK_IMPORTED_MODULE_26__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _registerer__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(136); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return _registerer__WEBPACK_IMPORTED_MODULE_27__["Registerer"]; }); - -/* harmony import */ var _session_bye_options__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(137); -/* harmony import */ var _session_bye_options__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_session_bye_options__WEBPACK_IMPORTED_MODULE_28__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_bye_options__WEBPACK_IMPORTED_MODULE_28__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_bye_options__WEBPACK_IMPORTED_MODULE_28__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(138); -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_session_delegate__WEBPACK_IMPORTED_MODULE_29__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_delegate__WEBPACK_IMPORTED_MODULE_29__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_delegate__WEBPACK_IMPORTED_MODULE_29__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(139); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_30__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(140); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler__WEBPACK_IMPORTED_MODULE_31__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler__WEBPACK_IMPORTED_MODULE_31__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_31__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_info_options__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(141); -/* harmony import */ var _session_info_options__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_session_info_options__WEBPACK_IMPORTED_MODULE_32__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_info_options__WEBPACK_IMPORTED_MODULE_32__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_info_options__WEBPACK_IMPORTED_MODULE_32__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_invite_options__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(142); -/* harmony import */ var _session_invite_options__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_session_invite_options__WEBPACK_IMPORTED_MODULE_33__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_invite_options__WEBPACK_IMPORTED_MODULE_33__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_invite_options__WEBPACK_IMPORTED_MODULE_33__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_message_options__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(143); -/* harmony import */ var _session_message_options__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_session_message_options__WEBPACK_IMPORTED_MODULE_34__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_message_options__WEBPACK_IMPORTED_MODULE_34__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_message_options__WEBPACK_IMPORTED_MODULE_34__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_options__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(144); -/* harmony import */ var _session_options__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_session_options__WEBPACK_IMPORTED_MODULE_35__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_options__WEBPACK_IMPORTED_MODULE_35__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_options__WEBPACK_IMPORTED_MODULE_35__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_refer_options__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(145); -/* harmony import */ var _session_refer_options__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(_session_refer_options__WEBPACK_IMPORTED_MODULE_36__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_refer_options__WEBPACK_IMPORTED_MODULE_36__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_refer_options__WEBPACK_IMPORTED_MODULE_36__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(118); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session_state__WEBPACK_IMPORTED_MODULE_37__["SessionState"]; }); - -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(114); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return _session__WEBPACK_IMPORTED_MODULE_38__["Session"]; }); - -/* harmony import */ var _subscriber_options__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(146); -/* harmony import */ var _subscriber_options__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(_subscriber_options__WEBPACK_IMPORTED_MODULE_39__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscriber_options__WEBPACK_IMPORTED_MODULE_39__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscriber_options__WEBPACK_IMPORTED_MODULE_39__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(147); -/* harmony import */ var _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(_subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscriber_subscribe_options__WEBPACK_IMPORTED_MODULE_40__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscriber__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(148); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _subscriber__WEBPACK_IMPORTED_MODULE_41__["Subscriber"]; }); - -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(151); -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_42___default = /*#__PURE__*/__webpack_require__.n(_subscription_delegate__WEBPACK_IMPORTED_MODULE_42__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_delegate__WEBPACK_IMPORTED_MODULE_42__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription_options__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(152); -/* harmony import */ var _subscription_options__WEBPACK_IMPORTED_MODULE_43___default = /*#__PURE__*/__webpack_require__.n(_subscription_options__WEBPACK_IMPORTED_MODULE_43__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_options__WEBPACK_IMPORTED_MODULE_43__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_options__WEBPACK_IMPORTED_MODULE_43__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(150); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription_state__WEBPACK_IMPORTED_MODULE_44__["SubscriptionState"]; }); - -/* harmony import */ var _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(153); -/* harmony import */ var _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45___default = /*#__PURE__*/__webpack_require__.n(_subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_subscribe_options__WEBPACK_IMPORTED_MODULE_45__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(154); -/* harmony import */ var _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46___default = /*#__PURE__*/__webpack_require__.n(_subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_unsubscribe_options__WEBPACK_IMPORTED_MODULE_46__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(149); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _subscription__WEBPACK_IMPORTED_MODULE_47__["Subscription"]; }); - -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(155); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_48___default = /*#__PURE__*/__webpack_require__.n(_transport__WEBPACK_IMPORTED_MODULE_48__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport__WEBPACK_IMPORTED_MODULE_48__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport__WEBPACK_IMPORTED_MODULE_48__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transport_state__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(156); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return _transport_state__WEBPACK_IMPORTED_MODULE_49__["TransportState"]; }); - -/* harmony import */ var _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(157); -/* harmony import */ var _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50___default = /*#__PURE__*/__webpack_require__.n(_user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__) if(["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","TransportState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_delegate__WEBPACK_IMPORTED_MODULE_50__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(119); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["SIPExtension"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return _user_agent_options__WEBPACK_IMPORTED_MODULE_51__["UserAgentRegisteredOptionTags"]; }); - -/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(158); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return _user_agent_state__WEBPACK_IMPORTED_MODULE_52__["UserAgentState"]; }); - -/* harmony import */ var _user_agent__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(159); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return _user_agent__WEBPACK_IMPORTED_MODULE_53__["UserAgent"]; }); - -/** - * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. - * @packageDocumentation - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/***/ }), -/* 3 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return _content_type_unsupported__WEBPACK_IMPORTED_MODULE_0__["ContentTypeUnsupportedError"]; }); - -/* harmony import */ var _request_pending__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return _request_pending__WEBPACK_IMPORTED_MODULE_1__["RequestPendingError"]; }); - -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(104); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]; }); - -/* harmony import */ var _session_terminated__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(105); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return _session_terminated__WEBPACK_IMPORTED_MODULE_3__["SessionTerminatedError"]; }); - -/* harmony import */ var _state_transition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(106); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return _state_transition__WEBPACK_IMPORTED_MODULE_4__["StateTransitionError"]; }); - - - - - - - - -/***/ }), -/* 4 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContentTypeUnsupportedError", function() { return ContentTypeUnsupportedError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating an unsupported content type prevented execution. - * @public - */ -class ContentTypeUnsupportedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Unsupported content type."); - } -} - - -/***/ }), -/* 5 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _dialogs__WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _dialogs__WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["Exception"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransportError"]; }); - -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(84); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Levels"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["LoggerFactory"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _log__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); - -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _messages__WEBPACK_IMPORTED_MODULE_3__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _messages__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(44); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session__WEBPACK_IMPORTED_MODULE_4__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(79); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription__WEBPACK_IMPORTED_MODULE_5__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(48); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transactions__WEBPACK_IMPORTED_MODULE_6__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transactions__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(88); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_core__WEBPACK_IMPORTED_MODULE_7__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(90); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ByeUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["CancelUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InfoUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["InviteUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["NotifyUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PublishUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["PrackUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReInviteUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReSubscribeUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["ReferUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["RegisterUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["SubscribeUserAgentServer"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agents__WEBPACK_IMPORTED_MODULE_8__["UserAgentServer"]; }); - -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(47); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return _timers__WEBPACK_IMPORTED_MODULE_9__["Timers"]; }); - -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(102); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_transport__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport__WEBPACK_IMPORTED_MODULE_10__) if(["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","ByeUserAgentClient","ByeUserAgentServer","CancelUserAgentClient","InfoUserAgentClient","InfoUserAgentServer","InviteUserAgentClient","InviteUserAgentServer","MessageUserAgentClient","MessageUserAgentServer","NotifyUserAgentClient","NotifyUserAgentServer","PublishUserAgentClient","PrackUserAgentClient","PrackUserAgentServer","ReInviteUserAgentClient","ReInviteUserAgentServer","ReSubscribeUserAgentClient","ReSubscribeUserAgentServer","ReferUserAgentClient","ReferUserAgentServer","RegisterUserAgentClient","RegisterUserAgentServer","SubscribeUserAgentClient","SubscribeUserAgentServer","UserAgentClient","UserAgentServer","Timers","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -// Directories - - - - - - - - - -// Files - - - - -/***/ }), -/* 6 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _dialog__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); - -/* harmony import */ var _dialog_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42); -/* harmony import */ var _dialog_state__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_dialog_state__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _dialog_state__WEBPACK_IMPORTED_MODULE_1__) if(["Dialog","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _dialog_state__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_dialog__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(43); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return _session_dialog__WEBPACK_IMPORTED_MODULE_2__["SessionDialog"]; }); - -/* harmony import */ var _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(78); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return _subscription_dialog__WEBPACK_IMPORTED_MODULE_3__["SubscriptionDialog"]; }); - - - - - - - -/***/ }), -/* 7 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return Dialog; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); - -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -class Dialog { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - constructor(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForUserAgentClient(outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const localSequenceNumber = outgoingRequestMessage.cseq; - const remoteSequenceNumber = undefined; - const callId = outgoingRequestMessage.callId; - const localTag = outgoingRequestMessage.fromTag; - const remoteTag = incomingResponseMessage.toTag; - if (!callId) { - // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { - // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { - // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { - // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { - // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - const localURI = outgoingRequestMessage.from.uri; - const remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - const early = incomingResponseMessage.statusCode < 200 ? true : false; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, early = false) { - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const routeSet = incomingRequestMessage.getHeaders("record-route"); - const contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const remoteSequenceNumber = incomingRequestMessage.cseq; - const localSequenceNumber = undefined; - const callId = incomingRequestMessage.callId; - const localTag = toTag; - const remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const remoteURI = incomingRequestMessage.from.uri; - const localURI = incomingRequestMessage.to.uri; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - /** Destructor. */ - dispose() { - this.core.dialogs.delete(this.id); - } - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get id() { - return this.dialogState.id; - } - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get early() { - return this.dialogState.early; - } - /** Call identifier component of the dialog id. */ - get callId() { - return this.dialogState.callId; - } - /** Local tag component of the dialog id. */ - get localTag() { - return this.dialogState.localTag; - } - /** Remote tag component of the dialog id. */ - get remoteTag() { - return this.dialogState.remoteTag; - } - /** Local sequence number (used to order requests from the UA to its peer). */ - get localSequenceNumber() { - return this.dialogState.localSequenceNumber; - } - /** Remote sequence number (used to order requests from its peer to the UA). */ - get remoteSequenceNumber() { - return this.dialogState.remoteSequenceNumber; - } - /** Local URI. */ - get localURI() { - return this.dialogState.localURI; - } - /** Remote URI. */ - get remoteURI() { - return this.dialogState.remoteURI; - } - /** Remote target. */ - get remoteTarget() { - return this.dialogState.remoteTarget; - } - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get routeSet() { - return this.dialogState.routeSet; - } - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get secure() { - return this.dialogState.secure; - } - /** The user agent core servicing this dialog. */ - get userAgentCore() { - return this.core; - } - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm() { - this.dialogState.early = false; - } - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - } - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - recomputeRouteSet(message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - } - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - createOutgoingRequestMessage(method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - const toUri = this.remoteURI; - const toTag = this.remoteTag; - const fromUri = this.localURI; - const fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - const callId = this.callId; - let cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - const ruri = this.remoteTarget; - const routeSet = this.routeSet; - const extraHeaders = options && options.extraHeaders; - const body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId, - cseq, - fromTag, - toTag, - routeSet - }, extraHeaders, body); - return message; - } - /** - * Increment the local sequence number by one. - * It feels like this should be protected, but the current authentication handling currently - * needs this to keep the dialog in sync when "auto re-sends" request messages. - * @internal - */ - incrementLocalSequenceNumber() { - if (!this.dialogState.localSequenceNumber) { - throw new Error("Local sequence number undefined."); - } - this.dialogState.localSequenceNumber += 1; - } - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - sequenceGuard(message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - } -} - - -/***/ }), -/* 8 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Parameters"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["URI"]; }); - -/* harmony import */ var _methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _methods__WEBPACK_IMPORTED_MODULE_1__) if(["Grammar","NameAddrHeader","Parameters","URI","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _methods__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _body__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["fromBodyLegacy"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["isBody"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return _body__WEBPACK_IMPORTED_MODULE_2__["getBody"]; }); - -/* harmony import */ var _digest_authentication__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return _digest_authentication__WEBPACK_IMPORTED_MODULE_3__["DigestAuthentication"]; }); - -/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return _incoming_message__WEBPACK_IMPORTED_MODULE_4__["IncomingMessage"]; }); - -/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return _incoming_request_message__WEBPACK_IMPORTED_MODULE_5__["IncomingRequestMessage"]; }); - -/* harmony import */ var _incoming_request__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(37); -/* harmony import */ var _incoming_request__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_incoming_request__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _incoming_request__WEBPACK_IMPORTED_MODULE_6__) if(["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _incoming_request__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(33); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return _incoming_response_message__WEBPACK_IMPORTED_MODULE_7__["IncomingResponseMessage"]; }); - -/* harmony import */ var _incoming_response__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(38); -/* harmony import */ var _incoming_response__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_incoming_response__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _incoming_response__WEBPACK_IMPORTED_MODULE_8__) if(["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _incoming_response__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(34); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return _outgoing_request_message__WEBPACK_IMPORTED_MODULE_9__["OutgoingRequestMessage"]; }); - -/* harmony import */ var _outgoing_request__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(39); -/* harmony import */ var _outgoing_request__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_outgoing_request__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _outgoing_request__WEBPACK_IMPORTED_MODULE_10__) if(["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","OutgoingRequestMessage","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _outgoing_request__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _outgoing_response__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(40); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return _outgoing_response__WEBPACK_IMPORTED_MODULE_11__["constructOutgoingResponse"]; }); - -/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(41); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _parser__WEBPACK_IMPORTED_MODULE_12__["Parser"]; }); - -// Grammar - -// Directories - -// Files - - - - - - - - - - - - - -/***/ }), -/* 9 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"]; }); - -/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return _name_addr_header__WEBPACK_IMPORTED_MODULE_1__["NameAddrHeader"]; }); - -/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _parameters__WEBPACK_IMPORTED_MODULE_2__["Parameters"]; }); - -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return _uri__WEBPACK_IMPORTED_MODULE_3__["URI"]; }); - - - - - - - -/***/ }), -/* 10 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Grammar", function() { return Grammar; }); -/* harmony import */ var _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); -/* eslint-disable @typescript-eslint/no-namespace */ -/* eslint-disable no-inner-declarations */ - -/** - * Grammar. - * @internal - */ -var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function parse(input, startRule) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const options = { startRule }; - try { - _pegjs_dist_grammar__WEBPACK_IMPORTED_MODULE_0__["parse"](input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar || (Grammar = {})); - - -/***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyntaxError", function() { return SyntaxError; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); -/* harmony import */ var _name_addr_header__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs - - -class SyntaxError extends Error { - constructor(message, expected, found, location) { - super(); - this.message = message; - this.expected = expected; - this.found = found; - this.location = location; - this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(this, SyntaxError); - } - } - static buildMessage(expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) - .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) - .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - const escapedParts = expectation.parts.map((part) => { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - const descriptions = expected1.map(describeExpectation); - let i; - let j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - } -} -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - const peg$FAILED = {}; - const peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - let peg$startRuleIndex = 119; - const peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new _uri__WEBPACK_IMPORTED_MODULE_1__["URI"](options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new _uri__WEBPACK_IMPORTED_MODULE_1__["URI"](options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new _uri__WEBPACK_IMPORTED_MODULE_1__["URI"](options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new _name_addr_header__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - const peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map((ch) => ch.charCodeAt(0) - 32); - } - function peg$parseRule(index) { - const bc = peg$bytecode[index]; - let ip = 0; - const ips = []; - let end = bc.length; - const ends = []; - const stack = []; - let params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -const parse = peg$parse; - - -/***/ }), -/* 12 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NameAddrHeader", function() { return NameAddrHeader; }); -/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); - -/** - * Name Address SIP header. - * @public - */ -class NameAddrHeader extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - constructor(uri, displayName, parameters) { - super(parameters); - this.uri = uri; - this._displayName = displayName; - } - get friendlyName() { - return this.displayName || this.uri.aor; - } - get displayName() { return this._displayName; } - set displayName(value) { - this._displayName = value; - } - clone() { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - } - toString() { - let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (const parameter in this.parameters) { - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - } -} - - -/***/ }), -/* 13 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return Parameters; }); -/** - * @internal - */ -class Parameters { - constructor(parameters) { - this.parameters = {}; - for (const param in parameters) { - // eslint-disable-next-line no-prototype-builtins - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setParam(key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - } - getParam(key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - } - hasParam(key) { - if (key) { - // eslint-disable-next-line no-prototype-builtins - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - deleteParam(parameter) { - parameter = parameter.toLowerCase(); - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - const value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - } - clearParams() { - this.parameters = {}; - } -} - - -/***/ }), -/* 14 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; }); -/* harmony import */ var _parameters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** - * URI. - * @public - */ -class URI extends _parameters__WEBPACK_IMPORTED_MODULE_0__["Parameters"] { - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - constructor(scheme, user, host, port, parameters, headers) { - super(parameters); - this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (const header in headers) { - // eslint-disable-next-line no-prototype-builtins - if (headers.hasOwnProperty(header)) { - this.setHeader(header, headers[header]); - } - } - // Raw URI - this.raw = { - scheme, - user, - host, - port - }; - // Normalized URI - this.normal = { - scheme: scheme.toLowerCase(), - user, - host: host.toLowerCase(), - port - }; - } - get scheme() { return this.normal.scheme; } - set scheme(value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - } - get user() { return this.normal.user; } - set user(value) { - this.normal.user = this.raw.user = value; - } - get host() { return this.normal.host; } - set host(value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - } - get aor() { return this.normal.user + "@" + this.normal.host; } - get port() { return this.normal.port; } - set port(value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - } - setHeader(name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - } - getHeader(name) { - if (name) { - return this.headers[this.headerize(name)]; - } - } - hasHeader(name) { - // eslint-disable-next-line no-prototype-builtins - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - } - deleteHeader(header) { - header = this.headerize(header); - // eslint-disable-next-line no-prototype-builtins - if (this.headers.hasOwnProperty(header)) { - const value = this.headers[header]; - delete this.headers[header]; - return value; - } - } - clearHeaders() { - this.headers = {}; - } - clone() { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - } - toRaw() { - return this._toString(this._raw); - } - toString() { - return this._toString(this._normal); - } - get _normal() { return this.normal; } - get _raw() { return this.raw; } - _toString(uri) { - let uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (const parameter in this.parameters) { - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - const headers = []; - for (const header in this.headers) { - // eslint-disable-next-line no-prototype-builtins - if (this.headers.hasOwnProperty(header)) { - for (const idx in this.headers[header]) { - // eslint-disable-next-line no-prototype-builtins - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - } - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - escapeUser(user) { - let decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - // eslint-disable-next-line no-useless-catch - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - headerize(str) { - const exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - const name = str.toLowerCase().replace(/_/g, "-").split("-"); - const parts = name.length; - let hname = ""; - for (let part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } -} - - -/***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["C"]; }); - -/* harmony import */ var _ack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); -/* harmony import */ var _ack__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_ack__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _ack__WEBPACK_IMPORTED_MODULE_1__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _ack__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_bye__WEBPACK_IMPORTED_MODULE_2__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _bye__WEBPACK_IMPORTED_MODULE_2__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _bye__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _cancel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19); -/* harmony import */ var _cancel__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cancel__WEBPACK_IMPORTED_MODULE_3__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _cancel__WEBPACK_IMPORTED_MODULE_3__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _cancel__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_info__WEBPACK_IMPORTED_MODULE_4__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _info__WEBPACK_IMPORTED_MODULE_4__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _info__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _invite__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(21); -/* harmony import */ var _invite__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_invite__WEBPACK_IMPORTED_MODULE_5__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _invite__WEBPACK_IMPORTED_MODULE_5__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _invite__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(22); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_message__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _message__WEBPACK_IMPORTED_MODULE_6__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _message__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _notify__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(23); -/* harmony import */ var _notify__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_notify__WEBPACK_IMPORTED_MODULE_7__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _notify__WEBPACK_IMPORTED_MODULE_7__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _notify__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _prack__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(24); -/* harmony import */ var _prack__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_prack__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _prack__WEBPACK_IMPORTED_MODULE_8__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _prack__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _publish__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(25); -/* harmony import */ var _publish__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_publish__WEBPACK_IMPORTED_MODULE_9__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _publish__WEBPACK_IMPORTED_MODULE_9__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _publish__WEBPACK_IMPORTED_MODULE_9__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(26); -/* harmony import */ var _register__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_register__WEBPACK_IMPORTED_MODULE_10__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _register__WEBPACK_IMPORTED_MODULE_10__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _register__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _refer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(27); -/* harmony import */ var _refer__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_refer__WEBPACK_IMPORTED_MODULE_11__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _refer__WEBPACK_IMPORTED_MODULE_11__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _refer__WEBPACK_IMPORTED_MODULE_11__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _subscribe__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(28); -/* harmony import */ var _subscribe__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_subscribe__WEBPACK_IMPORTED_MODULE_12__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscribe__WEBPACK_IMPORTED_MODULE_12__) if(["C","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscribe__WEBPACK_IMPORTED_MODULE_12__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - - - - - - - - - - - - -/***/ }), -/* 16 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return C; }); -/* eslint-disable @typescript-eslint/no-namespace */ -/** - * SIP Methods - * @internal - */ -var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C || (C = {})); - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 18 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 20 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 21 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 23 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 25 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 26 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 27 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 28 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 29 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromBodyLegacy", function() { return fromBodyLegacy; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBody", function() { return isBody; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBody", function() { return getBody; }); -/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30); -/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(33); -/* harmony import */ var _outgoing_request_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34); - - - -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -function fromBodyLegacy(bodyLegacy) { - const content = typeof bodyLegacy === "string" ? bodyLegacy : bodyLegacy.body; - const contentType = typeof bodyLegacy === "string" ? "application/sdp" : bodyLegacy.contentType; - const contentDisposition = contentTypeToContentDisposition(contentType); - const body = { contentDisposition, contentType, content }; - return body; -} -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined - ? true - : typeof body.contentDisposition === "string"; -} -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -function getBody(message) { - let contentDisposition; - let contentType; - let content; - // We're in UAS role, receiving incoming request - if (message instanceof _incoming_request_message__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - if (message.body) { - // FIXME: Parsing needs typing - const parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof _incoming_response_message__WEBPACK_IMPORTED_MODULE_1__["IncomingResponseMessage"]) { - if (message.body) { - // FIXME: Parsing needs typing - const parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof _outgoing_request_message__WEBPACK_IMPORTED_MODULE_2__["OutgoingRequestMessage"]) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition, - contentType, - content - }; -} - - -/***/ }), -/* 30 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingRequestMessage", function() { return IncomingRequestMessage; }); -/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); - -/** - * Incoming request message. - * @public - */ -class IncomingRequestMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { - constructor() { - super(); - } -} - - -/***/ }), -/* 31 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingMessage", function() { return IncomingMessage; }); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); - - -/** - * Incoming message. - * @public - */ -class IncomingMessage { - constructor() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - addHeader(name, value) { - const header = { raw: value }; - name = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - } - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name) { - const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - } - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - getHeaders(name) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - const result = []; - if (!header) { - return []; - } - for (const headerPart of header) { - result.push(headerPart.raw); - } - return result; - } - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name) { - return !!this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - } - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - parseHeader(name, idx = 0) { - name = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - const header = this.headers[name][idx]; - const value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - } - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - s(name, idx = 0) { - return this.parseHeader(name, idx); - } - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - setHeader(name, value) { - this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)] = [{ raw: value }]; - } - toString() { - return this.data; - } -} - - -/***/ }), -/* 32 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomToken", function() { return createRandomToken; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getReasonPhrase", function() { return getReasonPhrase; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newTag", function() { return newTag; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "headerize", function() { return headerize; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8Length", function() { return utf8Length; }); -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -const REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; -/** - * @param size - - * @param base - - * @internal - */ -function createRandomToken(size, base = 32) { - let token = ""; - for (let i = 0; i < size; i++) { - const r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -/** - * @internal - */ -function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -/** - * @internal - */ -function newTag() { - return createRandomToken(10); -} -/** - * @param str - - * @internal - */ -function headerize(str) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const exceptions = { - "Call-Id": "Call-ID", - Cseq: "CSeq", - "Min-Se": "Min-SE", - Rack: "RAck", - Rseq: "RSeq", - "Www-Authenticate": "WWW-Authenticate" - }; - const name = str.toLowerCase().replace(/_/g, "-").split("-"); - const parts = name.length; - let hname = ""; - for (let part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -/** - * @param str - - * @internal - */ -function utf8Length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} - - -/***/ }), -/* 33 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncomingResponseMessage", function() { return IncomingResponseMessage; }); -/* harmony import */ var _incoming_message__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); - -/** - * Incoming response message. - * @public - */ -class IncomingResponseMessage extends _incoming_message__WEBPACK_IMPORTED_MODULE_0__["IncomingMessage"] { - constructor() { - super(); - } -} - - -/***/ }), -/* 34 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OutgoingRequestMessage", function() { return OutgoingRequestMessage; }); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); - - -/** - * Outgoing SIP request message. - * @public - */ -class OutgoingRequestMessage { - constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - // Initialize default options - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = Object.assign(Object.assign({}, this.options), options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : Object(_utils__WEBPACK_IMPORTED_MODULE_1__["newTag"])(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - static getDefaultOptions() { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - } - static makeNameAddrHeader(uri, displayName, tag) { - const parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new _grammar__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"](uri, displayName, parameters); - } - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name) { - const header = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const exHeader of this.extraHeaders) { - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - } - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - getHeaders(name) { - const result = []; - const headerArray = this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]; - if (headerArray) { - for (const headerPart of headerArray) { - result.push(headerPart); - } - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const exHeader of this.extraHeaders) { - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - } - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name) { - if (this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)]) { - return true; - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const extraHeader of this.extraHeaders) { - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - } - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - setHeader(name, value) { - this.headers[Object(_utils__WEBPACK_IMPORTED_MODULE_1__["headerize"])(name)] = value instanceof Array ? value : [value]; - } - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param transport - The sent protocol transport. - */ - setViaHeader(branch, transport) { - // FIXME: Hack - if (this.options.hackViaTcp) { - transport = "TCP"; - } - let via = "SIP/2.0/" + transport; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - } - toString() { - let msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (const header in this.headers) { - if (this.headers[header]) { - for (const headerPart of this.headers[header]) { - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (const header of this.extraHeaders) { - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + Object(_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - } -} - - -/***/ }), -/* 35 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DigestAuthentication", function() { return DigestAuthentication; }); -/* harmony import */ var _md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); - - -function MD5(s) { - return _md5__WEBPACK_IMPORTED_MODULE_0__["Md5"].hashStr(s); -} -/** - * Digest Authentication. - * @internal - */ -class DigestAuthentication { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - constructor(loggerFactory, ha1, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.ha1 = ha1; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - authenticate(request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - } - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - toString() { - const authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - } - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - updateNcHex() { - const hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - } - /** - * Generate Digest 'response' value. - */ - calculateResponse(body) { - let ha1, ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - ha1 = this.ha1; - if (ha1 === "" || ha1 === undefined) { - ha1 = MD5(this.username + ":" + this.realm + ":" + this.password); - } - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = MD5(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)` - this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = MD5(this.method + ":" + this.uri + ":" + MD5(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = MD5(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = MD5(ha1 + ":" + this.nonce + ":" + ha2); - } - } -} - - -/***/ }), -/* 36 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Md5", function() { return Md5; }); -/* eslint-disable */ -// -// Scoped from: https://github.com/cotag/ts-md5 -// -/* - -TypeScript Md5 -============== - -Based on work by -* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html -* André Cruz: https://github.com/satazor/SparkMD5 -* Raymond Hill: https://github.com/gorhill/yamd5.js - -Effectively a TypeScrypt re-write of Raymond Hill JS Library - -The MIT License (MIT) - -Copyright (C) 2014 Raymond Hill - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2015 André Cruz - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - - -*/ -class Md5 { - constructor() { - this._dataLength = 0; - this._bufferLength = 0; - this._state = new Int32Array(4); - this._buffer = new ArrayBuffer(68); - this._buffer8 = new Uint8Array(this._buffer, 0, 68); - this._buffer32 = new Uint32Array(this._buffer, 0, 17); - this.start(); - } - static hashStr(str, raw = false) { - return this.onePassHasher - .start() - .appendStr(str) - .end(raw); - } - static hashAsciiStr(str, raw = false) { - return this.onePassHasher - .start() - .appendAsciiStr(str) - .end(raw); - } - static _hex(x) { - const hc = Md5.hexChars; - const ho = Md5.hexOut; - let n; - let offset; - let j; - let i; - for (i = 0; i < 4; i += 1) { - offset = i * 8; - n = x[i]; - for (j = 0; j < 8; j += 2) { - ho[offset + 1 + j] = hc.charAt(n & 0x0F); - n >>>= 4; - ho[offset + 0 + j] = hc.charAt(n & 0x0F); - n >>>= 4; - } - } - return ho.join(''); - } - static _md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - // ff() - a += (b & c | ~b & d) + k[0] - 680876936 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[1] - 389564586 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[2] + 606105819 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[3] - 1044525330 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[4] - 176418897 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[5] + 1200080426 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[6] - 1473231341 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[7] - 45705983 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[8] + 1770035416 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[9] - 1958414417 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[10] - 42063 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[11] - 1990404162 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[12] + 1804603682 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[13] - 40341101 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[14] - 1502002290 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[15] + 1236535329 | 0; - b = (b << 22 | b >>> 10) + c | 0; - // gg() - a += (b & d | c & ~d) + k[1] - 165796510 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[6] - 1069501632 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[11] + 643717713 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[0] - 373897302 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[5] - 701558691 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[10] + 38016083 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[15] - 660478335 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[4] - 405537848 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[9] + 568446438 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[14] - 1019803690 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[3] - 187363961 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[8] + 1163531501 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[13] - 1444681467 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[2] - 51403784 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[7] + 1735328473 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[12] - 1926607734 | 0; - b = (b << 20 | b >>> 12) + c | 0; - // hh() - a += (b ^ c ^ d) + k[5] - 378558 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[8] - 2022574463 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[11] + 1839030562 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[14] - 35309556 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[1] - 1530992060 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[4] + 1272893353 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[7] - 155497632 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[10] - 1094730640 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[13] + 681279174 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[0] - 358537222 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[3] - 722521979 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[6] + 76029189 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[9] - 640364487 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[12] - 421815835 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[15] + 530742520 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[2] - 995338651 | 0; - b = (b << 23 | b >>> 9) + c | 0; - // ii() - a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; - b = (b << 21 | b >>> 11) + c | 0; - x[0] = a + x[0] | 0; - x[1] = b + x[1] | 0; - x[2] = c + x[2] | 0; - x[3] = d + x[3] | 0; - } - start() { - this._dataLength = 0; - this._bufferLength = 0; - this._state.set(Md5.stateIdentity); - return this; - } - // Char to code point to to array conversion: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt - // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown - appendStr(str) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let code; - let i; - for (i = 0; i < str.length; i += 1) { - code = str.charCodeAt(i); - if (code < 128) { - buf8[bufLen++] = code; - } - else if (code < 0x800) { - buf8[bufLen++] = (code >>> 6) + 0xC0; - buf8[bufLen++] = code & 0x3F | 0x80; - } - else if (code < 0xD800 || code > 0xDBFF) { - buf8[bufLen++] = (code >>> 12) + 0xE0; - buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; - buf8[bufLen++] = (code & 0x3F) | 0x80; - } - else { - code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; - if (code > 0x10FFFF) { - throw new Error('Unicode standard supports code points up to U+10FFFF'); - } - buf8[bufLen++] = (code >>> 18) + 0xF0; - buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; - buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; - buf8[bufLen++] = (code & 0x3F) | 0x80; - } - if (bufLen >= 64) { - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen -= 64; - buf32[0] = buf32[16]; - } - } - this._bufferLength = bufLen; - return this; - } - appendAsciiStr(str) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let i; - let j = 0; - for (;;) { - i = Math.min(str.length - j, 64 - bufLen); - while (i--) { - buf8[bufLen++] = str.charCodeAt(j++); - } - if (bufLen < 64) { - break; - } - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen = 0; - } - this._bufferLength = bufLen; - return this; - } - appendByteArray(input) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let i; - let j = 0; - for (;;) { - i = Math.min(input.length - j, 64 - bufLen); - while (i--) { - buf8[bufLen++] = input[j++]; - } - if (bufLen < 64) { - break; - } - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen = 0; - } - this._bufferLength = bufLen; - return this; - } - getState() { - const self = this; - const s = self._state; - return { - buffer: String.fromCharCode.apply(null, self._buffer8), - buflen: self._bufferLength, - length: self._dataLength, - state: [s[0], s[1], s[2], s[3]] - }; - } - setState(state) { - const buf = state.buffer; - const x = state.state; - const s = this._state; - let i; - this._dataLength = state.length; - this._bufferLength = state.buflen; - s[0] = x[0]; - s[1] = x[1]; - s[2] = x[2]; - s[3] = x[3]; - for (i = 0; i < buf.length; i += 1) { - this._buffer8[i] = buf.charCodeAt(i); - } - } - end(raw = false) { - const bufLen = this._bufferLength; - const buf8 = this._buffer8; - const buf32 = this._buffer32; - const i = (bufLen >> 2) + 1; - let dataBitsLen; - this._dataLength += bufLen; - buf8[bufLen] = 0x80; - buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; - buf32.set(Md5.buffer32Identity.subarray(i), i); - if (bufLen > 55) { - Md5._md5cycle(this._state, buf32); - buf32.set(Md5.buffer32Identity); - } - // Do the final computation based on the tail and length - // Beware that the final length may not fit in 32 bits so we take care of that - dataBitsLen = this._dataLength * 8; - if (dataBitsLen <= 0xFFFFFFFF) { - buf32[14] = dataBitsLen; - } - else { - const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); - if (matches === null) { - return; - } - const lo = parseInt(matches[2], 16); - const hi = parseInt(matches[1], 16) || 0; - buf32[14] = lo; - buf32[15] = hi; - } - Md5._md5cycle(this._state, buf32); - return raw ? this._state : Md5._hex(this._state); - } -} -// Private Static Variables -Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); -Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); -Md5.hexChars = '0123456789abcdef'; -Md5.hexOut = []; -// Permanent instance is to use for one-call hashing -Md5.onePassHasher = new Md5(); -if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { - console.error('Md5 self test failed.'); -} - - -/***/ }), -/* 37 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 39 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 40 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "constructOutgoingResponse", function() { return constructOutgoingResponse; }); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(32); - -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -function constructOutgoingResponse(message, options) { - const CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_utils__WEBPACK_IMPORTED_MODULE_0__["getReasonPhrase"])(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - let response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - const fromHeader = "From: " + message.getHeader("From") + CRLF; - const callIdHeader = "Call-ID: " + message.callId + CRLF; - const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - const viaHeaders = message.getHeaders("via").reduce((previous, current) => { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - let toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - let toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = Object(_utils__WEBPACK_IMPORTED_MODULE_0__["newTag"])(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - let supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - let userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - let extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce((previous, current) => { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + Object(_utils__WEBPACK_IMPORTED_MODULE_0__["utf8Length"])(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} - - -/***/ }), -/* 41 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return Parser; }); -/* harmony import */ var _grammar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30); -/* harmony import */ var _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); -/* eslint-disable no-inner-declarations */ -/* eslint-disable @typescript-eslint/no-namespace */ - - - -/** - * Extract and parse every header of a SIP message. - * @internal - */ -var Parser; -(function (Parser) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function getHeader(data, headerStart) { - // 'start' position of the header. - let start = headerStart; - // 'end' position of the header. - let end = 0; - // 'partial end' position of the header. - let partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, headerStart, headerEnd) { - const hcolonIndex = data.indexOf(":", headerStart); - const headerName = data.substring(headerStart, hcolonIndex).trim(); - const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach((header) => { - message.addHeader("record-route", headerValue.substring(header.position, header.offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = header.parsed; - }); - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach((header) => { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["IncomingResponseMessage"]) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - function parseMessage(data, logger) { - let headerStart = 0; - let headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - const firstLine = data.substring(0, headerEnd); - const parsed = _grammar__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(firstLine, "Request_Response"); - let message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new _incoming_request_message__WEBPACK_IMPORTED_MODULE_1__["IncomingRequestMessage"](); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new _incoming_response_message__WEBPACK_IMPORTED_MODULE_2__["IncomingResponseMessage"](); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - // Loop over every line in data. Detect the end of each header and parse - // it or simply add to the headers collection. - let bodyStart; - // eslint-disable-next-line no-constant-condition - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - const parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - // RFC3261 18.3. - // If there are additional bytes in the transport packet - // beyond the end of the body, they MUST be discarded. - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser || (Parser = {})); - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 43 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDialog", function() { return SessionDialog; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); -/* harmony import */ var _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62); -/* harmony import */ var _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(64); -/* harmony import */ var _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(66); -/* harmony import */ var _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(67); -/* harmony import */ var _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(68); -/* harmony import */ var _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(69); -/* harmony import */ var _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(70); -/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(71); -/* harmony import */ var _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); -/* harmony import */ var _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); -/* harmony import */ var _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); -/* harmony import */ var _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); -/* harmony import */ var _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(76); -/* harmony import */ var _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(77); -/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(7); - - - - - - - - - - - - - - - - - - - -/** - * Session Dialog. - * @public - */ -class SessionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_18__["Dialog"] { - constructor(initialTransaction, core, state, delegate) { - super(core, state); - this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - this.ackWait = false; - /** True if processing an ACK to the initial transaction 2xx (UAS only). */ - this.ackProcessing = false; - this.delegate = delegate; - if (initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!this.early) { - this.start2xxRetransmissionTimer(); - } - this.signalingStateTransition(initialTransaction.request); - this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - this.logger.log(`INVITE dialog ${this.id} constructed`); - } - dispose() { - super.dispose(); - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log(`INVITE dialog ${this.id} destroyed`); - } - // FIXME: Need real state machine - get sessionState() { - if (this.early) { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Early; - } - else if (this.ackWait) { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].AckWait; - } - else if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed) { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Terminated; - } - else { - return _session__WEBPACK_IMPORTED_MODULE_1__["SessionState"].Confirmed; - } - } - /** The state of the offer/answer exchange. */ - get signalingState() { - return this._signalingState; - } - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get offer() { - return this._offer; - } - /** The current answer. Undefined unless signaling state Stable. */ - get answer() { - return this._answer; - } - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm() { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - super.confirm(); - } - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - reConfirm() { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - } - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - ack(options = {}) { - this.logger.log(`INVITE dialog ${this.id} sending ACK request`); - let transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"])) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, { - cseq: transaction.request.cseq, - extraHeaders: options.extraHeaders, - body: options.body - }); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message }; - } - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - bye(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending BYE request`); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new _user_agents_bye_user_agent_client__WEBPACK_IMPORTED_MODULE_4__["ByeUserAgentClient"](this, delegate, options); - } - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - info(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending INFO request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new _user_agents_info_user_agent_client__WEBPACK_IMPORTED_MODULE_6__["InfoUserAgentClient"](this, delegate, options); - } - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - invite(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending INVITE request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new _user_agents_re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"](this, delegate, options); - } - /** - * A UAC MAY associate a MESSAGE request with an existing dialog. If a - * MESSAGE request is sent within a dialog, it is "associated" with any - * media session or sessions associated with that dialog. - * https://tools.ietf.org/html/rfc3428#section-4 - * @param options - Options bucket. - */ - message(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - const message = this.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, options); - return new _user_agents_message_user_agent_client__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentClient"](this.core, message, delegate); - } - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - notify(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new _user_agents_notify_user_agent_client__WEBPACK_IMPORTED_MODULE_10__["NotifyUserAgentClient"](this, delegate, options); - } - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - prack(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); - return new _user_agents_prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["PrackUserAgentClient"](this, delegate, options); - } - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - refer(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending REFER request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new _user_agents_refer_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["ReferUserAgentClient"](this, delegate, options); - } - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message) { - this.logger.log(`INVITE dialog ${this.id} received ${message.method} request`); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteClientTransaction"]) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - const promiseOrVoid = this.delegate.onAck({ message }); - if (promiseOrVoid instanceof Promise) { - this.ackProcessing = true; // make sure this is always reset to false - promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false)); - } - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log(`INVITE dialog ${this.id} rejected out of order ${message.method} request.`); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - super.receiveRequest(message); - // Handle various INVITE related cross-over, glare and race conditions - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - // Hopefully this message is helpful... - const warning = () => { - const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK"; - this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`); - let msg = "RFC 5407 suggests the following to avoid this race condition... "; - msg += " Note: Implementation issues are outside the scope of this document,"; - msg += " but the following tip is provided for avoiding race conditions of"; - msg += " this type. The caller can delay sending re-INVITE F6 for some period"; - msg += " of time (2 seconds, perhaps), after which the caller can reasonably"; - msg += " assume that its ACK has been received. Implementors can decouple the"; - msg += " actions of the user (e.g., pressing the hold button) from the actions"; - msg += " of the protocol (the sending of re-INVITE F6), so that the UA can"; - msg += " behave like this. In this case, it is the implementor's choice as to"; - msg += " how long to wait. In most cases, such an implementation may be"; - msg += " useful to prevent the type of race condition shown in this section."; - msg += " This document expresses no preference about whether or not they"; - msg += " should wait for an ACK to be delivered. After considering the impact"; - msg += " on user experience, implementors should decide whether or not to wait"; - msg += " for a while, because the user experience depends on the"; - msg += " implementation and has no direct bearing on protocol behavior."; - this.logger.warn(msg); - return; // drop re-INVITE request message - }; - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - const retryAfter = Math.floor(Math.random() * 10) + 1; - const extraHeaders = [`Retry-After: ${retryAfter}`]; - // There may be ONLY ONE offer/answer negotiation in progress for a - // single dialog at any point in time. Section 4 explains how to ensure - // this. - // https://tools.ietf.org/html/rfc6337#section-2.2 - if (this.ackProcessing) { - // UAS-IsI: While an INVITE server transaction is incomplete or ACK - // transaction associated with an offer/answer is incomplete, - // a UA must reject another INVITE request with a 500 - // response. - // https://tools.ietf.org/html/rfc6337#section-4.3 - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - warning(); - return; - } - // 3.1.4. Callee Receives re-INVITE (Established State) While in the - // Moratorium State (Case 1) - // https://tools.ietf.org/html/rfc5407#section-3.1.4 - // 3.1.5. Callee Receives re-INVITE (Established State) While in the - // Moratorium State (Case 2) - // https://tools.ietf.org/html/rfc5407#section-3.1.5 - if (this.ackWait && this.signalingState !== _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable) { - // This scenario is basically the same as that of Section 3.1.4, but - // differs in sending an offer in the 200 and an answer in the ACK. In - // contrast to the previous case, the offer in the 200 (F3) and the - // offer in the re-INVITE (F6) collide with each other. - // - // Bob sends a 491 to the re-INVITE (F6) since he is not able to - // properly handle a new request until he receives an answer. (Note: - // 500 with a Retry-After header may be returned if the 491 response is - // understood to indicate request collision. However, 491 is - // recommended here because 500 applies to so many cases that it is - // difficult to determine what the real problem was.) - // https://tools.ietf.org/html/rfc5407#section-3.1.5 - // UAS-IsI: While an INVITE server transaction is incomplete or ACK - // transaction associated with an offer/answer is incomplete, - // a UA must reject another INVITE request with a 500 - // response. - // https://tools.ietf.org/html/rfc6337#section-4.3 - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - warning(); - return; - } - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - // FIXME: parser needs to be typed... - const contact = message.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - const uas = new _user_agents_bye_user_agent_server__WEBPACK_IMPORTED_MODULE_5__["ByeUserAgentServer"](this, message); - this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); - this.dispose(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - const uas = new _user_agents_info_user_agent_server__WEBPACK_IMPORTED_MODULE_7__["InfoUserAgentServer"](this, message); - this.delegate && this.delegate.onInfo - ? this.delegate.onInfo(uas) - : uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - const uas = new _user_agents_re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["ReInviteUserAgentServer"](this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE: - { - const uas = new _user_agents_message_user_agent_server__WEBPACK_IMPORTED_MODULE_9__["MessageUserAgentServer"](this.core, message); - this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_11__["NotifyUserAgentServer"](this, message); - this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - const uas = new _user_agents_prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"](this, message); - this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - const uas = new _user_agents_refer_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["ReferUserAgentServer"](this, message); - this.delegate && this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject(); - } - break; - default: - { - this.logger.log(`INVITE dialog ${this.id} received unimplemented ${message.method} request`); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - } - /** - * Guard against out of order reliable provisional responses and retransmissions. - * Returns false if the response should be discarded, otherwise true. - * @param message - Incoming response message within this dialog. - */ - reliableSequenceGuard(message) { - const statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - const requireHeader = message.getHeader("require"); - const rseqHeader = message.getHeader("rseq"); - const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - this.rseq = this.rseq ? this.rseq + 1 : rseq; - } - } - return true; - } - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - signalingStateRollback() { - if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer || - this.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - } - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - signalingStateTransition(message) { - const body = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["getBody"])(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"]) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (Object(_messages__WEBPACK_IMPORTED_MODULE_0__["isBody"])(message)) { - switch (this._signalingState) { - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial: - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveRemoteOffer: - this._signalingState = _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Stable; - this._answer = body; - break; - case _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - } - start2xxRetransmissionTimer() { - if (this.initialTransaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - const transaction = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; - const retransmission = () => { - if (!this.ackWait) { - this.invite2xxTimer = undefined; - return; - } - this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction.retransmitAcceptedResponse(); - timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); - this.invite2xxTimer = setTimeout(retransmission, timeout); - }; - this.invite2xxTimer = setTimeout(retransmission, timeout); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - const stateChanged = () => { - if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - transaction.removeStateChangeListener(stateChanged); - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - if (this.ackWait) { - if (this.delegate && this.delegate.onAckTimeout) { - this.delegate.onAckTimeout(); - } - else { - this.bye(); - } - } - } - }; - transaction.addStateChangeListener(stateChanged); - } - } - // FIXME: Refactor - startReInvite2xxRetransmissionTimer() { - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - const transaction = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - let timeout = _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T1; - const retransmission = () => { - if (!this.reinviteUserAgentServer) { - this.invite2xxTimer = undefined; - return; - } - this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction.retransmitAcceptedResponse(); - timeout = Math.min(timeout * 2, _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].T2); - this.invite2xxTimer = setTimeout(retransmission, timeout); - }; - this.invite2xxTimer = setTimeout(retransmission, timeout); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - const stateChanged = () => { - if (transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - transaction.removeStateChangeListener(stateChanged); - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction.addStateChangeListener(stateChanged); - } - } -} - - -/***/ }), -/* 44 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SessionState"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return _session__WEBPACK_IMPORTED_MODULE_0__["SignalingState"]; }); - -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46); -/* harmony import */ var _session_delegate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_session_delegate__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_delegate__WEBPACK_IMPORTED_MODULE_1__) if(["SessionState","SignalingState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_delegate__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - -/***/ }), -/* 45 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignalingState", function() { return SignalingState; }); -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState || (SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState || (SignalingState = {})); - - -/***/ }), -/* 46 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 47 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timers", function() { return Timers; }); -const T1 = 500; -const T2 = 4000; -const T4 = 5000; -/** - * Timers. - * @public - */ -const Timers = { - T1, - T2, - T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -/***/ }), -/* 48 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(49); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return _client_transaction__WEBPACK_IMPORTED_MODULE_0__["ClientTransaction"]; }); - -/* harmony import */ var _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return _invite_client_transaction__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"]; }); - -/* harmony import */ var _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(57); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return _invite_server_transaction__WEBPACK_IMPORTED_MODULE_2__["InviteServerTransaction"]; }); - -/* harmony import */ var _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(59); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return _non_invite_client_transaction__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"]; }); - -/* harmony import */ var _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return _non_invite_server_transaction__WEBPACK_IMPORTED_MODULE_4__["NonInviteServerTransaction"]; }); - -/* empty/unused harmony star reexport *//* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return _server_transaction__WEBPACK_IMPORTED_MODULE_5__["ServerTransaction"]; }); - -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(56); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return _transaction_state__WEBPACK_IMPORTED_MODULE_6__["TransactionState"]; }); - -/* harmony import */ var _transaction_user__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(61); -/* harmony import */ var _transaction_user__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_transaction_user__WEBPACK_IMPORTED_MODULE_7__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transaction_user__WEBPACK_IMPORTED_MODULE_7__) if(["ClientTransaction","InviteClientTransaction","InviteServerTransaction","NonInviteClientTransaction","NonInviteServerTransaction","ServerTransaction","TransactionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transaction_user__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(50); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return _transaction__WEBPACK_IMPORTED_MODULE_8__["Transaction"]; }); - - - - - - - - - - - - - -/***/ }), -/* 49 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientTransaction", function() { return ClientTransaction; }); -/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); - -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -class ClientTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { - constructor(_request, transport, user, state, loggerCategory) { - super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); - this._request = _request; - this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - _request.setViaHeader(this.id, transport.protocol); - } - static makeId(request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - } - /** The outgoing request the transaction handling. */ - get request() { - return this._request; - } - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - onRequestTimeout() { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - } -} - - -/***/ }), -/* 50 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transaction", function() { return Transaction; }); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); - -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -class Transaction { - constructor(_transport, _user, _id, _state, loggerCategory) { - this._transport = _transport; - this._user = _user; - this._id = _id; - this._state = _state; - this.listeners = new Array(); - this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - dispose() { - this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); - } - /** Transaction id. */ - get id() { - return this._id; - } - /** Transaction kind. Deprecated. */ - get kind() { - throw new Error("Invalid kind."); - } - /** Transaction state. */ - get state() { - return this._state; - } - /** Transaction transport. */ - get transport() { - return this._transport; - } - /** - * Sets up a function that will be called whenever the transaction state changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addStateChangeListener(listener, options) { - const onceWrapper = () => { - this.removeStateChangeListener(onceWrapper); - listener(); - }; - (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); - } - /** - * This is currently public so tests may spy on it. - * @internal - */ - notifyStateChangeListeners() { - this.listeners.slice().forEach((listener) => listener()); - } - /** - * Removes a listener previously registered with addStateListener. - * @param listener - Callback function. - */ - removeStateChangeListener(listener) { - this.listeners = this.listeners.filter((l) => l !== listener); - } - logTransportError(error, message) { - this.logger.error(error.message); - this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`); - this.logger.error(message); - } - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - send(message) { - return this.transport.send(message).catch((error) => { - // If the transport rejects, it SHOULD reject with a TransportError. - // But the transport may be external code, so we are careful - // make sure we convert it to a TransportError if need be. - if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"]) { - this.onTransportError(error); - throw error; - } - let transportError; - if (error && typeof error.message === "string") { - transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](error.message); - } - else { - transportError = new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransportError"](); - } - this.onTransportError(transportError); - throw transportError; - }); - } - setState(state) { - this.logger.debug(`State change to "${state}" on ${this.typeToString()} with id ${this.id}.`); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.notifyStateChangeListeners(); - } - typeToString() { - return "UnknownType"; - } -} - - -/***/ }), -/* 51 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"]; }); - -/* harmony import */ var _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(53); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return _transaction_state_error__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"]; }); - -/* harmony import */ var _transport_error__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return _transport_error__WEBPACK_IMPORTED_MODULE_2__["TransportError"]; }); - - - - - - -/***/ }), -/* 52 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Exception", function() { return Exception; }); -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -class Exception extends Error { - constructor(message) { - super(message); // 'Error' breaks prototype chain here - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain - } -} - - -/***/ }), -/* 53 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionStateError", function() { return TransactionStateError; }); -/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); - -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -class TransactionStateError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Transaction state error."); - } -} - - -/***/ }), -/* 54 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportError", function() { return TransportError; }); -/* harmony import */ var _exception__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52); - -/** - * Transport error. - * @public - */ -class TransportError extends _exception__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Unspecified transport error."); - } -} - - -/***/ }), -/* 55 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteClientTransaction", function() { return InviteClientTransaction; }); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); -/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); - - - -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -class InviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling, "sip.transaction.ict"); - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - this.B = setTimeout(() => this.timerB(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_B); - this.send(request.toString()).catch((error) => { - this.logTransportError(error, "Failed to send initial outgoing request."); - }); - } - /** - * Destructor. - */ - dispose() { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "ict"; - } - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - ackResponse(ack) { - const toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - ack.setViaHeader(id, this.transport.protocol); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch((error) => { - this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - } - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response) { - const statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - const ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - const message = `Received unexpected ${statusCode} response while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); - } - /** For logging. */ - typeToString() { - return "INVITE client transaction"; - } - ack(response) { - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - const ruri = this.request.ruri; - const callId = this.request.callId; - const cseq = this.request.cseq; - const from = this.request.getHeader("from"); - const to = response.getHeader("to"); - const via = this.request.getHeader("via"); - const route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - let ack = `ACK ${ruri} SIP/2.0\r\n`; - if (route) { - ack += `Route: ${route}\r\n`; - } - ack += `Via: ${via}\r\n`; - ack += `To: ${to}\r\n`; - ack += `From: ${from}\r\n`; - ack += `Call-ID: ${callId}\r\n`; - ack += `CSeq: ${cseq} ACK\r\n`; - ack += `Max-Forwards: 70\r\n`; - ack += `Content-Length: 0\r\n\r\n`; - // TOOO: "User-Agent" header - this.send(ack).catch((error) => { - this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted: - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.D = setTimeout(() => this.timerD(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { - this.M = setTimeout(() => this.timerM(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - timerA() { - // TODO - } - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - timerB() { - this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { - this.onRequestTimeout(); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - timerD() { - this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - timerM() { - this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Accepted) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 56 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransactionState", function() { return TransactionState; }); -/** - * Transaction state. - * @public - */ -var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState || (TransactionState = {})); - - -/***/ }), -/* 57 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteServerTransaction", function() { return InviteServerTransaction; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47); -/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(58); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(56); - - - - -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -class InviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_2__["ServerTransaction"] { - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding, "sip.transaction.ist"); - } - /** - * Destructor. - */ - dispose() { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "ist"; - } - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request) { - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE || request.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - return; - } - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `INVITE server transaction received unexpected ${request.method} request while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - receiveResponse(statusCode, response) { - if (statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; - this.logger.error(message); - throw new Error(message); - } - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - retransmitAcceptedResponse() { - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - } - } - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - } - /** For logging. */ - typeToString() { - return "INVITE server transaction"; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted: - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisional responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { - this.L = setTimeout(() => this.timerL(), _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(() => this.timerH(), _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(() => this.timerI(), _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - startProgressExtensionTimer() { - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(() => { - this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`); - if (!this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - this.send(this.lastProvisionalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, _timers__WEBPACK_IMPORTED_MODULE_1__["Timers"].PROVISIONAL_RESPONSE_INTERVAL); - } - } - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - stopProgressExtensionTimer() { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - } - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerG() { - // TODO - } - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerH() { - this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); - } - } - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerI() { - this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); - } - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - timerL() { - this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 58 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerTransaction", function() { return ServerTransaction; }); -/* harmony import */ var _transaction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); - -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -class ServerTransaction extends _transaction__WEBPACK_IMPORTED_MODULE_0__["Transaction"] { - constructor(_request, transport, user, state, loggerCategory) { - super(transport, user, _request.viaBranch, state, loggerCategory); - this._request = _request; - this.user = user; - } - /** The incoming request the transaction handling. */ - get request() { - return this._request; - } -} - - -/***/ }), -/* 59 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteClientTransaction", function() { return NonInviteClientTransaction; }); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); -/* harmony import */ var _client_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); - - - -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -class NonInviteClientTransaction extends _client_transaction__WEBPACK_IMPORTED_MODULE_1__["ClientTransaction"] { - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nict"); - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - this.F = setTimeout(() => this.timerF(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_F); - this.send(request.toString()).catch((error) => { - this.logTransportError(error, "Failed to send initial outgoing request."); - }); - } - /** - * Destructor. - */ - dispose() { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "nict"; - } - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response) { - const statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `Non-INVITE client transaction received unexpected ${statusCode} response while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the fail over mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Transport error - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); - } - /** For logging. */ - typeToString() { - return "non-INVITE client transaction"; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && - this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(() => this.timerK(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - timerF() { - this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying || this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - this.onRequestTimeout(); - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - timerK() { - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 60 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonInviteServerTransaction", function() { return NonInviteServerTransaction; }); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47); -/* harmony import */ var _server_transaction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58); -/* harmony import */ var _transaction_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56); - - - -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -class NonInviteServerTransaction extends _server_transaction__WEBPACK_IMPORTED_MODULE_1__["ServerTransaction"] { - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying, "sip.transaction.nist"); - } - /** - * Destructor. - */ - dispose() { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "nist"; - } - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - receiveRequest(request) { - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - } - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - receiveResponse(statusCode, response) { - if (statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `Non-INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; - this.logger.error(message); - throw new Error(message); - } - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated, true); - } - /** For logging. */ - typeToString() { - return "non-INVITE server transaction"; - } - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying: - invalidStateTransition(); - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Trying && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding) { - invalidStateTransition(); - } - break; - case _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated: - if (this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Proceeding && this.state !== _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.J = setTimeout(() => this.timerJ(), _timers__WEBPACK_IMPORTED_MODULE_0__["Timers"].TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated) { - this.dispose(); - } - this.setState(newState); - } - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - timerJ() { - this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); - if (this.state === _transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Completed) { - this.stateTransition(_transaction_state__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Terminated); - } - } -} - - -/***/ }), -/* 61 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 62 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return ByeUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * BYE UAC. - * @public - */ -class ByeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - dialog.dispose(); - } -} - - -/***/ }), -/* 63 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return UserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); - - -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -class UserAgentClient { - constructor(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - dispose() { - this.transaction.dispose(); - } - get loggerFactory() { - return this.core.loggerFactory; - } - /** The transaction associated with this request. */ - get transaction() { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - } - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - cancel(reason, options = {}) { - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - const message = this.core.makeOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { - new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); - } - else { - this.transaction.addStateChangeListener(() => { - if (this.transaction && this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { - new UserAgentClient(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this.core, message); - } - }, { once: true }); - } - return message; - } - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @param dialog - If defined, the dialog within which the response was received. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - authenticationGuard(message, dialog) { - const statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let challenge; - let authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - // If response to out of dialog request, assume incrementing the CSeq will suffice. - let cseq = (this.message.cseq += 1); - // If response to in dialog request, get a valid next CSeq number. - if (dialog && dialog.localSequenceNumber) { - dialog.incrementLocalSequenceNumber(); - cseq = this.message.cseq = dialog.localSequenceNumber; - } - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - } - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - onRequestTimeout() { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"](); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - } - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * @param error - Transport error - */ - onTransportError(error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - const message = new _messages__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"](); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - break; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - } - init() { - // We are the transaction user. - const user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: () => this.onRequestTimeout(), - onStateChange: (newState) => { - if (newState === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Terminated) { - // Remove the terminated transaction from the core. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - if (transaction === this._transaction) { - this.dispose(); - } - } - }, - onTransportError: (error) => this.onTransportError(error), - receiveResponse: (message) => this.receiveResponse(message) - }; - // Create a new transaction with us as the user. - const transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - const userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - } -} - - -/***/ }), -/* 64 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return ByeUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * BYE UAS. - * @public - */ -class ByeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 65 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return UserAgentServer; }); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _messages_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); - - - - -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -class UserAgentServer { - constructor(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : Object(_messages_utils__WEBPACK_IMPORTED_MODULE_2__["newTag"])(); - this.init(); - } - dispose() { - this.transaction.dispose(); - } - get loggerFactory() { - return this.core.loggerFactory; - } - /** The transaction associated with this request. */ - get transaction() { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - } - accept(options = { statusCode: 200 }) { - if (!this.acceptable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not acceptable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - progress(options = { statusCode: 180 }) { - if (!this.progressable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not progressable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - redirect(contacts, options = { statusCode: 302 }) { - if (!this.redirectable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not redirectable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const contactHeaders = new Array(); - contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - const response = this.reply(options); - return response; - } - reject(options = { statusCode: 480 }) { - if (!this.rejectable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not rejectable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - trying(options) { - if (!this.tryingable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"](`${this.message.method} not tryingable in state ${this.transaction.state}.`); - } - const response = this.reply({ statusCode: 100 }); - return response; - } - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - receiveCancel(message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - } - get acceptable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Accepted); - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); - } - throw new Error("Unknown transaction type."); - } - get progressable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - } - get redirectable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); - } - throw new Error("Unknown transaction type."); - } - get rejectable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying || this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding); - } - throw new Error("Unknown transaction type."); - } - get tryingable() { - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Proceeding; - } - if (this.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteServerTransaction"]) { - return this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Trying; - } - throw new Error("Unknown transaction type."); - } - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - reply(options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - const response = Object(_messages__WEBPACK_IMPORTED_MODULE_1__["constructOutgoingResponse"])(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - } - init() { - // We are the transaction user. - const user = { - loggerFactory: this.loggerFactory, - onStateChange: (newState) => { - if (newState === _transactions__WEBPACK_IMPORTED_MODULE_3__["TransactionState"].Terminated) { - // Remove the terminated transaction from the core. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.core.userAgentServers.delete(userAgentServerId); - this.dispose(); - } - }, - onTransportError: (error) => { - this.logger.error(error.message); - if (this.delegate && this.delegate.onTransportError) { - this.delegate.onTransportError(error); - } - else { - this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - const transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - const userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - } -} - - -/***/ }), -/* 66 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return InfoUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * INFO UAC. - * @public - */ -class InfoUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 67 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return InfoUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * INFO UAS. - * @public - */ -class InfoUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 68 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return MessageUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * MESSAGE UAC. - * @public - */ -class MessageUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 69 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return MessageUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * MESSAGE UAS. - * @public - */ -class MessageUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 70 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return NotifyUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * NOTIFY UAS. - * @public - */ -class NotifyUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 71 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return NotifyUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} -/** - * NOTIFY UAS. - * @public - */ -class NotifyUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - constructor(dialogOrCore, message, delegate) { - const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 72 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return PrackUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * PRACK UAC. - * @public - */ -class PrackUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - dialog.signalingStateTransition(message); - } -} - - -/***/ }), -/* 73 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return PrackUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * PRACK UAS. - * @public - */ -class PrackUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - this.dialog = dialog; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options = { statusCode: 200 }) { - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return super.accept(options); - } -} - - -/***/ }), -/* 74 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return ReInviteUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -class ReInviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["InviteClientTransaction"], dialog.userAgentCore, message, delegate); - this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = this; // let the dialog know re-invite request sent - this.dialog = dialog; - } - receiveResponse(message) { - if (!this.authenticationGuard(message, this.dialog)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message, - session: this.dialog, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - prack: (options) => { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message, - session: this.dialog, - ack: (options) => { - const outgoingAckRequest = this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - } -} - - -/***/ }), -/* 75 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return ReInviteUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -class ReInviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["InviteServerTransaction"], dialog.userAgentCore, message, delegate); - dialog.reinviteUserAgentServer = this; - this.dialog = dialog; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options = { statusCode: 200 }) { - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map((route) => `Record-Route: ${route}`)); - // Send and return the response - const response = super.accept(options); - const session = this.dialog; - const result = Object.assign(Object.assign({}, response), { session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - } - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - progress(options = { statusCode: 180 }) { - // Send and return the response - const response = super.progress(options); - const session = this.dialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - } - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - redirect(contacts, options = { statusCode: 302 }) { - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - } - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - reject(options = { statusCode: 488 }) { - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return super.reject(options); - } -} - - -/***/ }), -/* 76 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return ReferUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * REFER UAC. - * @public - */ -class ReferUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 77 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return ReferUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} -/** - * REFER UAS. - * @public - */ -class ReferUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - constructor(dialogOrCore, message, delegate) { - const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 78 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionDialog", function() { return SubscriptionDialog; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); -/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); -/* harmony import */ var _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(71); -/* harmony import */ var _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(83); -/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7); - - - - - - - -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -class SubscriptionDialog extends _dialog__WEBPACK_IMPORTED_MODULE_6__["Dialog"] { - constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - super(core, state); - this.delegate = delegate; - this._autoRefresh = false; - this._subscriptionEvent = subscriptionEvent; - this._subscriptionExpires = subscriptionExpires; - this._subscriptionExpiresInitial = subscriptionExpires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - this._subscriptionRefresh = undefined; - this._subscriptionRefreshLastSet = undefined; - this._subscriptionState = subscriptionState; - this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForSubscription(outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - const contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof _messages__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - const remoteSequenceNumber = undefined; - const callId = outgoingSubscribeRequestMessage.callId; - const localTag = outgoingSubscribeRequestMessage.fromTag; - const remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { - // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { - // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { - // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { - // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { - // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - const localURI = outgoingSubscribeRequestMessage.from.uri; - const remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - const early = false; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - dispose() { - super.dispose(); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); - } - get autoRefresh() { - return this._autoRefresh; - } - set autoRefresh(autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - } - get subscriptionEvent() { - return this._subscriptionEvent; - } - /** Number of seconds until subscription expires. */ - get subscriptionExpires() { - const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - } - set subscriptionExpires(expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - const refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - } - get subscriptionExpiresInitial() { - return this._subscriptionExpiresInitial; - } - /** Number of seconds until subscription auto refresh. */ - get subscriptionRefresh() { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - } - get subscriptionState() { - return this._subscriptionState; - } - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - receiveRequest(message) { - this.logger.log(`SUBSCRIBE dialog ${this.id} received ${message.method} request`); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${message.method} request.`); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - super.receiveRequest(message); - // Switch on method and then delegate. - switch (message.method) { - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${message.method} request`); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - } - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh() { - const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - } - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - subscribe(delegate, options = {}) { - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - // FIXME: This needs to be a proper exception - throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`); - } - this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`); - const uac = new _user_agents_re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["ReSubscribeUserAgentClient"](this, delegate, options); - // Abort any outstanding timer (as it would otherwise become guaranteed to terminate us). - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].TIMER_N); - return uac; - } - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - terminate() { - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); - this.onTerminated(); - } - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe() { - const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - } - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - onNotify(message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - const state = subscriptionState.state; - const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending, expires); - break; - case "active": - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active, expires); - break; - case "terminated": - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - const uas = new _user_agents_notify_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["NotifyUserAgentServer"](this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - } - onRefresh(request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - } - onTerminated() { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - } - refreshTimerClear() { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - } - refreshTimerSet() { - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - const refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(() => { - this.refreshTimer = undefined; - this._subscriptionRefresh = undefined; - this._subscriptionRefreshLastSet = undefined; - this.onRefresh(this.refresh()); - }, refresh); - } - } - stateTransition(newState, newExpires) { - // Assert valid state transitions. - const invalidStateTransition = () => { - this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); - }; - switch (newState) { - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: - invalidStateTransition(); - return; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: - invalidStateTransition(); - return; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending: - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending) { - invalidStateTransition(); - return; - } - break; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active: - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - invalidStateTransition(); - return; - } - break; - case _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated: - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending && - this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - } - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - timerN() { - this.logger.warn(`Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY.`); - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - this.stateTransition(_subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated); - this.onTerminated(); - } - } -} - - -/***/ }), -/* 79 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return _subscription__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"]; }); - -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); -/* harmony import */ var _subscription_delegate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_subscription_delegate__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__) if(["SubscriptionState","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _subscription_delegate__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - -/***/ }), -/* 80 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState || (SubscriptionState = {})); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 82 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllowedMethods", function() { return AllowedMethods; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); - -/** - * FIXME: TODO: Should be configurable/variable. - */ -const AllowedMethods = [ - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].PRACK, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, - _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE -]; - - -/***/ }), -/* 83 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return ReSubscribeUserAgentClient; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); - - - -/** - * Re-SUBSCRIBE UAC. - * @public - */ -class ReSubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"] { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(_messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, options); - super(_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], dialog.userAgentCore, message, delegate); - this.dialog = dialog; - } - waitNotifyStop() { - // TODO: Placeholder. Not utilized currently. - return; - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - const expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - const subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - const errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - super.receiveResponse(message); - } -} - - -/***/ }), -/* 84 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"]; }); - -/* harmony import */ var _logger_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return _logger_factory__WEBPACK_IMPORTED_MODULE_1__["LoggerFactory"]; }); - -/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _logger__WEBPACK_IMPORTED_MODULE_2__["Logger"]; }); - - - - - - -/***/ }), -/* 85 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Levels", function() { return Levels; }); -/** - * Log levels. - * @public - */ -var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels || (Levels = {})); - - -/***/ }), -/* 86 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoggerFactory", function() { return LoggerFactory; }); -/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); -/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87); - - -/** - * Logger. - * @public - */ -class LoggerFactory { - constructor() { - this.builtinEnabled = true; - this._level = _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - get level() { - return this._level; - } - set level(newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - // eslint-disable-next-line no-prototype-builtins - } - else if (_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get connector() { - return this._connector; - } - set connector(value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - } - getLogger(category, label) { - if (label && this.level === 3) { - return new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - const logger = new _logger__WEBPACK_IMPORTED_MODULE_1__["Logger"](this, category); - this.loggers[category] = logger; - return logger; - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - genericLog(levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"][levelToLog], category, label, content); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - print(levelToLog, category, label, content) { - if (typeof content === "string") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error: - // eslint-disable-next-line no-console - console.error(content); - break; - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn: - // eslint-disable-next-line no-console - console.warn(content); - break; - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log: - // eslint-disable-next-line no-console - console.log(content); - break; - case _levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug: - // eslint-disable-next-line no-console - console.debug(content); - break; - default: - break; - } - } -} - - -/***/ }), -/* 87 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return Logger; }); -/* harmony import */ var _levels__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); - -/** - * Logger. - * @public - */ -class Logger { - constructor(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - error(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].error, content); - } - warn(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn, content); - } - log(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].log, content); - } - debug(content) { - this.genericLog(_levels__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug, content); - } - genericLog(level, content) { - this.logger.genericLog(level, this.category, this.label, content); - } -} - - -/***/ }), -/* 88 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _user_agent_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return _user_agent_core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"]; }); - -/* harmony import */ var _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100); -/* harmony import */ var _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__) if(["UserAgentCore","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_core_configuration__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(101); -/* harmony import */ var _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__) if(["UserAgentCore","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user_agent_core_delegate__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - - -/***/ }), -/* 89 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentCore", function() { return UserAgentCore; }); -/* harmony import */ var _messages__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48); -/* harmony import */ var _user_agents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(90); -/* harmony import */ var _allowed_methods__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82); - - - - -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -const acceptedBodyTypes = ["application/sdp", "application/dtmf-relay"]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -class UserAgentCore { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - constructor(configuration, delegate = {}) { - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - dispose() { - this.reset(); - } - /** Reset. */ - reset() { - this.dialogs.forEach((dialog) => dialog.dispose()); - this.dialogs.clear(); - this.subscribers.forEach((subscriber) => subscriber.dispose()); - this.subscribers.clear(); - this.userAgentClients.forEach((uac) => uac.dispose()); - this.userAgentClients.clear(); - this.userAgentServers.forEach((uac) => uac.dispose()); - this.userAgentServers.clear(); - } - /** Logger factory. */ - get loggerFactory() { - return this.configuration.loggerFactory; - } - /** Transport. */ - get transport() { - const transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - } - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - invite(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentClient"](this, request, delegate); - } - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - message(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentClient"](this, request, delegate); - } - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - publish(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["PublishUserAgentClient"](this, request, delegate); - } - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - register(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentClient"](this, request, delegate); - } - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - subscribe(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["SubscribeUserAgentClient"](this, request, delegate); - } - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - request(request, delegate) { - return new _user_agents__WEBPACK_IMPORTED_MODULE_2__["UserAgentClient"](_transactions__WEBPACK_IMPORTED_MODULE_1__["NonInviteClientTransaction"], this, request, delegate); - } - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - const callIdPrefix = this.configuration.sipjsId; - const fromDisplayName = this.configuration.displayName; - const forceRport = this.configuration.viaForceRport; - const hackViaTcp = this.configuration.hackViaTcp; - const optionTags = this.configuration.supportedOptionTags.slice(); - if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - const routeSet = this.configuration.routeSet; - const userAgentString = this.configuration.userAgentHeaderFieldValue; - const viaHost = this.configuration.viaHost; - const defaultOptions = { - callIdPrefix, - forceRport, - fromDisplayName, - hackViaTcp, - optionTags, - routeSet, - userAgentString, - viaHost - }; - // merge provided options with default options - const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); - return new _messages__WEBPACK_IMPORTED_MODULE_0__["OutgoingRequestMessage"](method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - } - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - receiveIncomingRequestFromTransport(message) { - this.receiveRequestFromTransport(message); - } - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - receiveIncomingResponseFromTransport(message) { - this.receiveResponseFromTransport(message); - } - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - replyStateless(message, options) { - const userAgent = this.configuration.userAgentHeaderFieldValue; - const supported = this.configuration.supportedOptionTagsResponse; - options = Object.assign(Object.assign({}, options), { userAgent, supported }); - const response = Object(_messages__WEBPACK_IMPORTED_MODULE_0__["constructOutgoingResponse"])(message, options); - this.transport.send(response.message).catch((error) => { - // If the transport rejects, it SHOULD reject with a TransportError. - // But the transport may be external code, so we are careful... - if (error instanceof Error) { - this.logger.error(error.message); - } - this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); - // TODO: Currently there is no hook to provide notification that a transport error occurred - // and throwing would result in an uncaught error (in promise), so we silently eat the error. - // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. - }); - return response; - } - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - receiveRequestFromTransport(message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - const uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - if (uas && uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Accepted) { - if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"]) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${transactionId}.`); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_1__["InviteServerTransaction"] && - uas.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_1__["TransactionState"].Proceeding) { - if (uas instanceof _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"]) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - } - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - receiveRequest(message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!_allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].includes(message.method)) { - const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { - // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - const ruri = message.ruri; - const ruriMatches = (uri) => { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - const transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - const mergedRequest = Array.from(this.userAgentServers.values()).some((uas) => uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - } - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - receiveInsideDialogRequest(message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY) { - const event = message.parseHeader("Event"); - if (!event || !event.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - const subscriberId = message.callId + message.toTag + event.event; - const subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["NotifyUserAgentServer"](this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - const dialogId = message.callId + message.toTag + message.fromTag; - const dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS) { - const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - } - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - receiveOutsideDialogRequest(message) { - switch (message.method) { - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].ACK: - // Absorb stray out of dialog ACKs - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].CANCEL: - throw new Error(`Unexpected out of dialog request method ${message.method}.`); - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["InviteUserAgentServer"](this, message); - this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["MessageUserAgentServer"](this, message); - this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["NotifyUserAgentServer"](this, message); - this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - const allowHeader = "Allow: " + _allowed_methods__WEBPACK_IMPORTED_MODULE_3__["AllowedMethods"].toString(); - const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["ReferUserAgentServer"](this, message); - this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["RegisterUserAgentServer"](this, message); - this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); - } - break; - case _messages__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - const uas = new _user_agents__WEBPACK_IMPORTED_MODULE_2__["SubscribeUserAgentServer"](this, message); - this.delegate.onSubscribe ? this.delegate.onSubscribe(uas) : uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error(`Unexpected out of dialog request method ${message.method}.`); - } - return; - } - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - receiveResponseFromTransport(message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - const userAgentClientId = message.viaBranch + message.method; - const userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn(`Discarding unmatched ${message.statusCode} response to ${message.method} ${userAgentClientId}.`); - } - } -} - - -/***/ }), -/* 90 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(62); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentClient", function() { return _bye_user_agent_client__WEBPACK_IMPORTED_MODULE_0__["ByeUserAgentClient"]; }); - -/* harmony import */ var _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ByeUserAgentServer", function() { return _bye_user_agent_server__WEBPACK_IMPORTED_MODULE_1__["ByeUserAgentServer"]; }); - -/* harmony import */ var _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return _cancel_user_agent_client__WEBPACK_IMPORTED_MODULE_2__["CancelUserAgentClient"]; }); - -/* harmony import */ var _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentClient", function() { return _info_user_agent_client__WEBPACK_IMPORTED_MODULE_3__["InfoUserAgentClient"]; }); - -/* harmony import */ var _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(67); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InfoUserAgentServer", function() { return _info_user_agent_server__WEBPACK_IMPORTED_MODULE_4__["InfoUserAgentServer"]; }); - -/* harmony import */ var _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(92); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return _invite_user_agent_client__WEBPACK_IMPORTED_MODULE_5__["InviteUserAgentClient"]; }); - -/* harmony import */ var _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(93); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return _invite_user_agent_server__WEBPACK_IMPORTED_MODULE_6__["InviteUserAgentServer"]; }); - -/* harmony import */ var _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(68); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentClient", function() { return _message_user_agent_client__WEBPACK_IMPORTED_MODULE_7__["MessageUserAgentClient"]; }); - -/* harmony import */ var _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(69); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageUserAgentServer", function() { return _message_user_agent_server__WEBPACK_IMPORTED_MODULE_8__["MessageUserAgentServer"]; }); - -/* harmony import */ var _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(70); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentClient", function() { return _notify_user_agent_client__WEBPACK_IMPORTED_MODULE_9__["NotifyUserAgentClient"]; }); - -/* harmony import */ var _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(71); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotifyUserAgentServer", function() { return _notify_user_agent_server__WEBPACK_IMPORTED_MODULE_10__["NotifyUserAgentServer"]; }); - -/* harmony import */ var _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(94); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return _publish_user_agent_client__WEBPACK_IMPORTED_MODULE_11__["PublishUserAgentClient"]; }); - -/* harmony import */ var _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(72); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentClient", function() { return _prack_user_agent_client__WEBPACK_IMPORTED_MODULE_12__["PrackUserAgentClient"]; }); - -/* harmony import */ var _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(73); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrackUserAgentServer", function() { return _prack_user_agent_server__WEBPACK_IMPORTED_MODULE_13__["PrackUserAgentServer"]; }); - -/* harmony import */ var _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(74); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentClient", function() { return _re_invite_user_agent_client__WEBPACK_IMPORTED_MODULE_14__["ReInviteUserAgentClient"]; }); - -/* harmony import */ var _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(75); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReInviteUserAgentServer", function() { return _re_invite_user_agent_server__WEBPACK_IMPORTED_MODULE_15__["ReInviteUserAgentServer"]; }); - -/* harmony import */ var _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(83); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentClient", function() { return _re_subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_16__["ReSubscribeUserAgentClient"]; }); - -/* harmony import */ var _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(95); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return _re_subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_17__["ReSubscribeUserAgentServer"]; }); - -/* harmony import */ var _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(76); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentClient", function() { return _refer_user_agent_client__WEBPACK_IMPORTED_MODULE_18__["ReferUserAgentClient"]; }); - -/* harmony import */ var _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(77); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReferUserAgentServer", function() { return _refer_user_agent_server__WEBPACK_IMPORTED_MODULE_19__["ReferUserAgentServer"]; }); - -/* harmony import */ var _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(96); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return _register_user_agent_client__WEBPACK_IMPORTED_MODULE_20__["RegisterUserAgentClient"]; }); - -/* harmony import */ var _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(97); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return _register_user_agent_server__WEBPACK_IMPORTED_MODULE_21__["RegisterUserAgentServer"]; }); - -/* harmony import */ var _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(98); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return _subscribe_user_agent_client__WEBPACK_IMPORTED_MODULE_22__["SubscribeUserAgentClient"]; }); - -/* harmony import */ var _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(99); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return _subscribe_user_agent_server__WEBPACK_IMPORTED_MODULE_23__["SubscribeUserAgentServer"]; }); - -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(63); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentClient", function() { return _user_agent_client__WEBPACK_IMPORTED_MODULE_24__["UserAgentClient"]; }); - -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(65); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserAgentServer", function() { return _user_agent_server__WEBPACK_IMPORTED_MODULE_25__["UserAgentServer"]; }); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/***/ }), -/* 91 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CancelUserAgentClient", function() { return CancelUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * CANCEL UAC. - * @public - */ -class CancelUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 92 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentClient", function() { return InviteUserAgentClient; }); -/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); - - - - -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -class InviteUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_3__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"], core, message, delegate); - this.confirmedDialogAcks = new Map(); - this.confirmedDialogs = new Map(); - this.earlyDialogs = new Map(); - this.delegate = delegate; - } - dispose() { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - super.dispose(); - } - /** - * Special case for transport error while sending ACK. - * @param error - Transport error - */ - onTransportError(error) { - if (this.transaction.state === _transactions__WEBPACK_IMPORTED_MODULE_2__["TransactionState"].Calling) { - return super.onTransportError(error); - } - // If not in 'calling' state, the transport error occurred while sending an ACK. - this.logger.error(error.message); - this.logger.error("User agent client request transport error while sending ACK."); - } - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Dialogs are created through the generation of non-failure responses - // to requests with specific methods. Within this specification, only - // 2xx and 101-199 responses with a To tag, where the request was - // INVITE, will establish a dialog. A dialog established by a non-final - // response to a request is in the "early" state and it is called an - // early dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1 - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - // Provisional without Contact header field, malformed response. - const contact = message.parseHeader("contact"); - if (!contact) { - this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping."); - return; - } - // Compute dialog state. - const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - let earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || - earlyDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - const session = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message, - session, - prack: (options) => { - const outgoingPrackRequest = session.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Dialogs are created through the generation of non-failure responses - // to requests with specific methods. Within this specification, only - // 2xx and 101-199 responses with a To tag, where the request was - // INVITE, will establish a dialog. A dialog established by a non-final - // response to a request is in the "early" state and it is called an - // early dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1 - // Final without to tag, malformed response. - if (!message.toTag) { - this.logger.error("2xx INVITE response received without a to tag, dropping."); - return; - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - // Final without Contact header field, malformed response. - const contact = message.parseHeader("contact"); - if (!contact) { - this.logger.error("2xx INVITE response received without a Contact header field, dropping."); - return; - } - // Compute dialog state. - const dialogState = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - let dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_2__["InviteClientTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].Initial || - dialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_1__["SignalingState"].HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - const session = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message, - session, - ack: (options) => { - const outgoingAckRequest = session.ack(options); - this.confirmedDialogAcks.set(session.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - const outgoingAckRequest = session.ack(); - this.confirmedDialogAcks.set(session.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - return; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - throw new Error(`Executing what should be an unreachable code path receiving ${statusCode} response.`); - } -} - - -/***/ }), -/* 93 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InviteUserAgentServer", function() { return InviteUserAgentServer; }); -/* harmony import */ var _dialogs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(44); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); -/* harmony import */ var _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(82); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(65); - - - - - - -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -class InviteUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_5__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"], core, message, delegate); - this.core = core; - } - dispose() { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - super.dispose(); - } - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - accept(options = { statusCode: 200 }) { - if (!this.acceptable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"](`${this.message.method} not acceptable in state ${this.transaction.state}.`); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); - const contactHeader = `Contact: ${this.core.configuration.contact.toString()}`; - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - const allowHeader = "Allow: " + _user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_4__["AllowedMethods"].toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Initial || - this.confirmedDialog.signalingState === _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - const response = super.accept(options); - const session = this.confirmedDialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - } - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - progress(options = { statusCode: 180 }) { - if (!this.progressable) { - throw new _exceptions__WEBPACK_IMPORTED_MODULE_1__["TransactionStateError"](`${this.message.method} not progressable in state ${this.transaction.state}.`); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - const transaction = this.transaction; - if (!(transaction instanceof _transactions__WEBPACK_IMPORTED_MODULE_3__["InviteServerTransaction"])) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - const state = _dialogs__WEBPACK_IMPORTED_MODULE_0__["Dialog"].initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new _dialogs__WEBPACK_IMPORTED_MODULE_0__["SessionDialog"](transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); - const contactHeader = `Contact: ${this.core.configuration.contact}`; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - const response = super.progress(options); - const session = this.earlyDialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== _session__WEBPACK_IMPORTED_MODULE_2__["SignalingState"].Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - } - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts, options = { statusCode: 302 }) { - return super.redirect(contacts, options); - } - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - reject(options = { statusCode: 486 }) { - return super.reject(options); - } -} - - -/***/ }), -/* 94 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublishUserAgentClient", function() { return PublishUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * PUBLISH UAC. - * @public - */ -class PublishUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 95 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReSubscribeUserAgentServer", function() { return ReSubscribeUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * Re-SUBSCRIBE UAS. - * @public - */ -class ReSubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(dialog, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], dialog.userAgentCore, message, delegate); - } -} - - -/***/ }), -/* 96 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentClient", function() { return RegisterUserAgentClient; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); - - -/** - * REGISTER UAC. - * @public - */ -class RegisterUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_1__["UserAgentClient"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteClientTransaction"], core, message, delegate); - } -} - - -/***/ }), -/* 97 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegisterUserAgentServer", function() { return RegisterUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * REGISTER UAS. - * @public - */ -class RegisterUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); - this.core = core; - } -} - - -/***/ }), -/* 98 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentClient", function() { return SubscribeUserAgentClient; }); -/* harmony import */ var _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79); -/* harmony import */ var _timers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48); -/* harmony import */ var _user_agent_client__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(63); - - - - - -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE requests. - * @public - */ -class SubscribeUserAgentClient extends _user_agent_client__WEBPACK_IMPORTED_MODULE_4__["UserAgentClient"] { - constructor(core, message, delegate) { - // Get event from request message. - const event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from request message. - const expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - super(_transactions__WEBPACK_IMPORTED_MODULE_3__["NonInviteClientTransaction"], core, message, delegate); - this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - this.subscriberId = message.callId + message.fromTag + event; - this.subscriptionExpiresRequested = this.subscriptionExpires = Number(expires); - this.subscriptionEvent = event; - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - this.waitNotifyStart(); - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - dispose() { - super.dispose(); - } - /** - * Handle out of dialog NOTIFY associated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - onNotify(uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - const event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn(`Failed to parse event.`); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - const state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn(`Invalid subscription state ${state}`); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - const contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install multiple subscriptions. - // As such and in accordance with the specification, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = subscriptionState.expires - ? Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) - : this.subscriptionExpires; - // Update subscription state. - switch (state) { - case "pending": - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Pending; - break; - case "active": - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Active; - break; - case "terminated": - this.subscriptionState = _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated; - break; - default: - throw new Error(`Unrecognized state ${state}.`); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== _subscription__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - const dialogState = _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"].initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new _dialogs_subscription_dialog__WEBPACK_IMPORTED_MODULE_0__["SubscriptionDialog"](this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - const request = uas; - const subscription = this.dialog; - this.delegate.onNotify({ request, subscription }); - } - else { - uas.accept(); - } - } - waitNotifyStart() { - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(() => this.timerN(), _timers__WEBPACK_IMPORTED_MODULE_2__["Timers"].TIMER_N); - } - } - waitNotifyStop() { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - const expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - const subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - super.receiveResponse(message); - } - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - timerN() { - this.logger.warn(`Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY.`); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - } -} - - -/***/ }), -/* 99 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeUserAgentServer", function() { return SubscribeUserAgentServer; }); -/* harmony import */ var _transactions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48); -/* harmony import */ var _user_agent_server__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65); - - -/** - * SUBSCRIBE UAS. - * @public - */ -class SubscribeUserAgentServer extends _user_agent_server__WEBPACK_IMPORTED_MODULE_1__["UserAgentServer"] { - constructor(core, message, delegate) { - super(_transactions__WEBPACK_IMPORTED_MODULE_0__["NonInviteServerTransaction"], core, message, delegate); - this.core = core; - } -} - - -/***/ }), -/* 100 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 101 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 102 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 103 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RequestPendingError", function() { return RequestPendingError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating an outstanding prior request prevented execution. - * @public - */ -class RequestPendingError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - /** @internal */ - constructor(message) { - super(message ? message : "Request pending."); - } -} - - -/***/ }), -/* 104 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandlerError", function() { return SessionDescriptionHandlerError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating a session description handler error occured. - * @public - */ -class SessionDescriptionHandlerError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "Unspecified session description handler error."); - } -} - - -/***/ }), -/* 105 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionTerminatedError", function() { return SessionTerminatedError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating the session terminated before the action completed. - * @public - */ -class SessionTerminatedError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor() { - super("The session has terminated."); - } -} - - -/***/ }), -/* 106 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateTransitionError", function() { return StateTransitionError; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * An exception indicating an invalid state transition error occured. - * @public - */ -class StateTransitionError extends _core__WEBPACK_IMPORTED_MODULE_0__["Exception"] { - constructor(message) { - super(message ? message : "An error occurred during state transition."); - } -} - - -/***/ }), -/* 107 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bye", function() { return Bye; }); -/** - * A request to end a {@link Session} (incoming BYE). - * @public - */ -class Bye { - /** @internal */ - constructor(incomingByeRequest) { - this.incomingByeRequest = incomingByeRequest; - } - /** Incoming BYE request message. */ - get request() { - return this.incomingByeRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingByeRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingByeRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 108 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmitterImpl", function() { return EmitterImpl; }); -/** - * An {@link Emitter} implementation. - * @internal - */ -class EmitterImpl { - constructor() { - this.listeners = new Array(); - } - /** - * Sets up a function that will be called whenever the target changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addListener(listener, options) { - const onceWrapper = (data) => { - this.removeListener(onceWrapper); - listener(data); - }; - (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); - } - /** - * Emit change. - * @param data - Data to emit. - */ - emit(data) { - this.listeners.slice().forEach((listener) => listener(data)); - } - /** - * Removes all listeners previously registered with addListener. - */ - removeAllListeners() { - this.listeners = []; - } - /** - * Removes a listener previously registered with addListener. - * @param listener - Callback function. - */ - removeListener(listener) { - this.listeners = this.listeners.filter((l) => l !== listener); - } - /** - * Registers a listener. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - on(listener) { - return this.addListener(listener); - } - /** - * Unregisters a listener. - * @param listener - Callback function. - * @deprecated Use removeListener. - */ - off(listener) { - return this.removeListener(listener); - } - /** - * Registers a listener then unregisters the listener after one event emission. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - once(listener) { - return this.addListener(listener, { once: true }); - } -} - - -/***/ }), -/* 109 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Info", function() { return Info; }); -/** - * An exchange of information (incoming INFO). - * @public - */ -class Info { - /** @internal */ - constructor(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - /** Incoming MESSAGE request message. */ - get request() { - return this.incomingInfoRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 110 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 111 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 112 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 113 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Invitation", function() { return Invitation; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(114); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(118); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(119); - - - - - - -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -class Invitation extends _session__WEBPACK_IMPORTED_MODULE_3__["Session"] { - /** @internal */ - constructor(userAgent, incomingInviteRequest) { - super(userAgent); - this.incomingInviteRequest = incomingInviteRequest; - /** True if dispose() has been called. */ - this.disposed = false; - /** INVITE will be rejected if not accepted within a certain period time. */ - this.expiresTimer = undefined; - /** True if this Session has been Terminated due to a CANCEL request. */ - this.isCanceled = false; - /** Are reliable provisional responses required or supported. */ - this.rel100 = "none"; - /** The current RSeq header value. */ - this.rseq = Math.floor(Math.random() * 10000); - /** INVITE will be rejected if final response not sent in a certain period time. */ - this.userNoAnswerTimer = undefined; - /** True if waiting for a PRACK before sending a 200 Ok. */ - this.waitingForPrack = false; - this.logger = userAgent.getLogger("sip.Invitation"); - const incomingRequestMessage = this.incomingInviteRequest.message; - // Set 100rel if necessary - const requireHeader = incomingRequestMessage.getHeader("require"); - if (requireHeader && requireHeader.toLowerCase().includes("100rel")) { - this.rel100 = "required"; - } - const supportedHeader = incomingRequestMessage.getHeader("supported"); - if (supportedHeader && supportedHeader.toLowerCase().includes("100rel")) { - this.rel100 = "supported"; - } - // FIXME: HACK: This is a hack to port an existing behavior. - // Set the toTag on the incoming request message to the toTag which - // will be used in the response to the incoming request!!! - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - // eslint-disable-next-line @typescript-eslint/no-explicit-any - incomingRequestMessage.toTag = incomingInviteRequest.toTag; - if (typeof incomingRequestMessage.toTag !== "string") { - throw new TypeError("toTag should have been a string."); - } - // The following mapping values are RECOMMENDED: - // ... - // 19 no answer from the user 480 Temporarily unavailable - // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 - this.userNoAnswerTimer = setTimeout(() => { - incomingInviteRequest.reject({ statusCode: 480 }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); - // 1. If the request is an INVITE that contains an Expires header - // field, the UAS core sets a timer for the number of seconds - // indicated in the header field value. When the timer fires, the - // invitation is considered to be expired. If the invitation - // expires before the UAS has generated a final response, a 487 - // (Request Terminated) response SHOULD be generated. - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - if (incomingRequestMessage.hasHeader("expires")) { - const expires = Number(incomingRequestMessage.getHeader("expires") || 0) * 1000; - this.expiresTimer = setTimeout(() => { - if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { - incomingInviteRequest.reject({ statusCode: 487 }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - }, expires); - } - // Session parent properties - const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(assertedIdentity); - } - this._contact = this.userAgent.contact.toString(); - const contentDisposition = incomingRequestMessage.parseHeader("Content-Disposition"); - if (contentDisposition && contentDisposition.type === "render") { - this._renderbody = incomingRequestMessage.body; - this._rendertype = incomingRequestMessage.getHeader("Content-Type"); - } - // Identifier - this._id = incomingRequestMessage.callId + incomingRequestMessage.fromTag; - // Add to the user agent's session collection. - this.userAgent._sessions[this._id] = this; - } - /** - * Destructor. - */ - dispose() { - // Only run through this once. It can and does get called multiple times - // depending on the what the sessions state is when first called. - // For example, if called when "establishing" it will be called again - // at least once when the session transitions to "terminated". - // Regardless, running through this more than once is pointless. - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - // Clear timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - this.expiresTimer = undefined; - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - this.userNoAnswerTimer = undefined; - } - // If accept() is still waiting for a PRACK, make sure it rejects - this.prackNeverArrived(); - // If the final response for the initial INVITE not yet been sent, reject it - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial: - return this.reject().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing: - return this.reject().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminating: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated: - return super.dispose(); - default: - throw new Error("Unknown state."); - } - } - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - get autoSendAnInitialProvisionalResponse() { - return this.rel100 === "required" ? false : true; - } - /** - * Initial incoming INVITE request message body. - */ - get body() { - return this.incomingInviteRequest.message.body; - } - /** - * The identity of the local user. - */ - get localIdentity() { - return this.request.to; - } - /** - * The identity of the remote user. - */ - get remoteIdentity() { - return this.request.from; - } - /** - * Initial incoming INVITE request message. - */ - get request() { - return this.incomingInviteRequest.message; - } - /** - * Accept the invitation. - * - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * Resolves once the response sent, otherwise rejects. - * - * This method may reject for a variety of reasons including - * the receipt of a CANCEL request before `accept` is able - * to construct a response. - * @param options - Options bucket. - */ - accept(options = {}) { - this.logger.log("Invitation.accept"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing); - return (this.sendAccept() - // eslint-disable-next-line @typescript-eslint/no-unused-vars - .then(({ message, session }) => { - session.delegate = { - onAck: (ackRequest) => this.onAckRequest(ackRequest), - onAckTimeout: () => this.onAckTimeout(), - onBye: (byeRequest) => this.onByeRequest(byeRequest), - onInfo: (infoRequest) => this.onInfoRequest(infoRequest), - onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), - onMessage: (messageRequest) => this.onMessageRequest(messageRequest), - onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), - onPrack: (prackRequest) => this.onPrackRequest(prackRequest), - onRefer: (referRequest) => this.onReferRequest(referRequest) - }; - this._dialog = session; - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Established); - // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. - // This behavior has been ported forward from legacy versions. - if (this._replacee) { - this._replacee._bye(); - } - }) - .catch((error) => this.handleResponseError(error))); - } - /** - * Indicate progress processing the invitation. - * - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * Resolves once the response sent, otherwise rejects. - * @param options - Options bucket. - */ - progress(options = {}) { - this.logger.log("Invitation.progress"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // Ported - const statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.waitingForPrack) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return Promise.resolve(); - } - // Trying provisional response - if (options.statusCode === 100) { - return this.sendProgressTrying() - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - // Standard provisional response - if (!(this.rel100 === "required") && - !(this.rel100 === "supported" && options.rel100) && - !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_5__["SIPExtension"].Required)) { - return this.sendProgress(options) - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - // Reliable provisional response - return this.sendProgressReliableWaitForPrack(options) - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - /** - * Reject the invitation. - * - * @remarks - * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. - * Resolves once the response sent, otherwise rejects. - * - * The expectation is that this method is used to reject an INVITE request. - * That is indeed the case - a call to `progress` followed by `reject` is - * a typical way to "decline" an incoming INVITE request. However it may - * also be called after calling `accept` (but only before it completes) - * which will reject the call and cause `accept` to reject. - * @param options - Options bucket. - */ - reject(options = {}) { - this.logger.log("Invitation.reject"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - const statusCode = options.statusCode || 480; - const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(statusCode); - const extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(options.body) : undefined; - // FIXME: Need to redirect to someplace - statusCode < 400 - ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) - : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - return Promise.resolve(); - } - /** - * Handle CANCEL request. - * - * @param message - CANCEL message. - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _onCancel(message) { - this.logger.log("Invitation._onCancel"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { - this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); - return; - } - // flag canceled - this.isCanceled = true; - // reject INVITE with 487 status code - this.incomingInviteRequest.reject({ statusCode: 487 }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - /** - * Helper function to handle offer/answer in a PRACK. - */ - handlePrackOfferAnswer(request) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - const options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.dialog.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: - // Receved answer. - return this.setAnswer(body, options).then(() => undefined); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: - // Received offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - } - } - /** - * A handler for errors which occur while attempting to send 1xx and 2xx responses. - * In all cases, an attempt is made to reject the request if it is still outstanding. - * And while there are a variety of things which can go wrong and we log something here - * for all errors, there are a handful of common exceptions we pay some extra attention to. - * @param error - The error which occurred. - */ - handleResponseError(error) { - let statusCode = 480; // "Temporarily Unavailable" - // Log Error message - if (error instanceof Error) { - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw our way, - // and more generally as a last resort catch all, just assume we are getting an "unknown" and log it. - this.logger.error(error); - } - // Log Exception message - if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["ContentTypeUnsupportedError"]) { - this.logger.error("A session description handler occurred while sending response (content type unsupported"); - statusCode = 415; // "Unsupported Media Type" - } - else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandlerError"]) { - this.logger.error("A session description handler occurred while sending response"); - } - else if (error instanceof _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]) { - this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"); - } - else if (error instanceof _core__WEBPACK_IMPORTED_MODULE_0__["TransactionStateError"]) { - this.logger.error("Session changed state before response could be formulated and sent"); - } - // Reject if still in "initial" or "establishing" state. - if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Initial || this.state === _session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Establishing) { - try { - this.incomingInviteRequest.reject({ statusCode }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - catch (e) { - this.logger.error("An error occurred attempting to reject the request while handling another error"); - throw e; // This is not a good place to be... - } - } - // FIXME: TODO: - // Here we are squelching the throwing of errors due to an race condition. - // We have an internal race between calling `accept()` and handling an incoming - // CANCEL request. As there is no good way currently to delegate the handling of - // these race errors to the caller of `accept()`, we are squelching the throwing - // of ALL errors when/if they occur after receiving a CANCEL to catch the ONE we know - // is a "normal" exceptional condition. While this is a completely reasonable approach, - // the decision should be left up to the library user. Furthermore, as we are eating - // ALL errors in this case, we are potentially (likely) hiding "real" errors which occur. - // - // Only rethrow error if the session has not been canceled. - if (this.isCanceled) { - this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE." + - " However a CANCEL was received and processed while doing so which can (and often does) result" + - " in errors occurring as the session terminates in the meantime. Said error is being ignored."); - return; - } - throw error; - } - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - onAckTimeout() { - this.logger.log("Invitation.onAckTimeout"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.log("No ACK received for an extended period of time, terminating session"); - this.dialog.bye(); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_4__["SessionState"].Terminated); - } - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - sendAccept() { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.waitingForPrack) { - return this.waitForArrivalOfPrack() - .then(() => clearTimeout(this.userNoAnswerTimer)) // Ported - .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions)) - .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); - } - clearTimeout(this.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions).then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); - } - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - sendProgress(options = {}) { - const statusCode = options.statusCode || 180; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - const body = options.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this.sendProgressWithSDP(options); - } - try { - const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - this._dialog = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - } - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - sendProgressWithSDP(options = {}) { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - const statusCode = options.statusCode || 183; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) - .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) - .then((progressResponse) => { - this._dialog = progressResponse.session; - return progressResponse; - }); - } - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - sendProgressReliable(options = {}) { - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push("Require: 100rel"); - options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - return this.sendProgressWithSDP(options); - } - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - sendProgressReliableWaitForPrack(options = {}) { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - const statusCode = options.statusCode || 183; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - let body; - return new Promise((resolve, reject) => { - this.waitingForPrack = true; - this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) - .then((offerAnswer) => { - body = offerAnswer; - return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - }) - .then((progressResponse) => { - this._dialog = progressResponse.session; - let prackRequest; - let prackResponse; - progressResponse.session.delegate = { - onPrack: (request) => { - prackRequest = request; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(prackWaitTimeoutTimer); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(rel1xxRetransmissionTimer); - if (!this.waitingForPrack) { - return; - } - this.waitingForPrack = false; - this.handlePrackOfferAnswer(prackRequest) - .then((prackResponseBody) => { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - this.prackArrived(); - resolve({ prackRequest, prackResponse, progressResponse }); - } - catch (error) { - reject(error); - } - }) - .catch((error) => reject(error)); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - const prackWaitTimeout = () => { - if (!this.waitingForPrack) { - return; - } - this.waitingForPrack = false; - this.logger.warn("No PRACK received, rejecting INVITE."); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(rel1xxRetransmissionTimer); - this.reject({ statusCode: 504 }) - .then(() => reject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]())) - .catch((error) => reject(error)); - }; - const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - const rel1xxRetransmission = () => { - try { - this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - } - catch (error) { - this.waitingForPrack = false; - reject(error); - return; - } - // eslint-disable-next-line @typescript-eslint/no-use-before-define - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, (timeout *= 2)); - }; - let timeout = _core__WEBPACK_IMPORTED_MODULE_0__["Timers"].T1; - let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }) - .catch((error) => { - this.waitingForPrack = false; - reject(error); - }); - }); - } - /** - * A version of `progress` which resolves when a 100 Trying provisional response is sent. - */ - sendProgressTrying() { - try { - const progressResponse = this.incomingInviteRequest.trying(); - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - } - /** - * When attempting to accept the INVITE, an invitation waits - * for any outstanding PRACK to arrive before sending the 200 Ok. - * It will be waiting on this Promise to resolve which lets it know - * the PRACK has arrived and it may proceed to send the 200 Ok. - */ - waitForArrivalOfPrack() { - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise((resolve, reject) => { - this.waitingForPrackResolve = resolve; - this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - } - /** - * Here we are resolving the promise which in turn will cause - * the accept to proceed (it may still fail for other reasons, but...). - */ - prackArrived() { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - } - /** - * Here we are rejecting the promise which in turn will cause - * the accept to fail and the session to transition to "terminated". - */ - prackNeverArrived() { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new _exceptions__WEBPACK_IMPORTED_MODULE_2__["SessionTerminatedError"]()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - } -} - - -/***/ }), -/* 114 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Session", function() { return Session; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); -/* harmony import */ var _bye__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(107); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(108); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3); -/* harmony import */ var _info__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(109); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(115); -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(116); -/* harmony import */ var _referral__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(117); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(118); - - - - - - - - - - - -/** - * A session provides real time communication between one or more participants. - * - * @remarks - * The transport behaves in a deterministic manner according to the - * the state defined in {@link SessionState}. - * @public - */ -class Session { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - constructor(userAgent, options = {}) { - /** True if there is an outgoing re-INVITE request outstanding. */ - this.pendingReinvite = false; - /** True if there is an incoming re-INVITE ACK request outstanding. */ - this.pendingReinviteAck = false; - /** Session state. */ - this._state = _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial; - this.delegate = options.delegate; - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_4__["EmitterImpl"](); - this._userAgent = userAgent; - } - /** - * Destructor. - */ - dispose() { - this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`); - // Remove from the user agent's session collection - delete this.userAgent._sessions[this.id]; - // Dispose of dialog media - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - // TODO: The SDH needs to remain defined as it will be called after it is closed in cases - // where an answer/offer arrives while the session is being torn down. There are a variety - // of circumstances where this can happen - sending a BYE during a re-INVITE for example. - // The code is currently written such that it lazily makes a new SDH when it needs one - // and one is not yet defined. Thus if we undefined it here, it will currently make a - // new one which is out of sync and then never gets cleaned up. - // - // The downside of leaving it defined are that calls this closed SDH will continue to be - // made (think setDescription) and those should/will fail. These failures are handled, but - // it would be nice to have it all coded up in a way where having an undefined SDH where - // one is expected throws an error. - // - // this._sessionDescriptionHandler = undefined; - } - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: - break; // the Inviter/Invitation sub class dispose method handles this case - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: - break; // the Inviter/Invitation sub class dispose method handles this case - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: - return new Promise((resolve) => { - this._bye({ - // wait for the response to the BYE before resolving - onAccept: () => resolve(), - onRedirect: () => resolve(), - onReject: () => resolve() - }); - }); - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: - break; // nothing to be done - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: - break; // nothing to be done - default: - throw new Error("Unknown state."); - } - return Promise.resolve(); - } - /** - * The asserted identity of the remote user. - */ - get assertedIdentity() { - return this._assertedIdentity; - } - /** - * The confirmed session dialog. - */ - get dialog() { - return this._dialog; - } - /** - * A unique identifier for this session. - */ - get id() { - return this._id; - } - /** - * The session being replace by this one. - */ - get replacee() { - return this._replacee; - } - /** - * Session description handler. - * @remarks - * If `this` is an instance of `Invitation`, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". - * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * Otherwise `undefined`. - */ - get sessionDescriptionHandler() { - return this._sessionDescriptionHandler; - } - /** - * Session description handler factory. - */ - get sessionDescriptionHandlerFactory() { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - } - /** - * SDH modifiers for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerModifiers() { - return this._sessionDescriptionHandlerModifiers || []; - } - set sessionDescriptionHandlerModifiers(modifiers) { - this._sessionDescriptionHandlerModifiers = modifiers.slice(); - } - /** - * SDH options for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerOptions() { - return this._sessionDescriptionHandlerOptions || {}; - } - set sessionDescriptionHandlerOptions(options) { - this._sessionDescriptionHandlerOptions = Object.assign({}, options); - } - /** - * SDH modifiers for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerModifiersReInvite() { - return this._sessionDescriptionHandlerModifiersReInvite || []; - } - set sessionDescriptionHandlerModifiersReInvite(modifiers) { - this._sessionDescriptionHandlerModifiersReInvite = modifiers.slice(); - } - /** - * SDH options for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerOptionsReInvite() { - return this._sessionDescriptionHandlerOptionsReInvite || {}; - } - set sessionDescriptionHandlerOptionsReInvite(options) { - this._sessionDescriptionHandlerOptionsReInvite = Object.assign({}, options); - } - /** - * Session state. - */ - get state() { - return this._state; - } - /** - * Session state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * The user agent. - */ - get userAgent() { - return this._userAgent; - } - /** - * End the {@link Session}. Sends a BYE. - * @param options - Options bucket. See {@link SessionByeOptions} for details. - */ - bye(options = {}) { - let message = "Session.bye() may only be called if established session."; - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " However Inviter.invite() has not yet been called."; - message += " Perhaps you should have called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " However Invitation.accept() has not yet been called."; - message += " Perhaps you should have called Invitation.reject()?"; - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " However a dialog does not yet exist."; - message += " Perhaps you should have called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " However Invitation.accept() has not yet been called (or not yet resolved)."; - message += " Perhaps you should have called Invitation.reject()?"; - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: { - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._bye(requestDelegate, requestOptions); - } - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: - message += " However this session is already terminating."; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " Perhaps you have already called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " Perhaps you have already called Session.bye()?"; - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: - message += " However this session is already terminated."; - break; - default: - throw new Error("Unknown state"); - } - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - /** - * Share {@link Info} with peer. Sends an INFO. - * @param options - Options bucket. See {@link SessionInfoOptions} for details. - */ - info(options = {}) { - // guard session state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - const message = "Session.info() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._info(requestDelegate, requestOptions); - } - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. See {@link SessionInviteOptions} for details. - */ - invite(options = {}) { - this.logger.log("Session.invite"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - if (this.pendingReinvite) { - return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["RequestPendingError"]("Reinvite in progress. Please wait until complete, then try again.")); - } - this.pendingReinvite = true; - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptions; - } - const delegate = { - onAccept: (response) => { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Received 2xx response to re-INVITE without a session description"); - this.ackAndBye(response, 400, "Missing session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - const answerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.setOfferAndGetAnswer(body, answerOptions) - .then((answerBody) => { - response.ack({ body: answerBody }); - }) - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - this.logger.error(error.message); - if (this.state === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - // A BYE should not be sent if already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - response.ack(); - } - else { - this.ackAndBye(response, 488, "Bad Media Description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - }) - .then(() => { - this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - const answerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.setAnswer(body, answerOptions) - .then(() => { - response.ack(); - }) - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - this.logger.error(error.message); - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // The ACK needs to be sent regardless as it was not handled by the transaction. - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - this.ackAndBye(response, 488, "Bad Media Description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - else { - response.ack(); - } - }) - .then(() => { - this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onProgress: (response) => { - return; - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect: (response) => { - return; - }, - onReject: (response) => { - this.logger.warn("Received a non-2xx response to re-INVITE"); - this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - this.rollbackOffer() - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - this.logger.error(error.message); - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // Note that the ACK was already sent by the transaction, so just need to send BYE. - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - const extraHeaders = []; - extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); - this.dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTrying: (response) => { - return; - } - }; - const requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_2__["AllowedMethods"].toString()); - requestOptions.extraHeaders.push("Contact: " + this._contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - const offerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - return this.getOffer(offerOptions) - .then((offerBody) => { - if (!this.dialog) { - this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return this.dialog.invite(delegate, requestOptions); - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.error("Failed to send re-INVITE"); - this.pendingReinvite = false; - throw error; - }); - } - /** - * Deliver a {@link Message}. Sends a MESSAGE. - * @param options - Options bucket. See {@link SessionMessageOptions} for details. - */ - message(options = {}) { - // guard session state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - const message = "Session.message() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._message(requestDelegate, requestOptions); - } - /** - * Proffer a {@link Referral}. Send a REFER. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - Options bucket. See {@link SessionReferOptions} for details. - */ - refer(referTo, options = {}) { - // guard session state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - const message = "Session.refer() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - requestOptions.extraHeaders = requestOptions.extraHeaders - ? requestOptions.extraHeaders.concat(this.referExtraHeaders(this.referToString(referTo))) - : this.referExtraHeaders(this.referToString(referTo)); - return this._refer(options.onNotify, requestDelegate, requestOptions); - } - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _bye(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - const dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].AckWait: { - // This state only occurs if we are the callee. - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating); // We're terminating - return new Promise((resolve) => { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: () => { - const request = dialog.bye(delegate, options); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - resolve(request); - return Promise.resolve(); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: () => { - const request = dialog.bye(delegate, options); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - resolve(request); - } - }; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Confirmed: { - const request = dialog.bye(delegate, options); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(request); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - default: - throw new Error("Unrecognized state."); - } - } - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _info(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - } - /** - * Send MESSAGE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _message(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.message(delegate, options)); - } - /** - * Send REFER. - * @param onNotify - Notification callback. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _refer(onNotify, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If set, deliver any in-dialog NOTIFY requests here... - this.onNotify = onNotify; - return Promise.resolve(this.dialog.refer(delegate, options)); - } - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and send a BYE. - * Note that the BYE is sent in the dialog associated with the response - * which is not necessarily `this.dialog`. And, accordingly, the - * session state is not transitioned to terminated and session is not closed. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - ackAndBye(response, statusCode, reasonPhrase) { - response.ack(); - const extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); - } - // Using the dialog session associate with the response (which might not be this.dialog) - response.session.bye(undefined, { extraHeaders }); - } - /** - * Handle in dialog ACK request. - * @internal - */ - onAckRequest(request) { - this.logger.log("Session.onAckRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating) { - this.logger.error(`ACK received while in state ${this.state}, dropping request`); - return Promise.resolve(); - } - const dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // if received answer in ACK. - const answerOptions = { - sessionDescriptionHandlerOptions: this.pendingReinviteAck - ? this.sessionDescriptionHandlerOptionsReInvite - : this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.pendingReinviteAck - ? this._sessionDescriptionHandlerModifiersReInvite - : this._sessionDescriptionHandlerModifiers - }; - // reset pending ACK flag - this.pendingReinviteAck = false; - switch (dialog.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: { - // State should never be reached as first reliable response must have answer/offer. - // So we must have never has sent an offer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { - // State we should be in. - // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); - // If the ACK doesn't have an answer, nothing to be done. - if (!body) { - return Promise.resolve(); - } - if (body.contentDisposition === "render") { - this._renderbody = body.content; - this._rendertype = body.contentType; - return Promise.resolve(); - } - if (body.contentDisposition !== "session") { - return Promise.resolve(); - } - return this.setAnswer(body, answerOptions).catch((error) => { - this.logger.error(error.message); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: { - // State should never be reached as local offer would be answered by this ACK. - // So we must have received an ACK without an answer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: { - // State should never be reached as remote offer would be answered in first reliable response. - // So we must have never has sent an answer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - return Promise.resolve(); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - throw new Error(`Invalid signaling state ${dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${dialog.signalingState}.`); - } - } - /** - * Handle in dialog BYE request. - * @internal - */ - onByeRequest(request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`BYE received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onBye) { - const bye = new _bye__WEBPACK_IMPORTED_MODULE_3__["Bye"](request); - this.delegate.onBye(bye); - } - else { - request.accept(); - } - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - /** - * Handle in dialog INFO request. - * @internal - */ - onInfoRequest(request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`INFO received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onInfo) { - const info = new _info__WEBPACK_IMPORTED_MODULE_6__["Info"](request); - this.delegate.onInfo(info); - } - else { - // FIXME: TODO: We should reject request... - // - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - // https://tools.ietf.org/html/rfc6086#section-4.2.2 - request.accept(); - } - } - /** - * Handle in dialog INVITE request. - * @internal - */ - onInviteRequest(request) { - this.logger.log("Session.onInviteRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`INVITE received while in state ${this.state}, dropping request`); - return; - } - // set pending ACK flag - this.pendingReinviteAck = true; - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - const extraHeaders = ["Contact: " + this._contact]; - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - const header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(header); - } - const options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.generateResponseOfferAnswerInDialog(options) - .then((body) => { - const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.error("Failed to handle to re-INVITE request"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.error(this.dialog.signalingState); - // If we don't have a local/remote offer... - if (this.dialog.signalingState === _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable) { - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - this.rollbackOffer() - .then(() => { - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch((errorRollback) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error(errorRollback.message); - this.logger.error("Failed to rollback offer on re-INVITE request"); - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // Note that the ACK was already sent by the transaction, so just need to send BYE. - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - const extraHeadersBye = []; - extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); - this.dialog.bye(undefined, { extraHeaders }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated); - } - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - } - /** - * Handle in dialog MESSAGE request. - * @internal - */ - onMessageRequest(request) { - this.logger.log("Session.onMessageRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onMessage) { - const message = new _message__WEBPACK_IMPORTED_MODULE_7__["Message"](request); - this.delegate.onMessage(message); - } - else { - request.accept(); - } - } - /** - * Handle in dialog NOTIFY request. - * @internal - */ - onNotifyRequest(request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); - return; - } - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated callback. - if (this.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); - this.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_8__["Notification"](request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - } - /** - * Handle in dialog PRACK request. - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onPrackRequest(request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`PRACK received while in state ${this.state}, dropping request`); - return; - } - throw new Error("Unimplemented."); - } - /** - * Handle in dialog REFER request. - * @internal - */ - onReferRequest(request) { - this.logger.log("Session.onReferRequest"); - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - this.logger.error(`REFER received while in state ${this.state}, dropping request`); - return; - } - // REFER is a SIP request and is constructed as defined in [1]. A REFER - // request MUST contain exactly one Refer-To header field value. - // https://tools.ietf.org/html/rfc3515#section-2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - const referral = new _referral__WEBPACK_IMPORTED_MODULE_9__["Referral"](request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral - .accept() - .then(() => referral.makeInviter(this._referralInviterOptions).invite()) - .catch((error) => { - // FIXME: logging and eating error... - this.logger.error(error.message); - }); - } - } - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - generateResponseOfferAnswer(request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - const body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["getBody"])(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - } - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - generateResponseOfferAnswerInDialog(options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - return this.getOffer(options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - } - } - /** - * Get local offer. - * @internal - */ - getOffer(options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - return sdh - .getDescription(sdhOptions, sdhModifiers) - .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) - .catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.getOffer: SDH getDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.getOffer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.getOffer: SDH getDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Rollback local/remote offer. - * @internal - */ - rollbackOffer() { - const sdh = this.setupSessionDescriptionHandler(); - if (sdh.rollbackDescription === undefined) { - return Promise.resolve(); - } - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - return sdh.rollbackDescription().catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.rollbackOffer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Set remote answer. - * @internal - */ - setAnswer(answer, options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); - } - } - catch (error) { - this.logger.error("Session.setAnswer: SDH hasDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - try { - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers).catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.setAnswer: SDH setDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.setAnswer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.setAnswer: SDH setDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Set remote offer and get local answer. - * @internal - */ - setOfferAndGetAnswer(offer, options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new _exceptions__WEBPACK_IMPORTED_MODULE_5__["ContentTypeUnsupportedError"]()); - } - } - catch (error) { - this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - try { - return sdh - .setDescription(offer.content, sdhOptions, sdhModifiers) - .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) - .then((bodyAndContentType) => Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType)) - .catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.setOfferAndGetAnswer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * SDH for confirmed dialog. - * @internal - */ - setSessionDescriptionHandler(sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Session description handler defined."); - } - this._sessionDescriptionHandler = sdh; - } - /** - * SDH for confirmed dialog. - * @internal - */ - setupSessionDescriptionHandler() { - var _a; - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { - this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler, false); - } - return this._sessionDescriptionHandler; - } - /** - * Transition session state. - * @internal - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Initial: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Establishing: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && - newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Established: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating && newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminating: - if (newState !== _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - invalidTransition(); - } - break; - case _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _session_state__WEBPACK_IMPORTED_MODULE_10__["SessionState"].Terminated) { - this.dispose(); - } - } - copyRequestOptions(requestOptions = {}) { - const extraHeaders = requestOptions.extraHeaders ? requestOptions.extraHeaders.slice() : undefined; - const body = requestOptions.body - ? { - contentDisposition: requestOptions.body.contentDisposition || "render", - contentType: requestOptions.body.contentType || "text/plain", - content: requestOptions.body.content || "" - } - : undefined; - return { - extraHeaders, - body - }; - } - getReasonHeaderValue(code, reason) { - const cause = code; - let text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code); - if (!text && reason) { - text = reason; - } - return "SIP;cause=" + cause + ';text="' + text + '"'; - } - referExtraHeaders(referTo) { - const extraHeaders = []; - extraHeaders.push("Referred-By: <" + this.userAgent.configuration.uri + ">"); - extraHeaders.push("Contact: " + this._contact); - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - extraHeaders.push("Refer-To: " + referTo); - return extraHeaders; - } - referToString(target) { - let referTo; - if (target instanceof _core__WEBPACK_IMPORTED_MODULE_0__["URI"]) { - // REFER without Replaces (Blind Transfer) - referTo = target.toString(); - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.dialog) { - throw new Error("Dialog undefined."); - } - const displayName = target.remoteIdentity.friendlyName; - const remoteTarget = target.dialog.remoteTarget.toString(); - const callId = target.dialog.callId; - const remoteTag = target.dialog.remoteTag; - const localTag = target.dialog.localTag; - const replaces = encodeURIComponent(`${callId};to-tag=${remoteTag};from-tag=${localTag}`); - referTo = `"${displayName}" <${remoteTarget}?Replaces=${replaces}>`; - } - return referTo; - } -} - - -/***/ }), -/* 115 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; }); -/** - * A received message (incoming MESSAGE). - * @public - */ -class Message { - /** @internal */ - constructor(incomingMessageRequest) { - this.incomingMessageRequest = incomingMessageRequest; - } - /** Incoming MESSAGE request message. */ - get request() { - return this.incomingMessageRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingMessageRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingMessageRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 116 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; }); -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -class Notification { - /** @internal */ - constructor(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - /** Incoming NOTIFY request message. */ - get request() { - return this.incomingNotifyRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - } -} - - -/***/ }), -/* 117 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Referral", function() { return Referral; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -class Referral { - /** @internal */ - constructor(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - get referTo() { - const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof _core__WEBPACK_IMPORTED_MODULE_0__["NameAddrHeader"])) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - } - get referredBy() { - return this.incomingReferRequest.message.getHeader("referred-by"); - } - get replaces() { - return this.referTo.uri.getHeader("replaces"); - } - /** Incoming REFER request message. */ - get request() { - return this.incomingReferRequest.message; - } - /** Accept the request. */ - accept(options = { statusCode: 202 }) { - this.incomingReferRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - } - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - makeInviter(options) { - if (this.inviter) { - return this.inviter; - } - const targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - const extraHeaders = (options.extraHeaders || []).slice(); - const replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - const referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent._makeInviter(targetURI, options); - this.inviter._referred = this.session; - this.session._referral = this.inviter; - return this.inviter; - } -} - - -/***/ }), -/* 118 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionState", function() { return SessionState; }); -/** - * {@link Session} state. - * - * @remarks - * The {@link Session} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ___________________________________________________________ - * | ____________________________________________ | - * | | ____________________________ | | - * Session | | | v v v - * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated - * | |___________________________^ ^ - * |_______________________________________________| - * ``` - * @public - */ -var SessionState; -(function (SessionState) { - /** - * If `Inviter`, INVITE not sent yet. - * If `Invitation`, received INVITE (but no final response sent yet). - */ - SessionState["Initial"] = "Initial"; - /** - * If `Inviter`, sent INVITE and waiting for a final response. - * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). - */ - SessionState["Establishing"] = "Establishing"; - /** - * If `Inviter`, sent INVITE and received 200 final response and sent ACK. - * If `Invitation`, received INVITE and sent 200 final response. - */ - SessionState["Established"] = "Established"; - /** - * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). - * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE - * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). - */ - SessionState["Terminating"] = "Terminating"; - /** - * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). - * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). - */ - SessionState["Terminated"] = "Terminated"; -})(SessionState || (SessionState = {})); - - -/***/ }), -/* 119 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SIPExtension", function() { return SIPExtension; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentRegisteredOptionTags", function() { return UserAgentRegisteredOptionTags; }); -/** - * SIP extension support level. - * @public - */ -var SIPExtension; -(function (SIPExtension) { - SIPExtension["Required"] = "Required"; - SIPExtension["Supported"] = "Supported"; - SIPExtension["Unsupported"] = "Unsupported"; -})(SIPExtension || (SIPExtension = {})); -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -const UserAgentRegisteredOptionTags = { - "100rel": true, - "199": true, - answermode: true, - "early-session": true, - eventlist: true, - explicitsub: true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - gin: true, - gruu: true, - histinfo: true, - ice: true, - join: true, - "multiple-refer": true, - norefersub: true, - nosub: true, - outbound: true, - path: true, - policy: true, - precondition: true, - pref: true, - privacy: true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - replaces: true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - tdialog: true, - timer: true, - uui: true // RFC 7433 -}; - - -/***/ }), -/* 120 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 121 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 122 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 123 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Inviter", function() { return Inviter; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(114); -/* harmony import */ var _session_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(118); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(119); - - - - - -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -class Inviter extends _session__WEBPACK_IMPORTED_MODULE_2__["Session"] { - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - constructor(userAgent, targetURI, options = {}) { - super(userAgent, options); - /** True if dispose() has been called. */ - this.disposed = false; - /** True if early media use is enabled. */ - this.earlyMedia = false; - /** The early media session description handlers. */ - this.earlyMediaSessionDescriptionHandlers = new Map(); - /** True if cancel() was called. */ - this.isCanceled = false; - /** True if initial INVITE without SDP. */ - this.inviteWithoutSdp = false; - this.logger = userAgent.getLogger("sip.Inviter"); - // Early media - this.earlyMedia = options.earlyMedia !== undefined ? options.earlyMedia : this.earlyMedia; - // From tag - this.fromTag = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["newTag"])(); - // Invite without SDP - this.inviteWithoutSdp = options.inviteWithoutSdp !== undefined ? options.inviteWithoutSdp : this.inviteWithoutSdp; - // Inviter options (could do better copying these options) - const inviterOptions = Object.assign({}, options); - inviterOptions.params = Object.assign({}, options.params); - // Anonymous call - const anonymous = options.anonymous || false; - // Contact - const contact = userAgent.contact.toString({ - anonymous, - // Do not add ;ob in initial forming dialog requests if the - // registration over the current connection got a GRUU URI. - outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu - }); - // FIXME: TODO: We should not be parsing URIs here as if it fails we have to throw an exception - // which is not something we want our constructor to do. URIs should be passed in as params. - // URIs - if (anonymous && userAgent.configuration.uri) { - inviterOptions.params.fromDisplayName = "Anonymous"; - inviterOptions.params.fromUri = "sip:anonymous@anonymous.invalid"; - } - let fromURI = userAgent.userAgentCore.configuration.aor; - if (inviterOptions.params.fromUri) { - fromURI = - typeof inviterOptions.params.fromUri === "string" - ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.fromUri) - : inviterOptions.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + inviterOptions.params.fromUri); - } - let toURI = targetURI; - if (inviterOptions.params.toUri) { - toURI = - typeof inviterOptions.params.toUri === "string" - ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(inviterOptions.params.toUri) - : inviterOptions.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + inviterOptions.params.toUri); - } - // Params - const messageOptions = Object.assign({}, inviterOptions.params); - messageOptions.fromTag = this.fromTag; - // Extra headers - const extraHeaders = (inviterOptions.extraHeaders || []).slice(); - if (anonymous && userAgent.configuration.uri) { - extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - if (userAgent.configuration.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { - extraHeaders.push("Require: 100rel"); - } - if (userAgent.configuration.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_4__["SIPExtension"].Required) { - extraHeaders.push("Require: replaces"); - } - inviterOptions.extraHeaders = extraHeaders; - // Body - const body = undefined; - // Make initial outgoing request message - this.outgoingRequestMessage = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].INVITE, targetURI, fromURI, toURI, messageOptions, extraHeaders, body); - // Session parent properties - this._contact = contact; - this._referralInviterOptions = inviterOptions; - this._renderbody = options.renderbody; - this._rendertype = options.rendertype; - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // Modifiers and options for re-INVITE transactions - if (options.sessionDescriptionHandlerModifiersReInvite) { - this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiersReInvite; - } - if (options.sessionDescriptionHandlerOptionsReInvite) { - this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptionsReInvite; - } - // Identifier - this._id = this.outgoingRequestMessage.callId + this.fromTag; - // Add to the user agent's session collection. - this.userAgent._sessions[this._id] = this; - } - /** - * Destructor. - */ - dispose() { - // Only run through this once. It can and does get called multiple times - // depending on the what the sessions state is when first called. - // For example, if called when "establishing" it will be called again - // at least once when the session transitions to "terminated". - // Regardless, running through this more than once is pointless. - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - // Dispose of early dialog media - this.disposeEarlyMedia(); - // If the final response for the initial INVITE not yet been received, cancel it - switch (this.state) { - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial: - return this.cancel().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing: - return this.cancel().then(() => super.dispose()); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating: - return super.dispose(); - case _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated: - return super.dispose(); - default: - throw new Error("Unknown state."); - } - } - /** - * Initial outgoing INVITE request message body. - */ - get body() { - return this.outgoingRequestMessage.body; - } - /** - * The identity of the local user. - */ - get localIdentity() { - return this.outgoingRequestMessage.from; - } - /** - * The identity of the remote user. - */ - get remoteIdentity() { - return this.outgoingRequestMessage.to; - } - /** - * Initial outgoing INVITE request message. - */ - get request() { - return this.outgoingRequestMessage; - } - /** - * Cancels the INVITE request. - * - * @remarks - * Sends a CANCEL request. - * Resolves once the response sent, otherwise rejects. - * - * After sending a CANCEL request the expectation is that a 487 final response - * will be received for the INVITE. However a 200 final response to the INVITE - * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before - * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect - * is that this method will terminate the session regardless of the race. - * @param options - Options bucket. - */ - cancel(options = {}) { - this.logger.log("Inviter.cancel"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // flag canceled - this.isCanceled = true; - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating); - // helper function - function getCancelReason(code, reason) { - if ((code && code < 200) || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - const cause = code; - const text = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["getReasonPhrase"])(code) || reason; - return "SIP;cause=" + cause + ';text="' + text + '"'; - } - } - if (this.outgoingInviteRequest) { - // the CANCEL may not be respected by peer(s), so don't transition to terminated - let cancelReason; - if (options.statusCode && options.reasonPhrase) { - cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); - } - this.outgoingInviteRequest.cancel(cancelReason, options); - } - else { - this.logger.warn("Canceled session before INVITE was sent"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - } - return Promise.resolve(); - } - /** - * Sends the INVITE request. - * - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behavior may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behavior of the SIP - * servers being utilized is configured to disallow forking. - */ - invite(options = {}) { - this.logger.log("Inviter.invite"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Initial) { - // re-invite - return super.invite(options); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // just send an INVITE with no sdp... - if (options.withoutSdp || this.inviteWithoutSdp) { - if (this._renderbody && this._rendertype) { - this.outgoingRequestMessage.body = { contentType: this._rendertype, body: this._renderbody }; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); - return Promise.resolve(this.sendInvite(options)); - } - // get an offer and send it in an INVITE - const offerOptions = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.getOffer(offerOptions) - .then((body) => { - this.outgoingRequestMessage.body = { body: body.content, contentType: body.contentType }; - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing); - return this.sendInvite(options); - }) - .catch((error) => { - this.logger.log(error.message); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - sendInvite(options = {}) { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - //// - //// - // TODO: The Offer/Answer Model Implementation - // - // Currently if `earlyMedia` is enabled and the INVITE request forks, - // the session is terminated if the early dialog does not match the - // confirmed dialog. This restriction make sense in a WebRTC environment, - // but there are other environments where this restriction does not hold. - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we propose doing the following... - // - // OPTION 1 - // - add a `earlyMediaForking` option and - // - require SDH.setDescription() to be callable multiple times. - // - // OPTION 2 - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.userAgent.userAgentCore.invite(this.outgoingRequestMessage, { - onAccept: (inviteResponse) => { - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this additional confirmed session. - if (this.dialog) { - this.logger.log("Additional confirmed dialog, sending ACK and BYE"); - this.ackAndBye(inviteResponse); - // We do NOT transition state in this case (this is an "extra" dialog) - return; - } - // If the user requested cancellation, ack & bye this session. - if (this.isCanceled) { - this.logger.log("Canceled session accepted, sending ACK and BYE"); - this.ackAndBye(inviteResponse); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return; - } - this.notifyReferer(inviteResponse); - this.onAccept(inviteResponse) - .then(() => { - this.disposeEarlyMedia(); - }) - .catch(() => { - this.disposeEarlyMedia(); - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(inviteResponse); - } - }); - }, - onProgress: (inviteResponse) => { - // If the user requested cancellation, ignore response. - if (this.isCanceled) { - return; - } - this.notifyReferer(inviteResponse); - this.onProgress(inviteResponse) - .catch(() => { - this.disposeEarlyMedia(); - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(inviteResponse); - } - }); - }, - onRedirect: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onRedirect(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(inviteResponse); - } - }, - onReject: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onReject(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(inviteResponse); - } - }, - onTrying: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onTrying(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(inviteResponse); - } - } - }); - return this.outgoingInviteRequest; - } - disposeEarlyMedia() { - this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { - sessionDescriptionHandler.close(); - }); - this.earlyMediaSessionDescriptionHandlers.clear(); - } - notifyReferer(response) { - if (!this._referred) { - return; - } - if (!(this._referred instanceof _session__WEBPACK_IMPORTED_MODULE_2__["Session"])) { - throw new Error("Referred session not instance of session"); - } - if (!this._referred.dialog) { - return; - } - if (!response.message.statusCode) { - throw new Error("Status code undefined."); - } - if (!response.message.reasonPhrase) { - throw new Error("Reason phrase undefined."); - } - const statusCode = response.message.statusCode; - const reasonPhrase = response.message.reasonPhrase; - const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); - const outgoingNotifyRequest = this._referred.dialog.notify(undefined, { - extraHeaders: ["Event: refer", "Subscription-State: terminated"], - body: { - contentDisposition: "render", - contentType: "message/sipfrag", - content: body - } - }); - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - // If the notify is rejected, stop sending NOTIFY requests. - outgoingNotifyRequest.delegate = { - onReject: () => { - this._referred = undefined; - } - }; - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - onAccept(inviteResponse) { - this.logger.log("Inviter.onAccept"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - this.logger.error(`Accept received while in state ${this.state}, dropping response`); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const response = inviteResponse.message; - const session = inviteResponse.session; - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - session.delegate = { - onAck: (ackRequest) => this.onAckRequest(ackRequest), - onBye: (byeRequest) => this.onByeRequest(byeRequest), - onInfo: (infoRequest) => this.onInfoRequest(infoRequest), - onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), - onMessage: (messageRequest) => this.onMessageRequest(messageRequest), - onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), - onPrack: (prackRequest) => this.onPrackRequest(prackRequest), - onRefer: (referRequest) => this.onReferRequest(referRequest) - }; - this._dialog = session; - switch (session.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - // INVITE without offer, so MUST have offer at this point, so invalid state. - this.logger.error("Received 2xx response to INVITE without a session description"); - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return Promise.reject(new Error("Bad Media Description")); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // INVITE with offer, so MUST have answer at this point, so invalid state. - this.logger.error("Received 2xx response to INVITE without a session description"); - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return Promise.reject(new Error("Bad Media Description")); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: { - // INVITE without offer, received offer in 2xx, so MUST send answer in ACK. - if (!this._dialog.offer) { - throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setOfferAndGetAnswer(this._dialog.offer, options) - .then((body) => { - inviteResponse.ack({ body }); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - }) - .catch((error) => { - this.ackAndBye(inviteResponse, 488, "Invalid session description"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: { - // If INVITE without offer and we have already completed the initial exchange. - if (this.earlyMediaSessionDescriptionHandlers.size > 0) { - const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!sdh) { - throw new Error("Session description handler undefined."); - } - this.setSessionDescriptionHandler(sdh); - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - inviteResponse.ack(); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - return Promise.resolve(); - } - // If INVITE with offer and we used an "early" answer in a provisional response for media - if (this.earlyMediaDialog) { - // If early media dialog doesn't match confirmed dialog, we must unfortunately fail. - // This limitation stems from how WebRTC currently implements its offer/answer model. - // There are details elsewhere, but in short a WebRTC offer cannot be forked. - if (this.earlyMediaDialog !== session) { - if (this.earlyMedia) { - const message = "You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests " + - "do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly " + - "the end point which accepted the INVITE (confirmed dialog) does not match the end point with " + - "which early media has been setup (early dialog) and thus this session is unable to proceed. " + - "In accordance with the SIP specifications, the SIP servers your end point is connected to " + - "determine if an INVITE forks and the forking behavior of those servers cannot be controlled " + - "by this library. If you wish to use early media with this library you must configure those " + - "servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow " + - "this library to function with any INVITE requests which do fork."; - this.logger.error(message); - } - const error = new Error("Early media dialog does not equal confirmed dialog, terminating session"); - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - return Promise.reject(error); - } - // Otherwise we are good to go. - inviteResponse.ack(); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - return Promise.resolve(); - } - // If INVITE with offer and we have been waiting till now to apply the answer. - const answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setAnswer(answer, options) - .then(() => { - // This session has completed an initial offer/answer exchange... - let ackOptions; - if (this._renderbody && this._rendertype) { - ackOptions = { - body: { contentDisposition: "render", contentType: this._rendertype, content: this._renderbody } - }; - } - inviteResponse.ack(ackOptions); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Established); - }) - .catch((error) => { - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - } - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - onProgress(inviteResponse) { - var _a; - this.logger.log("Inviter.onProgress"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - this.logger.error(`Progress received while in state ${this.state}, dropping response`); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - const response = inviteResponse.message; - const session = inviteResponse.session; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this._assertedIdentity = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - const requireHeader = response.getHeader("require"); - const rseqHeader = response.getHeader("rseq"); - const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - const responseReliable = !!rseq; - const extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - switch (session.signalingState) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Initial: - // INVITE without offer and session still has no offer (and no answer). - if (responseReliable) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders }); - } - return Promise.resolve(); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveLocalOffer: - // INVITE with offer and session only has that initial local offer. - if (responseReliable) { - inviteResponse.prack({ extraHeaders }); - } - return Promise.resolve(); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].HaveRemoteOffer: - if (!responseReliable) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return Promise.resolve(); - } - { - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { - this.delegate.onSessionDescriptionHandler(sdh, true); - } - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); - return sdh - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers) - .then(() => sdh.getDescription(this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers)) - .then((description) => { - const body = { - contentDisposition: "session", - contentType: description.contentType, - content: description.body - }; - inviteResponse.prack({ extraHeaders, body }); - }) - .catch((error) => { - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Stable: - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (responseReliable) { - inviteResponse.prack({ extraHeaders }); - } - if (this.earlyMedia && !this.earlyMediaDialog) { - this.earlyMediaDialog = session; - const answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setAnswer(answer, options).catch((error) => { - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - throw error; - }); - } - return Promise.resolve(); - case _core__WEBPACK_IMPORTED_MODULE_0__["SignalingState"].Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect(inviteResponse) { - this.logger.log("Inviter.onRedirect"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { - this.logger.error(`Redirect received while in state ${this.state}, dropping response`); - return; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onReject(inviteResponse) { - this.logger.log("Inviter.onReject"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing && this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminating) { - this.logger.error(`Reject received while in state ${this.state}, dropping response`); - return; - } - // transition state - this.stateTransition(_session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Terminated); - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTrying(inviteResponse) { - this.logger.log("Inviter.onTrying"); - // validate state - if (this.state !== _session_state__WEBPACK_IMPORTED_MODULE_3__["SessionState"].Establishing) { - this.logger.error(`Trying received while in state ${this.state}, dropping response`); - return; - } - } -} - - -/***/ }), -/* 124 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 125 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 126 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messager", function() { return Messager; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); - -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -class Messager { - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - constructor(userAgent, targetURI, content, contentType = "text/plain", options = {}) { - // Logger - this.logger = userAgent.getLogger("sip.Messager"); - // Default options params - options.params = options.params || {}; - // URIs - let fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - typeof options.params.fromUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.fromUri) : options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - let toURI = targetURI; - if (options.params.toUri) { - toURI = typeof options.params.toUri === "string" ? _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(options.params.toUri) : options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Message params - const params = options.params ? Object.assign({}, options.params) : {}; - // Extra headers - const extraHeaders = (options.extraHeaders || []).slice(); - // Body - const contentDisposition = "render"; - const body = { - contentDisposition, - contentType, - content - }; - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); - // User agent - this.userAgent = userAgent; - } - /** - * Send the message. - */ - message(options = {}) { - this.userAgent.userAgentCore.request(this.request, options.requestDelegate); - return Promise.resolve(); - } -} - - -/***/ }), -/* 127 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 128 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 129 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PublisherState", function() { return PublisherState; }); -/** - * {@link Publisher} state. - * @remarks - * The {@link Publisher} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Publisher | | v v - * Constructed -> Initial -> Published -> Unpublished -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -var PublisherState; -(function (PublisherState) { - PublisherState["Initial"] = "Initial"; - PublisherState["Published"] = "Published"; - PublisherState["Unpublished"] = "Unpublished"; - PublisherState["Terminated"] = "Terminated"; -})(PublisherState || (PublisherState = {})); - - -/***/ }), -/* 130 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 131 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Publisher", function() { return Publisher; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); -/* harmony import */ var _publisher_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(129); - - - -/** - * A publisher publishes a publication (outgoing PUBLISH). - * @public - */ -class Publisher { - /** - * Constructs a new instance of the `Publisher` class. - * - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - constructor(userAgent, targetURI, eventType, options = {}) { - this.disposed = false; - /** The publication state. */ - this._state = _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial; - // state emitter - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); - this.userAgent = userAgent; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = options.contentType || "text/plain"; - if (typeof options.expires !== "number" || options.expires % 1 !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof options.unpublishOnClose !== "boolean") { - options.unpublishOnClose = true; - } - this.target = targetURI; - this.event = eventType; - this.options = options; - this.pubRequestExpires = options.expires; - this.logger = userAgent.getLogger("sip.Publisher"); - const params = options.params || {}; - const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; - const toURI = params.toUri ? params.toUri : targetURI; - let body; - if (options.body && options.contentType) { - const contentDisposition = "render"; - const contentType = options.contentType; - const content = options.body; - body = { - contentDisposition, - contentType, - content - }; - } - const extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); - // Identifier - this.id = this.target.toString() + ":" + this.event; - // Add to the user agent's publisher collection. - this.userAgent._publishers[this.id] = this; - } - /** - * Destructor. - */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's publisher collection - delete this.userAgent._publishers[this.id]; - // Send unpublish, if requested - if (this.options.unpublishOnClose && this.state === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published) { - return this.unpublish(); - } - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - return Promise.resolve(); - } - /** The publication state. */ - get state() { - return this._state; - } - /** Emits when the publisher state changes. */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * Publish. - * @param content - Body to publish - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - publish(content, options = {}) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Initial or Modify request - this.options.body = content; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - if (this.options.expires === undefined) { - throw new Error("Expires undefined."); - } - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - this.sendPublishRequest(); - return Promise.resolve(); - } - /** - * Unpublish. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - unpublish(options = {}) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - return Promise.resolve(); - } - /** @internal */ - receiveResponse(response) { - const statusCode = response.statusCode || 0; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - const expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(() => this.refreshRequest(), this.pubRequestExpires * 900); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published); - } - else { - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - if (this.options.body === undefined) { - throw new Error("Body undefined."); - } - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - const minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - if (this.options.body === undefined) { - throw new Error("Body undefined."); - } - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - } - break; - default: - this.pubRequestExpires = 0; - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished); - this.stateTransition(_publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - } - /** @internal */ - send() { - return this.userAgent.userAgentCore.publish(this.request, { - onAccept: (response) => this.receiveResponse(response.message), - onProgress: (response) => this.receiveResponse(response.message), - onRedirect: (response) => this.receiveResponse(response.message), - onReject: (response) => this.receiveResponse(response.message), - onTrying: (response) => this.receiveResponse(response.message) - }); - } - refreshRequest() { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - throw new Error("Etag undefined"); - } - if (this.pubRequestExpires === 0) { - throw new Error("Expires zero"); - } - this.sendPublishRequest(); - } - sendPublishRequest() { - const reqOptions = Object.assign({}, this.options); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - const ruri = this.target; - const params = this.options.params || {}; - let bodyAndContentType; - if (this.pubRequestBody !== undefined) { - if (this.options.contentType === undefined) { - throw new Error("Content type undefined."); - } - bodyAndContentType = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - let body; - if (bodyAndContentType) { - body = Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(bodyAndContentType); - } - this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - return this.send(); - } - /** - * Transition publication state. - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Initial: - if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && - newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && - newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - invalidTransition(); - } - break; - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published: - if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - invalidTransition(); - } - break; - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Unpublished: - if (newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Published && newState !== _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - invalidTransition(); - } - break; - case _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Publication transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _publisher_state__WEBPACK_IMPORTED_MODULE_2__["PublisherState"].Terminated) { - this.dispose(); - } - } -} - - -/***/ }), -/* 132 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 133 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 134 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RegistererState", function() { return RegistererState; }); -/** - * {@link Registerer} state. - * @remarks - * The {@link Registerer} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Registerer | | v v - * Constructed -> Initial -> Registered -> Unregistered -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -var RegistererState; -(function (RegistererState) { - RegistererState["Initial"] = "Initial"; - RegistererState["Registered"] = "Registered"; - RegistererState["Unregistered"] = "Unregistered"; - RegistererState["Terminated"] = "Terminated"; -})(RegistererState || (RegistererState = {})); - - -/***/ }), -/* 135 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 136 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Registerer", function() { return Registerer; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(108); -/* harmony import */ var _exceptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _registerer_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(134); - - - - -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -class Registerer { - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - constructor(userAgent, options = {}) { - this.disposed = false; - /** The contacts returned from the most recent accepted REGISTER request. */ - this._contacts = []; - /** The number of seconds to wait before retrying to register. */ - this._retryAfter = undefined; - /** The registration state. */ - this._state = _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial; - /** True is waiting for final response to outstanding REGISTER request. */ - this._waiting = false; - // state emitter - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); - // waiting emitter - this._waitingEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_1__["EmitterImpl"](); - // Set user agent - this.userAgent = userAgent; - // Default registrar is domain portion of user agent uri - const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); - defaultUserAgentRegistrar.user = undefined; - // Initialize configuration - this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions()), { registrar: defaultUserAgentRegistrar }), Registerer.stripUndefinedProperties(options)); - // Make sure we are not using references to array options - this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); - this.options.extraHeaders = (this.options.extraHeaders || []).slice(); - // Make sure we are not using references to registrar uri - if (!this.options.registrar) { - throw new Error("Registrar undefined."); - } - this.options.registrar = this.options.registrar.clone(); - // Set instanceId and regId conditional defaults and validate - if (this.options.regId && !this.options.instanceId) { - this.options.instanceId = Registerer.newUUID(); - } - else if (!this.options.regId && this.options.instanceId) { - this.options.regId = 1; - } - if (this.options.instanceId && _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].parse(this.options.instanceId, "uuid") === -1) { - throw new Error("Invalid instanceId."); - } - if (this.options.regId && this.options.regId < 0) { - throw new Error("Invalid regId."); - } - const registrar = this.options.registrar; - const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; - const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; - const params = this.options.params || {}; - const extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); - // Registration expires - this.expires = this.options.expires || Registerer.defaultExpires; - if (this.expires < 0) { - throw new Error("Invalid expires."); - } - // initialize logger - this.logger = userAgent.getLogger("sip.Registerer"); - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - Object.keys(this.options).forEach((key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value = this.options[key]; - switch (key) { - case "registrar": - this.logger.log("· " + key + ": " + value); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - }); - } - // Identifier - this.id = this.request.callId + this.request.from.parameters.tag; - // Add to the user agent's session collection. - this.userAgent._registerers[this.id] = this; - } - /** Default registerer options. */ - static defaultOptions() { - return { - expires: Registerer.defaultExpires, - extraContactHeaderParams: [], - extraHeaders: [], - logConfiguration: true, - instanceId: "", - params: {}, - regId: 0, - registrar: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid") - }; - } - // http://stackoverflow.com/users/109538/broofa - static newUUID() { - const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = Math.floor(Math.random() * 16); - const v = c === "x" ? r : (r % 4) + 8; - return v.toString(16); - }); - return UUID; - } - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - static stripUndefinedProperties(options) { - return Object.keys(options).reduce((object, key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (options[key] !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object[key] = options[key]; - } - return object; - }, {}); - } - /** The registered contacts. */ - get contacts() { - return this._contacts.slice(); - } - /** - * The number of seconds to wait before retrying to register. - * @defaultValue `undefined` - * @remarks - * When the server rejects a registration request, if it provides a suggested - * duration to wait before retrying, that value is available here when and if - * the state transitions to `Unsubscribed`. It is also available during the - * callback to `onReject` after a call to `register`. (Note that if the state - * if already `Unsubscribed`, a rejected request created by `register` will - * not cause the state to transition to `Unsubscribed`. One way to avoid this - * case is to dispose of `Registerer` when unregistered and create a new - * `Registerer` for any attempts to retry registering.) - * @example - * ```ts - * // Checking for retry after on state change - * registerer.stateChange.addListener((newState) => { - * switch (newState) { - * case RegistererState.Unregistered: - * const retryAfter = registerer.retryAfter; - * break; - * } - * }); - * - * // Checking for retry after on request rejection - * registerer.register({ - * requestDelegate: { - * onReject: () => { - * const retryAfter = registerer.retryAfter; - * } - * } - * }); - * ``` - */ - get retryAfter() { - return this._retryAfter; - } - /** The registration state. */ - get state() { - return this._state; - } - /** Emits when the registerer state changes. */ - get stateChange() { - return this._stateEventEmitter; - } - /** Destructor. */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's registerer collection - delete this.userAgent._registerers[this.id]; - // If registered, unregisters and resolves after final response received. - return new Promise((resolve) => { - const doClose = () => { - // If we are registered, unregister and resolve after our state changes - if (!this.waiting && this._state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { - this.stateChange.addListener(() => { - this.terminated(); - resolve(); - }, { once: true }); - this.unregister(); - return; - } - // Otherwise just resolve - this.terminated(); - resolve(); - }; - // If we are waiting for an outstanding request, wait for it to finish and then try closing. - // Otherwise just try closing. - if (this.waiting) { - this.waitingChange.addListener(() => { - doClose(); - }, { once: true }); - } - else { - doClose(); - } - }); - } - /** - * Sends the REGISTER request. - * @remarks - * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - register(options = {}) { - if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.stateError(); - throw new Error("Registerer terminated. Unable to register."); - } - if (this.disposed) { - this.stateError(); - throw new Error("Registerer disposed. Unable to register."); - } - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - this.waitingWarning(); - const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); - return Promise.reject(error); - } - // Options - if (options.requestOptions) { - this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); - } - // Extra headers - const extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.waitingToggle(true); - const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: (response) => { - let expires; - // FIXME: This does NOT appear to be to spec and should be removed. - // I haven't found anywhere that an Expires header may be used in a response. - if (response.message.hasHeader("expires")) { - expires = Number(response.message.getHeader("expires")); - } - // 8. The registrar returns a 200 (OK) response. The response MUST - // contain Contact header field values enumerating all current - // bindings. Each Contact value MUST feature an "expires" - // parameter indicating its expiration interval chosen by the - // registrar. The response SHOULD include a Date header field. - // https://tools.ietf.org/html/rfc3261#section-10.3 - this._contacts = response.message.getHeaders("contact"); - let contacts = this._contacts.length; - if (!contacts) { - this.logger.error("No Contact header in response to REGISTER, dropping response."); - this.unregistered(); - return; - } - // The 200 (OK) response from the registrar contains a list of Contact - // fields enumerating all current bindings. The UA compares each - // contact address to see if it created the contact address, using - // comparison rules in Section 19.1.4. If so, it updates the expiration - // time interval according to the expires parameter or, if absent, the - // Expires field value. The UA then issues a REGISTER request for each - // of its bindings before the expiration interval has elapsed. - // https://tools.ietf.org/html/rfc3261#section-10.2.4 - let contact; - while (contacts--) { - contact = response.message.parseHeader("contact", contacts); - if (!contact) { - throw new Error("Contact undefined"); - } - if (contact.uri.user === this.userAgent.contact.uri.user) { - expires = Number(contact.getParam("expires")); - break; - } - contact = undefined; - } - // There must be a matching contact. - if (contact === undefined) { - this.logger.error("No Contact header pointing to us, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // The contact must have an expires. - if (expires === undefined) { - this.logger.error("Contact pointing to us is missing expires parameter, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // Save gruu values - if (contact.hasParam("temp-gruu")) { - const gruu = contact.getParam("temp-gruu"); - if (gruu) { - this.userAgent.contact.tempGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); - } - } - if (contact.hasParam("pub-gruu")) { - const gruu = contact.getParam("pub-gruu"); - if (gruu) { - this.userAgent.contact.pubGruu = _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(gruu.replace(/"/g, "")); - } - } - this.registered(expires); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - this.waitingToggle(false); - }, - onProgress: (response) => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: (response) => { - this.logger.error("Redirect received. Not supported."); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - this.waitingToggle(false); - }, - onReject: (response) => { - if (response.message.statusCode === 423) { - // If a UA receives a 423 (Interval Too Brief) response, it MAY retry - // the registration after making the expiration interval of all contact - // addresses in the REGISTER request equal to or greater than the - // expiration interval within the Min-Expires header field of the 423 - // (Interval Too Brief) response. - // https://tools.ietf.org/html/rfc3261#section-10.2.8 - // - // The registrar MAY choose an expiration less than the requested - // expiration interval. If and only if the requested expiration - // interval is greater than zero AND smaller than one hour AND - // less than a registrar-configured minimum, the registrar MAY - // reject the registration with a response of 423 (Interval Too - // Brief). This response MUST contain a Min-Expires header field - // that states the minimum expiration interval the registrar is - // willing to honor. It then skips the remaining steps. - // https://tools.ietf.org/html/rfc3261#section-10.3 - if (!response.message.hasHeader("min-expires")) { - // This response MUST contain a Min-Expires header field - this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // Increase our registration interval to the suggested minimum - this.expires = Number(response.message.getHeader("min-expires")); - // Attempt the registration again immediately - this.waitingToggle(false); - this.register(); - return; - } - this.logger.warn(`Failed to register, status code ${response.message.statusCode}`); - // The Retry-After header field can be used with a 500 (Server Internal - // Error) or 503 (Service Unavailable) response to indicate how long the - // service is expected to be unavailable to the requesting client... - // https://tools.ietf.org/html/rfc3261#section-20.33 - let retryAfterDuration = NaN; - if (response.message.statusCode === 500 || response.message.statusCode === 503) { - const header = response.message.getHeader("retry-after"); - if (header) { - retryAfterDuration = Number.parseInt(header, undefined); - } - } - // Set for the state change (if any) and the delegate callback (if any) - this._retryAfter = isNaN(retryAfterDuration) ? undefined : retryAfterDuration; - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - this._retryAfter = undefined; - this.waitingToggle(false); - }, - onTrying: (response) => { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return Promise.resolve(outgoingRegisterRequest); - } - /** - * Sends the REGISTER request with expires equal to zero. - * @remarks - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - unregister(options = {}) { - if (this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.stateError(); - throw new Error("Registerer terminated. Unable to register."); - } - if (this.disposed) { - if (this.state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { - // allows unregister while disposing and registered - this.stateError(); - throw new Error("Registerer disposed. Unable to register."); - } - } - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - this.waitingWarning(); - const error = new _exceptions__WEBPACK_IMPORTED_MODULE_2__["RequestPendingError"]("REGISTER request already in progress, waiting for final response"); - return Promise.reject(error); - } - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && !options.all) { - this.logger.warn("Not currently registered, but sending an unregister anyway."); - } - // Extra headers - const extraHeaders = ((options.requestOptions && options.requestOptions.extraHeaders) || []).slice(); - this.request.extraHeaders = extraHeaders; - // Registrations are soft state and expire unless refreshed, but can - // also be explicitly removed. A client can attempt to influence the - // expiration interval selected by the registrar as described in Section - // 10.2.1. A UA requests the immediate removal of a binding by - // specifying an expiration interval of "0" for that contact address in - // a REGISTER request. UAs SHOULD support this mechanism so that - // bindings can be removed before their expiration interval has passed. - // - // The REGISTER-specific Contact header field value of "*" applies to - // all registrations, but it MUST NOT be used unless the Expires header - // field is present with a value of "0". - // https://tools.ietf.org/html/rfc3261#section-10.2.2 - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - // Pre-emptive clear the registration timer to avoid a race condition where - // this timer fires while waiting for a final response to the unsubscribe. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - this.waitingToggle(true); - const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: (response) => { - this._contacts = response.message.getHeaders("contact"); // Update contacts - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - this.waitingToggle(false); - }, - onProgress: (response) => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: (response) => { - this.logger.error("Unregister redirected. Not currently supported."); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - this.waitingToggle(false); - }, - onReject: (response) => { - this.logger.error(`Unregister rejected with status code ${response.message.statusCode}`); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - this.waitingToggle(false); - }, - onTrying: (response) => { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return Promise.resolve(outgoingRegisterRequest); - } - /** - * Clear registration timers. - */ - clearTimers() { - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - } - /** - * Generate Contact Header - */ - generateContactHeader(expires) { - let contact = this.userAgent.contact.toString(); - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach((header) => { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - } - /** - * Helper function, called when registered. - */ - registered(expires) { - this.clearTimers(); - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - this.registrationTimer = setTimeout(() => { - this.registrationTimer = undefined; - this.register(); - }, expires * 1000 - 3000); - // We are unregistered if the registration expires. - this.registrationExpiredTimer = setTimeout(() => { - this.logger.warn("Registration expired"); - this.unregistered(); - }, expires * 1000); - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered) { - this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered); - } - } - /** - * Helper function, called when unregistered. - */ - unregistered() { - this.clearTimers(); - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered) { - this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered); - } - } - /** - * Helper function, called when terminated. - */ - terminated() { - this.clearTimers(); - if (this._state !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.stateTransition(_registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated); - } - } - /** - * Transition registration state. - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Initial: - if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && - newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && - newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - invalidTransition(); - } - break; - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered: - if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - invalidTransition(); - } - break; - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Unregistered: - if (newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Registered && newState !== _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - invalidTransition(); - } - break; - case _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Registration transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated) { - this.dispose(); - } - } - /** True if the registerer is currently waiting for final response to a REGISTER request. */ - get waiting() { - return this._waiting; - } - /** Emits when the registerer waiting state changes. */ - get waitingChange() { - return this._waitingEventEmitter; - } - /** - * Toggle waiting. - */ - waitingToggle(waiting) { - if (this._waiting === waiting) { - throw new Error(`Invalid waiting transition from ${this._waiting} to ${waiting}`); - } - this._waiting = waiting; - this.logger.log(`Waiting toggled to ${this._waiting}`); - this._waitingEventEmitter.emit(this._waiting); - } - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - waitingWarning() { - let message = "An attempt was made to send a REGISTER request while a prior one was still in progress."; - message += " RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response"; - message += " from the registrar for the previous one or the previous REGISTER request has timed out."; - message += " Note that if the transport disconnects, you still must wait for the prior request to time out before"; - message += - " sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer."; - this.logger.warn(message); - } - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - stateError() { - const reason = this.state === _registerer_state__WEBPACK_IMPORTED_MODULE_3__["RegistererState"].Terminated ? "is in 'Terminated' state" : "has been disposed"; - let message = `An attempt was made to send a REGISTER request when the Registerer ${reason}.`; - message += " The Registerer transitions to 'Terminated' when Registerer.dispose() is called."; - message += " Perhaps you called UserAgent.stop() which dipsoses of all Registerers?"; - this.logger.error(message); - } -} -Registerer.defaultExpires = 600; - - -/***/ }), -/* 137 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 138 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 139 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 140 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 141 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 142 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 143 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 144 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 145 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 146 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 147 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 148 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(82); -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(116); -/* harmony import */ var _subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(149); -/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(150); - - - - - -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.addListener((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -class Subscriber extends _subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"] { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - constructor(userAgent, targetURI, eventType, options = {}) { - super(userAgent, options); - this.body = undefined; - this.logger = userAgent.getLogger("sip.Subscriber"); - if (options.body) { - this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - this.targetURI = targetURI; - // Subscription event - this.event = eventType; - // Subscription expires - if (options.expires === undefined) { - this.expires = 3600; - } - else if (typeof options.expires !== "number") { - // pre-typescript type guard - this.logger.warn(`Option "expires" must be a number. Using default of 3600.`); - this.expires = 3600; - } - else { - this.expires = options.expires; - } - // Subscription extra headers - this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - this.subscriberRequest = this.initSubscriberRequest(); - this.outgoingRequestMessage = this.subscriberRequest.message; - // Add to UserAgent's collection - this.id = this.outgoingRequestMessage.callId + this.outgoingRequestMessage.from.parameters.tag + this.event; - this._userAgent._subscriptions[this.id] = this; - } - /** - * Destructor. - * @internal - */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's subscription collection - delete this._userAgent._subscriptions[this.id]; - // Clear timers - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - // Dispose subscriber request - this.subscriberRequest.dispose(); - // Make sure to dispose of our parent, then unsubscribe the - // subscription dialog (if need be) and resolve when it has terminated. - return super.dispose().then(() => { - // If we have never subscribed there is nothing to wait on. - // If we are already transitioned to terminated there is no need to unsubscribe again. - if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { - return; - } - if (!this._dialog) { - throw new Error("Dialog undefined."); - } - if (this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending || - this._dialog.subscriptionState === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { - const dialog = this._dialog; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - return new Promise((resolve, reject) => { - dialog.delegate = { - onTerminated: () => resolve() - }; - dialog.unsubscribe(); - }); - } - }); - } - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - subscribe(options = {}) { - switch (this.subscriberRequest.state) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: - // we can end up here when retrying so only state transition if in SubscriptionState.Initial state - if (this.state === _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Initial) { - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].NotifyWait); - } - this.subscriberRequest.subscribe().then((result) => { - if (result.success) { - if (result.success.subscription) { - this._dialog = result.success.subscription; - this._dialog.delegate = { - onNotify: (request) => this.onNotify(request), - onRefresh: (request) => this.onRefresh(request), - onTerminated: () => { - // If a call to unsubscribe will state transition to SubscriptionState.Terminated, - // but we can end up here after that if the NOTIFY never arrives and timer N fires. - if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated) { - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); - } - } - }; - } - this.onNotify(result.success.request); - } - else if (result.failure) { - this.unsubscribe(); - } - }); - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: - if (this._dialog) { - const request = this._dialog.refresh(); - request.delegate = { - onAccept: (response) => this.onAccepted(response), - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect: (response) => this.unsubscribe(), - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onReject: (response) => this.unsubscribe() - }; - } - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: - break; - default: - break; - } - return Promise.resolve(); - } - /** - * {@inheritDoc Subscription.unsubscribe} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - unsubscribe(options = {}) { - if (this.disposed) { - return Promise.resolve(); - } - switch (this.subscriberRequest.state) { - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait: - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Pending: - if (this._dialog) { - this._dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active: - if (this._dialog) { - this._dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Terminated: - break; - default: - throw new Error("Unknown state."); - } - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Terminated); - return Promise.resolve(); - } - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - _refresh() { - if (this.subscriberRequest.state === _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Active) { - return this.subscribe(); - } - return Promise.resolve(); - } - /** @internal */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onAccepted(response) { - // NOTE: If you think you should do something with this response, - // please make sure you understand what it is you are doing and why. - // Per the RFC, the first NOTIFY is all that actually matters. - } - /** @internal */ - onNotify(request) { - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - request.accept(); - return; - } - // State transition if needed. - if (this.state !== _subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed) { - this.stateTransition(_subscription_state__WEBPACK_IMPORTED_MODULE_4__["SubscriptionState"].Subscribed); - } - // Delegate notification. - if (this.delegate && this.delegate.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_2__["Notification"](request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - // If the "Subscription-State" value is SubscriptionState.Terminated, the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for SubscriptionState.Terminated -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of SubscriptionState.Terminated, and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log(`Terminated subscription with reason ${subscriptionState.reason}`); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initSubscriberRequest(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initSubscriberRequest(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(() => { - this.subscribe(); - }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.unsubscribe(); - break; - default: - break; - } - } - } - /** @internal */ - onRefresh(request) { - request.delegate = { - onAccept: (response) => this.onAccepted(response) - }; - } - initSubscriberRequest() { - const options = { - extraHeaders: this.extraHeaders, - body: this.body ? Object(_core__WEBPACK_IMPORTED_MODULE_0__["fromBodyLegacy"])(this.body) : undefined - }; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.subscriberRequest = new SubscriberRequest(this._userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); - this.subscriberRequest.delegate = { - onAccept: (response) => this.onAccepted(response) - }; - return this.subscriberRequest; - } -} -class SubscriberRequest { - constructor(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.Subscriber"); - this.delegate = delegate; - const allowHeader = "Allow: " + _core_user_agent_core_allowed_methods__WEBPACK_IMPORTED_MODULE_1__["AllowedMethods"].toString(); - const extraHeaders = ((options && options.extraHeaders) || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - const body = options && options.body; - this.message = core.makeOutgoingRequestMessage(_core__WEBPACK_IMPORTED_MODULE_0__["C"].SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - dispose() { - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - this.request = undefined; - } - } - /** Subscription state. */ - get state() { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].NotifyWait; - } - else { - return _core__WEBPACK_IMPORTED_MODULE_0__["SubscriptionState"].Initial; - } - } - /** - * Establish subscription. - * @param options Options bucket. - */ - subscribe() { - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise((resolve) => { - if (!this.message) { - throw new Error("Message undefined."); - } - this.request = this.core.subscribe(this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: (response) => { - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: (requestWithSubscription) => { - this.subscription = requestWithSubscription.subscription; - if (this.subscription) { - this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: () => { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: (response) => { - resolve({ failure: { response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: (response) => { - resolve({ failure: { response } }); - } - }); - }); - } -} - - -/***/ }), -/* 149 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; }); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); -/* harmony import */ var _subscription_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(150); - - -/** - * A subscription provides {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -class Subscription { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - constructor(userAgent, options = {}) { - this._disposed = false; - this._state = _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial; - this._logger = userAgent.getLogger("sip.Subscription"); - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); - this._userAgent = userAgent; - this.delegate = options.delegate; - } - /** - * Destructor. - */ - dispose() { - if (this._disposed) { - return Promise.resolve(); - } - this._disposed = true; - this._stateEventEmitter.removeAllListeners(); - return Promise.resolve(); - } - /** - * The subscribed subscription dialog. - */ - get dialog() { - return this._dialog; - } - /** - * True if disposed. - * @internal - */ - get disposed() { - return this._disposed; - } - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - get state() { - return this._state; - } - /** - * Emits when the subscription `state` property changes. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** @internal */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Initial: - if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - invalidTransition(); - } - break; - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].NotifyWait: - if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed && newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - invalidTransition(); - } - break; - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Subscribed: - if (newState !== _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - invalidTransition(); - } - break; - case _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Guard against duplicate transition - if (this._state === newState) { - return; - } - // Transition - this._state = newState; - this._logger.log(`Subscription ${this._dialog ? this._dialog.id : undefined} transitioned to ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === _subscription_state__WEBPACK_IMPORTED_MODULE_1__["SubscriptionState"].Terminated) { - this.dispose(); - } - } -} - - -/***/ }), -/* 150 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionState", function() { return SubscriptionState; }); -/** - * {@link Subscription} state. - * @remarks - * The {@link Subscription} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * _______________________________________ - * Subscription | v - * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated - * |____________________________^ - * ``` - * @public - */ -var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Subscribed"] = "Subscribed"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState || (SubscriptionState = {})); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 152 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 153 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 154 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 155 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 156 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportState", function() { return TransportState; }); -/** - * {@link Transport} state. - * - * @remarks - * The {@link Transport} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ______________________________ - * | ____________ | - * Transport v v | | - * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting - * ^ ^ |_____________________^ | | - * | |_____________________________| | - * |_____________________________________________| - * ``` - * @public - */ -var TransportState; -(function (TransportState) { - /** - * The `connect()` method was called. - */ - TransportState["Connecting"] = "Connecting"; - /** - * The `connect()` method resolved. - */ - TransportState["Connected"] = "Connected"; - /** - * The `disconnect()` method was called. - */ - TransportState["Disconnecting"] = "Disconnecting"; - /** - * The `connect()` method was rejected, or - * the `disconnect()` method completed, or - * network connectivity was lost. - */ - TransportState["Disconnected"] = "Disconnected"; -})(TransportState || (TransportState = {})); - - -/***/ }), -/* 157 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 158 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgentState", function() { return UserAgentState; }); -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "Started" --> "Stopped" - * 2. "Stopped" --> "Started" - * ``` - * @public - */ -var UserAgentState; -(function (UserAgentState) { - UserAgentState["Started"] = "Started"; - UserAgentState["Stopped"] = "Stopped"; -})(UserAgentState || (UserAgentState = {})); - - -/***/ }), -/* 159 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserAgent", function() { return UserAgent; }); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _core_messages_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); -/* harmony import */ var _platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); -/* harmony import */ var _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1); -/* harmony import */ var _emitter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(108); -/* harmony import */ var _invitation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(113); -/* harmony import */ var _inviter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(123); -/* harmony import */ var _message__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(115); -/* harmony import */ var _notification__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(116); -/* harmony import */ var _user_agent_options__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(119); -/* harmony import */ var _user_agent_state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(158); - - - - - - - - - - - - -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -class UserAgent { - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - constructor(options = {}) { - /** @internal */ - this._publishers = {}; - /** @internal */ - this._registerers = {}; - /** @internal */ - this._sessions = {}; - /** @internal */ - this._subscriptions = {}; - this._state = _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped; - /** Unload listener. */ - this.unloadListener = () => { - this.stop(); - }; - // state emitter - this._stateEventEmitter = new _emitter__WEBPACK_IMPORTED_MODULE_5__["EmitterImpl"](); - // initialize delegate - this.delegate = options.delegate; - // initialize configuration - this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions()), { sipjsId: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(5) }), { uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous." + Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(6), "anonymous.invalid") }), { viaHost: Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); - // viaHost is hack - if (this.options.hackIpInContact) { - if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { - const from = 1; - const to = 254; - const octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - this.options.viaHost = "192.0.2." + octet; - } - else if (this.options.hackIpInContact) { - this.options.viaHost = this.options.hackIpInContact; - } - } - // initialize logger & logger factory - this.loggerFactory = new _core__WEBPACK_IMPORTED_MODULE_0__["LoggerFactory"](); - this.logger = this.loggerFactory.getLogger("sip.UserAgent"); - this.loggerFactory.builtinEnabled = this.options.logBuiltinEnabled; - this.loggerFactory.connector = this.options.logConnector; - switch (this.options.logLevel) { - case "error": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].error; - break; - case "warn": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].warn; - break; - case "log": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].log; - break; - case "debug": - this.loggerFactory.level = _core__WEBPACK_IMPORTED_MODULE_0__["Levels"].debug; - break; - default: - break; - } - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - Object.keys(this.options).forEach((key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value = this.options[key]; - switch (key) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + key + ": " + value); - break; - case "authorizationPassword": - this.logger.log("· " + key + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + key + ": " + value.name); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - }); - } - // guard deprecated transport options (remove this in version 16.x) - if (this.options.transportOptions) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const optionsDeprecated = this.options.transportOptions; - const maxReconnectionAttemptsDeprecated = optionsDeprecated.maxReconnectionAttempts; - const reconnectionTimeoutDeprecated = optionsDeprecated.reconnectionTimeout; - if (maxReconnectionAttemptsDeprecated !== undefined) { - const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (reconnectionTimeoutDeprecated !== undefined) { - const deprecatedMessage = `The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // hack - if (options.reconnectionDelay === undefined && reconnectionTimeoutDeprecated !== undefined) { - this.options.reconnectionDelay = reconnectionTimeoutDeprecated; - } - if (options.reconnectionAttempts === undefined && maxReconnectionAttemptsDeprecated !== undefined) { - this.options.reconnectionAttempts = maxReconnectionAttemptsDeprecated; - } - } - // guard deprecated user agent options (remove this in version 16.x) - if (options.reconnectionDelay !== undefined) { - const deprecatedMessage = `The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (options.reconnectionAttempts !== undefined) { - const deprecatedMessage = `The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // Initialize Transport - this._transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); - this.initTransportCallbacks(); - // Initialize Contact - this._contact = this.initContact(); - // Initialize UserAgentCore - this._userAgentCore = this.initCore(); - if (this.options.autoStart) { - this.start(); - } - } - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - static makeURI(uri) { - return _core__WEBPACK_IMPORTED_MODULE_0__["Grammar"].URIParse(uri); - } - /** Default user agent options. */ - static defaultOptions() { - return { - allowLegacyNotifications: false, - authorizationHa1: "", - authorizationPassword: "", - authorizationUsername: "", - autoStart: false, - autoStop: true, - delegate: {}, - displayName: "", - forceRport: false, - hackAllowUnregisteredOptionTags: false, - hackIpInContact: false, - hackViaTcp: false, - hackWssInTransport: false, - logBuiltinEnabled: true, - logConfiguration: true, - logConnector: () => { - /* noop */ - }, - logLevel: "log", - noAnswerTimeout: 60, - preloadedRouteSet: [], - reconnectionAttempts: 0, - reconnectionDelay: 4, - sessionDescriptionHandlerFactory: Object(_platform_web_session_description_handler__WEBPACK_IMPORTED_MODULE_2__["defaultSessionDescriptionHandlerFactory"])(), - sessionDescriptionHandlerFactoryOptions: {}, - sipExtension100rel: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, - sipExtensionReplaces: _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported, - sipExtensionExtraSupported: [], - sipjsId: "", - transportConstructor: _platform_web_transport__WEBPACK_IMPORTED_MODULE_3__["Transport"], - transportOptions: {}, - uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", "anonymous", "anonymous.invalid"), - userAgentString: "SIP.js/" + _version__WEBPACK_IMPORTED_MODULE_4__["LIBRARY_VERSION"], - viaHost: "" - }; - } - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - static stripUndefinedProperties(options) { - return Object.keys(options).reduce((object, key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (options[key] !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object[key] = options[key]; - } - return object; - }, {}); - } - /** - * User agent configuration. - */ - get configuration() { - return this.options; - } - /** - * User agent contact. - */ - get contact() { - return this._contact; - } - /** - * User agent state. - */ - get state() { - return this._state; - } - /** - * User agent state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * User agent transport. - */ - get transport() { - return this._transport; - } - /** - * User agent core. - */ - get userAgentCore() { - return this._userAgentCore; - } - /** - * The logger. - */ - getLogger(category, label) { - return this.loggerFactory.getLogger(category, label); - } - /** - * The logger factory. - */ - getLoggerFactory() { - return this.loggerFactory; - } - /** - * True if transport is connected. - */ - isConnected() { - return this.transport.isConnected(); - } - /** - * Reconnect the transport. - */ - reconnect() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - return Promise.reject(new Error("User agent stopped.")); - } - // Make sure we don't call synchronously - return Promise.resolve().then(() => this.transport.connect()); - } - /** - * Start the user agent. - * - * @remarks - * Resolves if transport connects, otherwise rejects. - * - * @example - * ```ts - * userAgent.start() - * .then(() => { - * // userAgent.isConnected() === true - * }) - * .catch((error: Error) => { - * // userAgent.isConnected() === false - * }); - * ``` - */ - start() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { - this.logger.warn(`User agent already started`); - return Promise.resolve(); - } - this.logger.log(`Starting ${this.configuration.uri}`); - // Transition state - this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started); - // TODO: Review this as it is not clear it has any benefit and at worst causes additional load the server. - // On unload it may be best to simply in most scenarios to do nothing. Furthermore and regardless, this - // kind of behavior seems more appropriate to be managed by the consumer of the API than the API itself. - // Should this perhaps be deprecated? - // - // Add window unload event listener - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && typeof window.addEventListener === "function" && !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return this.transport.connect(); - } - /** - * Stop the user agent. - * - * @remarks - * Resolves when the user agent has completed a graceful shutdown. - * ```txt - * 1) Sessions terminate. - * 2) Registerers unregister. - * 3) Subscribers unsubscribe. - * 4) Publishers unpublish. - * 5) Transport disconnects. - * 6) User Agent Core resets. - * ``` - * NOTE: While this is a "graceful shutdown", it can also be very slow one if you - * are waiting for the returned Promise to resolve. The disposal of the clients and - * dialogs is done serially - waiting on one to finish before moving on to the next. - * This can be slow if there are lot of subscriptions to unsubscribe for example. - * - * THE SLOW PACE IS INTENTIONAL! - * While one could spin them all down in parallel, this could slam the remote server. - * It is bad practice to denial of service attack (DoS attack) servers!!! - * Moreover, production servers will automatically blacklist clients which send too - * many requests in too short a period of time - dropping any additional requests. - * - * If a different approach to disposing is needed, one can implement whatever is - * needed and execute that prior to calling `stop()`. Alternatively one may simply - * not wait for the Promise returned by `stop()` to complete. - */ - async stop() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - this.logger.warn(`User agent already stopped`); - return Promise.resolve(); - } - this.logger.log(`Stopping ${this.configuration.uri}`); - // Transition state - this.transitionState(_user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped); - // TODO: See comments with associated complimentary code in start(). Should this perhaps be deprecated? - // Remove window unload event listener - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - // Be careful here to use a local references as start() can be called - // again before we complete and we don't want to touch new clients - // and we don't want to step on the new instances (or vice versa). - const publishers = Object.assign({}, this._publishers); - const registerers = Object.assign({}, this._registerers); - const sessions = Object.assign({}, this._sessions); - const subscriptions = Object.assign({}, this._subscriptions); - const transport = this.transport; - const userAgentCore = this.userAgentCore; - // - // At this point we have completed the state transition and everything - // following will effectively run async and MUST NOT cause any issues - // if UserAgent.start() is called while the following code continues. - // - // TODO: Minor optimization. - // The disposal in all cases involves, in part, sending messages which - // is not worth doing if the transport is not connected as we know attempting - // to send messages will be futile. But none of these disposal methods check - // if that's is the case and it would be easy for them to do so at this point. - // Dispose of Registerers - this.logger.log(`Dispose of registerers`); - for (const id in registerers) { - if (registerers[id]) { - await registerers[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._registerers[id]; - throw error; - }); - } - } - // Dispose of Sessions - this.logger.log(`Dispose of sessions`); - for (const id in sessions) { - if (sessions[id]) { - await sessions[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._sessions[id]; - throw error; - }); - } - } - // Dispose of Subscriptions - this.logger.log(`Dispose of subscriptions`); - for (const id in subscriptions) { - if (subscriptions[id]) { - await subscriptions[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._subscriptions[id]; - throw error; - }); - } - } - // Dispose of Publishers - this.logger.log(`Dispose of publishers`); - for (const id in publishers) { - if (publishers[id]) { - await publishers[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._publishers[id]; - throw error; - }); - } - } - // Dispose of the transport (disconnecting) - this.logger.log(`Dispose of transport`); - await transport.dispose().catch((error) => { - this.logger.error(error.message); - throw error; - }); - // Dispose of the user agent core (resetting) - this.logger.log(`Dispose of core`); - userAgentCore.dispose(); - } - /** - * Used to avoid circular references. - * @internal - */ - _makeInviter(targetURI, options) { - return new _inviter__WEBPACK_IMPORTED_MODULE_7__["Inviter"](this, targetURI, options); - } - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - attemptReconnection(reconnectionAttempt = 1) { - const reconnectionAttempts = this.options.reconnectionAttempts; - const reconnectionDelay = this.options.reconnectionDelay; - if (reconnectionAttempt > reconnectionAttempts) { - this.logger.log(`Maximum reconnection attempts reached`); - return; - } - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); - setTimeout(() => { - this.reconnect() - .then(() => { - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); - this.attemptReconnection(++reconnectionAttempt); - }); - }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); - } - /** - * Initialize contact. - */ - initContact() { - const contactName = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["createRandomToken"])(8); // FIXME: should be configurable - const contactTransport = this.options.hackWssInTransport ? "wss" : "ws"; // FIXME: clearly broken for non ws transports - const contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new _core__WEBPACK_IMPORTED_MODULE_0__["URI"]("sip", contactName, this.options.viaHost, undefined, { transport: contactTransport }), - toString: (contactToStringOptions = {}) => { - const anonymous = contactToStringOptions.anonymous || false; - const outbound = contactToStringOptions.outbound || false; - let contactString = "<"; - if (anonymous) { - contactString += this.contact.tempGruu || `sip:anonymous@anonymous.invalid;transport=${contactTransport}`; - } - else { - contactString += this.contact.pubGruu || this.contact.uri; - } - if (outbound) { - contactString += ";ob"; - } - contactString += ">"; - return contactString; - } - }; - return contact; - } - /** - * Initialize user agent core. - */ - initCore() { - // supported options - let supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (this.options.sipExtension100rel === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { - supportedOptionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Supported) { - supportedOptionTags.push("replaces"); - } - if (this.options.sipExtensionExtraSupported) { - supportedOptionTags.push(...this.options.sipExtensionExtraSupported); - } - if (!this.options.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter((optionTag) => _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["UserAgentRegisteredOptionTags"][optionTag]); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - // FIXME: TODO: This was ported, but this is and was just plain broken. - const supportedOptionTagsResponse = supportedOptionTags.slice(); - if (this.contact.pubGruu || this.contact.tempGruu) { - supportedOptionTagsResponse.push("gruu"); - } - // core configuration - const userAgentCoreConfiguration = { - aor: this.options.uri, - contact: this.contact, - displayName: this.options.displayName, - loggerFactory: this.loggerFactory, - hackViaTcp: this.options.hackViaTcp, - routeSet: this.options.preloadedRouteSet, - supportedOptionTags, - supportedOptionTagsResponse, - sipjsId: this.options.sipjsId, - userAgentHeaderFieldValue: this.options.userAgentString, - viaForceRport: this.options.forceRport, - viaHost: this.options.viaHost, - authenticationFactory: () => { - const username = this.options.authorizationUsername - ? this.options.authorizationUsername - : this.options.uri.user; // if authorization username not provided, use uri user as username - const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; - const ha1 = this.options.authorizationHa1 ? this.options.authorizationHa1 : undefined; - return new _core__WEBPACK_IMPORTED_MODULE_0__["DigestAuthentication"](this.getLoggerFactory(), ha1, username, password); - }, - transportAccessor: () => this.transport - }; - const userAgentCoreDelegate = { - onInvite: (incomingInviteRequest) => { - var _a; - const invitation = new _invitation__WEBPACK_IMPORTED_MODULE_6__["Invitation"](this, incomingInviteRequest); - incomingInviteRequest.delegate = { - onCancel: (cancel) => { - invitation._onCancel(cancel); - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTransportError: (error) => { - // A server transaction MUST NOT discard transaction state based only on - // encountering a non-recoverable transport error when sending a - // response. Instead, the associated INVITE server transaction state - // machine MUST remain in its current state. (Timers will eventually - // cause it to transition to the "Terminated" state). - // https://tools.ietf.org/html/rfc6026#section-7.1 - // As noted in the comment above, we are to leaving it to the transaction - // timers to eventually cause the transaction to sort itself out in the case - // of a transport failure in an invite server transaction. This delegate method - // is here simply here for completeness and to make it clear that it provides - // nothing more than informational hook into the core. That is, if you think - // you should be trying to deal with a transport error here, you are likely wrong. - this.logger.error("A transport error has occurred while handling an incoming INVITE request."); - } - }; - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - if (this.options.sipExtensionReplaces !== _user_agent_options__WEBPACK_IMPORTED_MODULE_10__["SIPExtension"].Unsupported) { - const message = incomingInviteRequest.message; - const replaces = message.parseHeader("replaces"); - if (replaces) { - const callId = replaces.call_id; - if (typeof callId !== "string") { - throw new Error("Type of call id is not string"); - } - const toTag = replaces.replaces_to_tag; - if (typeof toTag !== "string") { - throw new Error("Type of to tag is not string"); - } - const fromTag = replaces.replaces_from_tag; - if (typeof fromTag !== "string") { - throw new Error("type of from tag is not string"); - } - const targetDialogId = callId + toTag + fromTag; - const targetDialog = this.userAgentCore.dialogs.get(targetDialogId); - // If no match is found, the UAS rejects the INVITE and returns a 481 - // Call/Transaction Does Not Exist response. Likewise, if the Replaces - // header field matches a dialog which was not created with an INVITE, - // the UAS MUST reject the request with a 481 response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog) { - invitation.reject({ statusCode: 481 }); - return; - } - // If the Replaces header field matches a confirmed dialog, it checks - // for the presence of the "early-only" flag in the Replaces header - // field. (This flag allows the UAC to prevent a potentially - // undesirable race condition described in Section 7.1.) If the flag is - // present, the UA rejects the request with a 486 Busy response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog.early && replaces.early_only === true) { - invitation.reject({ statusCode: 486 }); - return; - } - // Provide a handle on the session being replaced. - const targetSession = this._sessions[callId + fromTag] || this._sessions[callId + toTag] || undefined; - if (!targetSession) { - throw new Error("Session does not exist."); - } - invitation._replacee = targetSession; - } - } - // Delegate invitation handling. - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) { - if (invitation.autoSendAnInitialProvisionalResponse) { - invitation.progress().then(() => { - var _a; - if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) === undefined) { - throw new Error("onInvite undefined."); - } - this.delegate.onInvite(invitation); - }); - return; - } - this.delegate.onInvite(invitation); - return; - } - // A common scenario occurs when the callee is currently not willing or - // able to take additional calls at this end system. A 486 (Busy Here) - // SHOULD be returned in such a scenario. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - invitation.reject({ statusCode: 486 }); - }, - onMessage: (incomingMessageRequest) => { - if (this.delegate && this.delegate.onMessage) { - const message = new _message__WEBPACK_IMPORTED_MODULE_8__["Message"](incomingMessageRequest); - this.delegate.onMessage(message); - } - else { - // Accept the MESSAGE request, but do nothing with it. - incomingMessageRequest.accept(); - } - }, - onNotify: (incomingNotifyRequest) => { - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - if (this.delegate && this.delegate.onNotify) { - const notification = new _notification__WEBPACK_IMPORTED_MODULE_9__["Notification"](incomingNotifyRequest); - this.delegate.onNotify(notification); - } - else { - // Per the above which obsoletes https://tools.ietf.org/html/rfc3265, - // the use of out of dialog NOTIFY is obsolete, but... - if (this.options.allowLegacyNotifications) { - incomingNotifyRequest.accept(); // Accept the NOTIFY request, but do nothing with it. - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - } - }, - onRefer: (incomingReferRequest) => { - this.logger.warn("Received an out of dialog REFER request"); - // TOOD: this.delegate.onRefer(...) - if (this.delegate && this.delegate.onReferRequest) { - this.delegate.onReferRequest(incomingReferRequest); - } - else { - incomingReferRequest.reject({ statusCode: 405 }); - } - }, - onRegister: (incomingRegisterRequest) => { - this.logger.warn("Received an out of dialog REGISTER request"); - // TOOD: this.delegate.onRegister(...) - if (this.delegate && this.delegate.onRegisterRequest) { - this.delegate.onRegisterRequest(incomingRegisterRequest); - } - else { - incomingRegisterRequest.reject({ statusCode: 405 }); - } - }, - onSubscribe: (incomingSubscribeRequest) => { - this.logger.warn("Received an out of dialog SUBSCRIBE request"); - // TOOD: this.delegate.onSubscribe(...) - if (this.delegate && this.delegate.onSubscribeRequest) { - this.delegate.onSubscribeRequest(incomingSubscribeRequest); - } - else { - incomingSubscribeRequest.reject({ statusCode: 405 }); - } - } - }; - return new _core__WEBPACK_IMPORTED_MODULE_0__["UserAgentCore"](userAgentCoreConfiguration, userAgentCoreDelegate); - } - initTransportCallbacks() { - this.transport.onConnect = () => this.onTransportConnect(); - this.transport.onDisconnect = (error) => this.onTransportDisconnect(error); - this.transport.onMessage = (message) => this.onTransportMessage(message); - } - onTransportConnect() { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - return; - } - if (this.delegate && this.delegate.onConnect) { - this.delegate.onConnect(); - } - } - onTransportDisconnect(error) { - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - return; - } - if (this.delegate && this.delegate.onDisconnect) { - this.delegate.onDisconnect(error); - } - // Only attempt to reconnect if network/server dropped the connection. - if (error && this.options.reconnectionAttempts > 0) { - this.attemptReconnection(); - } - } - onTransportMessage(messageString) { - const message = _core__WEBPACK_IMPORTED_MODULE_0__["Parser"].parseMessage(messageString, this.getLogger("sip.Parser")); - if (!message) { - this.logger.warn("Failed to parse incoming message. Dropping."); - return; - } - if (this.state === _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped && message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - this.logger.warn(`Received ${message.method} request while stopped. Dropping.`); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - const hasMinimumHeaders = () => { - const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (const header of mandatoryHeaders) { - if (!message.hasHeader(header)) { - this.logger.warn(`Missing mandatory header field : ${header}.`); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn(`Request missing mandatory header field. Dropping.`); - return; - } - // FIXME: This is non-standard and should be a configurable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.options.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); - const contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Response Checks - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn(`Response missing mandatory header field. Dropping.`); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.options.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - const len = Object(_core_messages_utils__WEBPACK_IMPORTED_MODULE_1__["utf8Length"])(message.body); - const contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingRequestMessage"]) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof _core__WEBPACK_IMPORTED_MODULE_0__["IncomingResponseMessage"]) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - } - /** - * Transition state. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - transitionState(newState, error) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate state transition - switch (this._state) { - case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started: - if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped) { - invalidTransition(); - } - break; - case _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Stopped: - if (newState !== _user_agent_state__WEBPACK_IMPORTED_MODULE_11__["UserAgentState"].Started) { - invalidTransition(); - } - break; - default: - throw new Error("Unknown state."); - } - // Update state - this.logger.log(`Transitioned from ${this._state} to ${newState}`); - this._state = newState; - this._stateEventEmitter.emit(this._state); - } -} - - -/***/ }), -/* 160 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"]; }); - -/* harmony import */ var _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(162); -/* harmony import */ var _media_stream_factory__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_media_stream_factory__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__) if(["defaultMediaStreamFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _media_stream_factory__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(163); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_2__["defaultPeerConnectionConfiguration"]; }); - -/* harmony import */ var _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(164); -/* harmony import */ var _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _peer_connection_delegate__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(165); -/* harmony import */ var _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_configuration__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(166); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return _session_description_handler_factory_default__WEBPACK_IMPORTED_MODULE_5__["defaultSessionDescriptionHandlerFactory"]; }); - -/* harmony import */ var _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(168); -/* harmony import */ var _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_factory_options__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(169); -/* harmony import */ var _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_factory__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(170); -/* harmony import */ var _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__) if(["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler_options__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(167); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_9__["SessionDescriptionHandler"]; }); - -/** - * A SessionDescriptionHandler for web browsers. - * @packageDocumentation - */ - - - - - - - - - - - - -/***/ }), -/* 161 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultMediaStreamFactory", function() { return defaultMediaStreamFactory; }); -/** - * Function which returns a MediaStreamFactory. - * @public - */ -function defaultMediaStreamFactory() { - return (constraints) => { - // if no audio or video, return a media stream without tracks - if (!constraints.audio && !constraints.video) { - return Promise.resolve(new MediaStream()); - } - // getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, - // navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, - // a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. - // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Privacy_and_security - if (navigator.mediaDevices === undefined) { - return Promise.reject(new Error("Media devices not available in insecure contexts.")); - } - return navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices, constraints); - }; -} - - -/***/ }), -/* 162 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 163 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultPeerConnectionConfiguration", function() { return defaultPeerConnectionConfiguration; }); -/** - * Function which returns an RTCConfiguration. - * @public - */ -function defaultPeerConnectionConfiguration() { - const configuration = { - bundlePolicy: "balanced", - certificates: undefined, - iceCandidatePoolSize: 0, - iceServers: [{ urls: "stun:stun.l.google.com:19302" }], - iceTransportPolicy: "all", - peerIdentity: undefined, - rtcpMuxPolicy: "require" - }; - return configuration; -} - - -/***/ }), -/* 164 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 165 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 166 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultSessionDescriptionHandlerFactory", function() { return defaultSessionDescriptionHandlerFactory; }); -/* harmony import */ var _media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(161); -/* harmony import */ var _peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(163); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(167); - - - -/** - * Function which returns a SessionDescriptionHandlerFactory. - * @remarks - * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. - * The ICE gathering timeout defaults to 5000ms. - * @param mediaStreamFactory - MediaStream factory. - * @public - */ -function defaultSessionDescriptionHandlerFactory(mediaStreamFactory) { - return (session, options) => { - // provide a default media stream factory if need be - if (mediaStreamFactory === undefined) { - mediaStreamFactory = Object(_media_stream_factory_default__WEBPACK_IMPORTED_MODULE_0__["defaultMediaStreamFactory"])(); - } - // make sure we allow `0` to be passed in so timeout can be disabled - const iceGatheringTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) !== undefined ? options === null || options === void 0 ? void 0 : options.iceGatheringTimeout : 5000; - // merge passed factory options into default session description configuration - const sessionDescriptionHandlerConfiguration = { - iceGatheringTimeout, - peerConnectionConfiguration: Object.assign(Object.assign({}, Object(_peer_connection_configuration_default__WEBPACK_IMPORTED_MODULE_1__["defaultPeerConnectionConfiguration"])()), options === null || options === void 0 ? void 0 : options.peerConnectionConfiguration) - }; - const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler"); - return new _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"](logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration); - }; -} - - -/***/ }), -/* 167 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionDescriptionHandler", function() { return SessionDescriptionHandler; }); -/** - * A base class implementing a WebRTC session description handler for sip.js. - * @remarks - * It is expected/intended to be extended by specific WebRTC based applications. - * @privateRemarks - * So do not put application specific implementation in here. - * @public - */ -class SessionDescriptionHandler { - /** - * Constructor - * @param logger - A logger - * @param mediaStreamFactory - A factory to provide a MediaStream - * @param options - Options passed from the SessionDescriptionHandleFactory - */ - constructor(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration) { - logger.debug("SessionDescriptionHandler.constructor"); - this.logger = logger; - this.mediaStreamFactory = mediaStreamFactory; - this.sessionDescriptionHandlerConfiguration = sessionDescriptionHandlerConfiguration; - this._localMediaStream = new MediaStream(); - this._remoteMediaStream = new MediaStream(); - this._peerConnection = new RTCPeerConnection(sessionDescriptionHandlerConfiguration === null || sessionDescriptionHandlerConfiguration === void 0 ? void 0 : sessionDescriptionHandlerConfiguration.peerConnectionConfiguration); - this.initPeerConnectionEventHandlers(); - } - /** - * The local media stream currently being sent. - * - * @remarks - * The local media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * local media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get localMediaStream() { - return this._localMediaStream; - } - /** - * The remote media stream currently being received. - * - * @remarks - * The remote media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * remote media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get remoteMediaStream() { - return this._remoteMediaStream; - } - /** - * The data channel. Undefined before it is created. - */ - get dataChannel() { - return this._dataChannel; - } - /** - * The peer connection. Undefined if peer connection has closed. - * - * @remarks - * While access to the underlying `RTCPeerConnection` is provided, note that - * using methods with modify it may break the operation of this class. - * In particular, this class depends on exclusive access to the - * event handler properties. If you need access to the peer connection - * events, either register for events using `addEventListener()` on - * the `RTCPeerConnection` or set the `peerConnectionDelegate` on - * this `SessionDescriptionHandler`. - */ - get peerConnection() { - return this._peerConnection; - } - /** - * A delegate which provides access to the peer connection event handlers. - * - * @remarks - * Setting the peer connection event handlers directly is not supported - * and may break this class. As this class depends on exclusive access - * to them, a delegate may be set which provides alternative access to - * the event handlers in a fashion which is supported. - */ - get peerConnectionDelegate() { - return this._peerConnectionDelegate; - } - set peerConnectionDelegate(delegate) { - this._peerConnectionDelegate = delegate; - } - // The addtrack event does not get fired when JavaScript code explicitly adds tracks to the stream (by calling addTrack()). - // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - static dispatchAddTrackEvent(stream, track) { - stream.dispatchEvent(new MediaStreamTrackEvent("addtrack", { track })); - } - // The removetrack event does not get fired when JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). - // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onremovetrack - static dispatchRemoveTrackEvent(stream, track) { - stream.dispatchEvent(new MediaStreamTrackEvent("removetrack", { track })); - } - /** - * Stop tracks and close peer connection. - */ - close() { - this.logger.debug("SessionDescriptionHandler.close"); - if (this._peerConnection === undefined) { - return; - } - this._peerConnection.getReceivers().forEach((receiver) => { - receiver.track && receiver.track.stop(); - }); - this._peerConnection.getSenders().forEach((sender) => { - sender.track && sender.track.stop(); - }); - if (this._dataChannel) { - this._dataChannel.close(); - } - this._peerConnection.close(); - this._peerConnection = undefined; - } - /** - * Creates an offer or answer. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - getDescription(options, modifiers) { - var _a, _b; - this.logger.debug("SessionDescriptionHandler.getDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // Callback on data channel creation - this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; - // ICE will restart upon applying an offer created with the iceRestart option - const iceRestart = (_a = options === null || options === void 0 ? void 0 : options.offerOptions) === null || _a === void 0 ? void 0 : _a.iceRestart; - // ICE gathering timeout may be set on a per call basis, otherwise the configured default is used - const iceTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) === undefined - ? (_b = this.sessionDescriptionHandlerConfiguration) === null || _b === void 0 ? void 0 : _b.iceGatheringTimeout : options === null || options === void 0 ? void 0 : options.iceGatheringTimeout; - return this.getLocalMediaStream(options) - .then(() => this.createDataChannel(options)) - .then(() => this.createLocalOfferOrAnswer(options)) - .then((sessionDescription) => this.applyModifiers(sessionDescription, modifiers)) - .then((sessionDescription) => this.setLocalSessionDescription(sessionDescription)) - .then(() => this.waitForIceGatheringComplete(iceRestart, iceTimeout)) - .then(() => this.getLocalSessionDescription()) - .then((sessionDescription) => { - return { - body: sessionDescription.sdp, - contentType: "application/sdp" - }; - }) - .catch((error) => { - this.logger.error("SessionDescriptionHandler.getDescription failed - " + error); - throw error; - }); - } - /** - * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. - * @param contentType - The content type that is in the SIP Message. - */ - hasDescription(contentType) { - this.logger.debug("SessionDescriptionHandler.hasDescription"); - return contentType === "application/sdp"; - } - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones - A string containing DTMF digits. - * @param options - Options object to be used by sendDtmf. - */ - sendDtmf(tones, options) { - this.logger.debug("SessionDescriptionHandler.sendDtmf"); - if (this._peerConnection === undefined) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"); - return false; - } - const senders = this._peerConnection.getSenders(); - if (senders.length === 0) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"); - return false; - } - const dtmfSender = senders[0].dtmf; - if (!dtmfSender) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"); - return false; - } - const duration = options === null || options === void 0 ? void 0 : options.duration; - const interToneGap = options === null || options === void 0 ? void 0 : options.interToneGap; - try { - dtmfSender.insertDTMF(tones, duration, interToneGap); - } - catch (e) { - this.logger.error(e); - return false; - } - this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: " + tones.toString()); - return true; - } - /** - * Sets an offer or answer. - * @param sdp - The session description. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - setDescription(sdp, options, modifiers) { - this.logger.debug("SessionDescriptionHandler.setDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // Callback on data channel creation - this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; - // SDP type - const type = this._peerConnection.signalingState === "have-local-offer" ? "answer" : "offer"; - return this.getLocalMediaStream(options) - .then(() => this.applyModifiers({ sdp, type }, modifiers)) - .then((sessionDescription) => this.setRemoteSessionDescription(sessionDescription)) - .catch((error) => { - this.logger.error("SessionDescriptionHandler.setDescription failed - " + error); - throw error; - }); - } - /** - * Applies modifiers to SDP prior to setting the local or remote description. - * @param sdp - SDP to modify. - * @param modifiers - Modifiers to apply. - */ - applyModifiers(sdp, modifiers) { - this.logger.debug("SessionDescriptionHandler.applyModifiers"); - if (!modifiers || modifiers.length === 0) { - return Promise.resolve(sdp); - } - return modifiers - .reduce((cur, next) => cur.then(next), Promise.resolve(sdp)) - .then((modified) => { - this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"); - if (!modified.sdp || !modified.type) { - throw new Error("Invalid SDP."); - } - return { sdp: modified.sdp, type: modified.type }; - }); - } - /** - * Create a data channel. - * @remarks - * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. - * Only creates a data channel if creating a local offer. - * Only if one does not already exist. - * @param options - Session description handler options. - */ - createDataChannel(options) { - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // only create a data channel if requested - if ((options === null || options === void 0 ? void 0 : options.dataChannel) !== true) { - return Promise.resolve(); - } - // do not create a data channel if we already have one - if (this._dataChannel) { - return Promise.resolve(); - } - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable, assume we are creating a local offer so create a data channel - this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel"); - try { - this._dataChannel = this._peerConnection.createDataChannel((options === null || options === void 0 ? void 0 : options.dataChannelLabel) || "", options === null || options === void 0 ? void 0 : options.dataChannelOptions); - if (this.onDataChannel) { - this.onDataChannel(this._dataChannel); - } - return Promise.resolve(); - } - catch (error) { - return Promise.reject(error); - } - case "have-remote-offer": - return Promise.resolve(); - case "have-local-offer": - case "have-local-pranswer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - } - /** - * Depending on current signaling state, create a local offer or answer. - * @param options - Session description handler options. - */ - createLocalOfferOrAnswer(options) { - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable, assume we are creating a local offer - this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"); - return this._peerConnection.createOffer(options === null || options === void 0 ? void 0 : options.offerOptions); - case "have-remote-offer": - // if we have a remote offer, assume we are creating a local answer - this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"); - return this._peerConnection.createAnswer(options === null || options === void 0 ? void 0 : options.answerOptions); - case "have-local-offer": - case "have-local-pranswer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - } - /** - * Get a media stream from the media stream factory and set the local media stream. - * @param options - Session description handler options. - */ - getLocalMediaStream(options) { - this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - let constraints = Object.assign({}, options === null || options === void 0 ? void 0 : options.constraints); - // if we already have a local media stream... - if (this.localMediaStreamConstraints) { - // ignore constraint "downgrades" - constraints.audio = constraints.audio || this.localMediaStreamConstraints.audio; - constraints.video = constraints.video || this.localMediaStreamConstraints.video; - // if constraints have not changed, do not get a new media stream - if (JSON.stringify(this.localMediaStreamConstraints.audio) === JSON.stringify(constraints.audio) && - JSON.stringify(this.localMediaStreamConstraints.video) === JSON.stringify(constraints.video)) { - return Promise.resolve(); - } - } - else { - // if no constraints have been specified, default to audio for initial media stream - if (constraints.audio === undefined && constraints.video === undefined) { - constraints = { audio: true }; - } - } - this.localMediaStreamConstraints = constraints; - return this.mediaStreamFactory(constraints, this).then((mediaStream) => this.setLocalMediaStream(mediaStream)); - } - /** - * Sets the peer connection's sender tracks and local media stream tracks. - * - * @remarks - * Only the first audio and video tracks of the provided MediaStream are utilized. - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param stream - Media stream containing tracks to be utilized. - */ - setLocalMediaStream(stream) { - this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"); - if (!this._peerConnection) { - throw new Error("Peer connection undefined."); - } - const pc = this._peerConnection; - const localStream = this._localMediaStream; - const trackUpdates = []; - const updateTrack = (newTrack) => { - const kind = newTrack.kind; - if (kind !== "audio" && kind !== "video") { - throw new Error(`Unknown new track kind ${kind}.`); - } - const sender = pc.getSenders().find((sender) => sender.track && sender.track.kind === kind); - if (sender) { - trackUpdates.push(new Promise((resolve) => { - this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${kind} track`); - resolve(); - }).then(() => sender - .replaceTrack(newTrack) - .then(() => { - const oldTrack = localStream.getTracks().find((localTrack) => localTrack.kind === kind); - if (oldTrack) { - oldTrack.stop(); - localStream.removeTrack(oldTrack); - SessionDescriptionHandler.dispatchRemoveTrackEvent(localStream, oldTrack); - } - localStream.addTrack(newTrack); - SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); - }) - .catch((error) => { - this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${kind} track`); - throw error; - }))); - } - else { - trackUpdates.push(new Promise((resolve) => { - this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${kind} track`); - resolve(); - }).then(() => { - // Review: could make streamless tracks a configurable option? - // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack#Usage_notes - try { - pc.addTrack(newTrack, localStream); - } - catch (error) { - this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${kind} track`); - throw error; - } - localStream.addTrack(newTrack); - SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); - })); - } - }; - // update peer connection audio tracks - const audioTracks = stream.getAudioTracks(); - if (audioTracks.length) { - updateTrack(audioTracks[0]); - } - // update peer connection video tracks - const videoTracks = stream.getVideoTracks(); - if (videoTracks.length) { - updateTrack(videoTracks[0]); - } - return trackUpdates.reduce((p, x) => p.then(() => x), Promise.resolve()); - } - /** - * Gets the peer connection's local session description. - */ - getLocalSessionDescription() { - this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - const sdp = this._peerConnection.localDescription; - if (!sdp) { - return Promise.reject(new Error("Failed to get local session description")); - } - return Promise.resolve(sdp); - } - /** - * Sets the peer connection's local session description. - * @param sessionDescription - sessionDescription The session description. - */ - setLocalSessionDescription(sessionDescription) { - this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - return this._peerConnection.setLocalDescription(sessionDescription); - } - /** - * Sets the peer connection's remote session description. - * @param sessionDescription - The session description. - */ - setRemoteSessionDescription(sessionDescription) { - this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - const sdp = sessionDescription.sdp; - let type; - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable assume this is a remote offer - type = "offer"; - break; - case "have-local-offer": - // if we made an offer, assume this is a remote answer - type = "answer"; - break; - case "have-local-pranswer": - case "have-remote-offer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - if (!sdp) { - this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"); - return Promise.reject(new Error("SDP is undefined")); - } - return this._peerConnection.setRemoteDescription({ sdp, type }); - } - /** - * Sets a remote media stream track. - * - * @remarks - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param track - Media stream track to be utilized. - */ - setRemoteTrack(track) { - this.logger.debug("SessionDescriptionHandler.setRemoteTrack"); - const remoteStream = this._remoteMediaStream; - if (remoteStream.getTrackById(track.id)) { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${track.kind} track`); - } - else if (track.kind === "audio") { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); - remoteStream.getAudioTracks().forEach((track) => { - track.stop(); - remoteStream.removeTrack(track); - SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); - }); - remoteStream.addTrack(track); - SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); - } - else if (track.kind === "video") { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); - remoteStream.getVideoTracks().forEach((track) => { - track.stop(); - remoteStream.removeTrack(track); - SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); - }); - remoteStream.addTrack(track); - SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); - } - } - /** - * Called when ICE gathering completes and resolves any waiting promise. - */ - iceGatheringComplete() { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"); - // clear timer if need be - if (this.iceGatheringCompleteTimeoutId !== undefined) { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"); - clearTimeout(this.iceGatheringCompleteTimeoutId); - this.iceGatheringCompleteTimeoutId = undefined; - } - // resolve and cleanup promise if need be - if (this.iceGatheringCompletePromise !== undefined) { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"); - this.iceGatheringCompleteResolve && this.iceGatheringCompleteResolve(); - this.iceGatheringCompletePromise = undefined; - this.iceGatheringCompleteResolve = undefined; - this.iceGatheringCompleteReject = undefined; - } - } - /** - * Wait for ICE gathering to complete. - * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). - * @param timeout - Milliseconds after which waiting times out. No timeout if 0. - */ - waitForIceGatheringComplete(restart = false, timeout = 0) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"); - if (this._peerConnection === undefined) { - return Promise.reject("Peer connection closed."); - } - // guard already complete - if (!restart && this._peerConnection.iceGatheringState === "complete") { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"); - return Promise.resolve(); - } - // only one may be waiting, reject any prior - if (this.iceGatheringCompletePromise !== undefined) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"); - this.iceGatheringCompleteReject && this.iceGatheringCompleteReject(new Error("Promise superseded.")); - this.iceGatheringCompletePromise = undefined; - this.iceGatheringCompleteResolve = undefined; - this.iceGatheringCompleteReject = undefined; - } - this.iceGatheringCompletePromise = new Promise((resolve, reject) => { - this.iceGatheringCompleteResolve = resolve; - this.iceGatheringCompleteReject = reject; - if (timeout > 0) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in " + timeout); - this.iceGatheringCompleteTimeoutId = setTimeout(() => { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"); - this.iceGatheringComplete(); - }, timeout); - } - }); - return this.iceGatheringCompletePromise; - } - /** - * Initializes the peer connection event handlers - */ - initPeerConnectionEventHandlers() { - this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"); - if (!this._peerConnection) - throw new Error("Peer connection undefined."); - const peerConnection = this._peerConnection; - peerConnection.onconnectionstatechange = (event) => { - var _a; - const newState = peerConnection.connectionState; - this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onconnectionstatechange) { - this._peerConnectionDelegate.onconnectionstatechange(event); - } - }; - peerConnection.ondatachannel = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.ondatachannel`); - this._dataChannel = event.channel; - if (this.onDataChannel) { - this.onDataChannel(this._dataChannel); - } - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ondatachannel) { - this._peerConnectionDelegate.ondatachannel(event); - } - }; - peerConnection.onicecandidate = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onicecandidate`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidate) { - this._peerConnectionDelegate.onicecandidate(event); - } - }; - peerConnection.onicecandidateerror = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onicecandidateerror`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidateerror) { - this._peerConnectionDelegate.onicecandidateerror(event); - } - }; - peerConnection.oniceconnectionstatechange = (event) => { - var _a; - const newState = peerConnection.iceConnectionState; - this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.oniceconnectionstatechange) { - this._peerConnectionDelegate.oniceconnectionstatechange(event); - } - }; - peerConnection.onicegatheringstatechange = (event) => { - var _a; - const newState = peerConnection.iceGatheringState; - this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${newState}`); - if (newState === "complete") { - this.iceGatheringComplete(); // complete waiting for ICE gathering to complete - } - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicegatheringstatechange) { - this._peerConnectionDelegate.onicegatheringstatechange(event); - } - }; - peerConnection.onnegotiationneeded = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onnegotiationneeded`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onnegotiationneeded) { - this._peerConnectionDelegate.onnegotiationneeded(event); - } - }; - peerConnection.onsignalingstatechange = (event) => { - var _a; - const newState = peerConnection.signalingState; - this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onsignalingstatechange) { - this._peerConnectionDelegate.onsignalingstatechange(event); - } - }; - peerConnection.onstatsended = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onstatsended`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onstatsended) { - this._peerConnectionDelegate.onstatsended(event); - } - }; - peerConnection.ontrack = (event) => { - var _a; - const kind = event.track.kind; - const enabled = event.track.enabled ? "enabled" : "disabled"; - this.logger.debug(`SessionDescriptionHandler.ontrack ${kind} ${enabled}`); - this.setRemoteTrack(event.track); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ontrack) { - this._peerConnectionDelegate.ontrack(event); - } - }; - } -} - - -/***/ }), -/* 168 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 169 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 170 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 171 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(172); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return _transport__WEBPACK_IMPORTED_MODULE_0__["Transport"]; }); - -/* harmony import */ var _transport_options__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(173); -/* harmony import */ var _transport_options__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_transport_options__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport_options__WEBPACK_IMPORTED_MODULE_1__) if(["Transport","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport_options__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/** - * A Transport implementation for web browsers. - * @packageDocumentation - */ - - - - -/***/ }), -/* 172 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transport", function() { return Transport; }); -/* harmony import */ var _api_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(108); -/* harmony import */ var _api_exceptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _api_transport_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(156); -/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); - - - - -/** - * Transport for SIP over secure WebSocket (WSS). - * @public - */ -class Transport { - constructor(logger, options) { - this._state = _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected; - this.transitioningState = false; - // state emitter - this._stateEventEmitter = new _api_emitter__WEBPACK_IMPORTED_MODULE_0__["EmitterImpl"](); - // logger - this.logger = logger; - // guard deprecated options (remove this in version 16.x) - if (options) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const optionsDeprecated = options; - const wsServersDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.wsServers; - const maxReconnectionAttemptsDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.maxReconnectionAttempts; - if (wsServersDeprecated !== undefined) { - const deprecatedMessage = `The transport option "wsServers" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (maxReconnectionAttemptsDeprecated !== undefined) { - const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // hack - if (wsServersDeprecated && !options.server) { - if (typeof wsServersDeprecated === "string") { - options.server = wsServersDeprecated; - } - if (wsServersDeprecated instanceof Array) { - options.server = wsServersDeprecated[0]; - } - } - } - // initialize configuration - this.configuration = Object.assign(Object.assign({}, Transport.defaultOptions), options); - // validate server URL - const url = this.configuration.server; - const parsed = _core__WEBPACK_IMPORTED_MODULE_3__["Grammar"].parse(url, "absoluteURI"); - if (parsed === -1) { - this.logger.error(`Invalid WebSocket Server URL "${url}"`); - throw new Error("Invalid WebSocket Server URL"); - } - if (!["wss", "ws", "udp"].includes(parsed.scheme)) { - this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); - throw new Error("Invalid scheme in WebSocket Server URL"); - } - this._protocol = parsed.scheme.toUpperCase(); - } - dispose() { - return this.disconnect(); - } - /** - * The protocol. - * - * @remarks - * Formatted as defined for the Via header sent-protocol transport. - * https://tools.ietf.org/html/rfc3261#section-20.42 - */ - get protocol() { - return this._protocol; - } - /** - * The URL of the WebSocket Server. - */ - get server() { - return this.configuration.server; - } - /** - * Transport state. - */ - get state() { - return this._state; - } - /** - * Transport state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * The WebSocket. - */ - get ws() { - return this._ws; - } - /** - * Connect to network. - * Resolves once connected. Otherwise rejects with an Error. - */ - connect() { - return this._connect(); - } - /** - * Disconnect from network. - * Resolves once disconnected. Otherwise rejects with an Error. - */ - disconnect() { - return this._disconnect(); - } - /** - * Returns true if the `state` equals "Connected". - * @remarks - * This is equivalent to `state === TransportState.Connected`. - */ - isConnected() { - return this.state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected; - } - /** - * Sends a message. - * Resolves once message is sent. Otherwise rejects with an Error. - * @param message - Message to send. - */ - send(message) { - // Error handling is independent of whether the message was a request or - // response. - // - // If the transport user asks for a message to be sent over an - // unreliable transport, and the result is an ICMP error, the behavior - // depends on the type of ICMP error. Host, network, port or protocol - // unreachable errors, or parameter problem errors SHOULD cause the - // transport layer to inform the transport user of a failure in sending. - // Source quench and TTL exceeded ICMP errors SHOULD be ignored. - // - // If the transport user asks for a request to be sent over a reliable - // transport, and the result is a connection failure, the transport - // layer SHOULD inform the transport user of a failure in sending. - // https://tools.ietf.org/html/rfc3261#section-18.4 - return this._send(message); - } - _connect() { - this.logger.log(`Connecting ${this.server}`); - switch (this.state) { - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: - // If `state` is "Connecting", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); - } - if (!this.connectPromise) { - throw new Error("Connect promise must be defined."); - } - return this.connectPromise; // Already connecting - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: - // If `state` is "Connected", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting)); - } - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - return Promise.resolve(); // Already connected - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: - // If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: - // If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - default: - throw new Error("Unknown state"); - } - let ws; - try { - // WebSocket() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket - ws = new WebSocket(this.server, "sip"); - ws.binaryType = "arraybuffer"; // set data type of received binary messages - ws.addEventListener("close", (ev) => this.onWebSocketClose(ev, ws)); - ws.addEventListener("error", (ev) => this.onWebSocketError(ev, ws)); - ws.addEventListener("open", (ev) => this.onWebSocketOpen(ev, ws)); - ws.addEventListener("message", (ev) => this.onWebSocketMessage(ev, ws)); - this._ws = ws; - } - catch (error) { - this._ws = undefined; - this.logger.error("WebSocket construction failed."); - this.logger.error(error); - return new Promise((resolve, reject) => { - this.connectResolve = resolve; - this.connectReject = reject; - // The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); - }); - } - this.connectPromise = new Promise((resolve, reject) => { - this.connectResolve = resolve; - this.connectReject = reject; - this.connectTimeout = setTimeout(() => { - this.logger.warn("Connect timed out. " + - "Exceeded time set in configuration.connectionTimeout: " + - this.configuration.connectionTimeout + - "s."); - ws.close(1000); // careful here to use a local reference instead of this._ws - }, this.configuration.connectionTimeout * 1000); - }); - return this.connectPromise; - } - _disconnect() { - this.logger.log(`Disconnecting ${this.server}`); - switch (this.state) { - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: - // If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: - // If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - try { - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting); - } - catch (e) { - if (e instanceof _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: - // If `state` is "Disconnecting", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); - } - if (!this.disconnectPromise) { - throw new Error("Disconnect promise must be defined."); - } - return this.disconnectPromise; // Already disconnecting - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: - // If `state` is "Disconnected", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting)); - } - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - return Promise.resolve(); // Already disconnected - default: - throw new Error("Unknown state"); - } - if (!this._ws) { - throw new Error("WebSocket must be defined."); - } - const ws = this._ws; - this.disconnectPromise = new Promise((resolve, reject) => { - this.disconnectResolve = resolve; - this.disconnectReject = reject; - try { - // WebSocket.close() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close - ws.close(1000); // careful here to use a local reference instead of this._ws - } - catch (error) { - // Treating this as a coding error as it apparently can only happen - // if you pass close() invalid parameters (so it should never happen) - this.logger.error("WebSocket close failed."); - this.logger.error(error); - throw error; - } - }); - return this.disconnectPromise; - } - _send(message) { - if (this.configuration.traceSip === true) { - this.logger.log("Sending WebSocket message:\n\n" + message + "\n"); - } - if (this._state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - return Promise.reject(new Error("Not connected.")); - } - if (!this._ws) { - throw new Error("WebSocket undefined."); - } - try { - // WebSocket.send() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send - this._ws.send(message); - } - catch (error) { - if (error instanceof Error) { - return Promise.reject(error); - } - return Promise.reject(new Error("WebSocket send failed.")); - } - return Promise.resolve(); - } - /** - * WebSocket "onclose" event handler. - * @param ev - Event. - */ - onWebSocketClose(ev, ws) { - if (ws !== this._ws) { - return; - } - const message = `WebSocket closed ${this.server} (code: ${ev.code})`; - const error = !this.disconnectPromise ? new Error(message) : undefined; - if (error) { - this.logger.warn("WebSocket closed unexpectedly"); - } - this.logger.log(message); - // We are about to transition to disconnected, so clear our web socket - this._ws = undefined; - // The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected, error); - } - /** - * WebSocket "onerror" event handler. - * @param ev - Event. - */ - onWebSocketError(ev, ws) { - if (ws !== this._ws) { - return; - } - this.logger.error("WebSocket error occurred."); - } - /** - * WebSocket "onmessage" event handler. - * @param ev - Event. - */ - onWebSocketMessage(ev, ws) { - if (ws !== this._ws) { - return; - } - const data = ev.data; - let finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket message with CRLF Keep Alive response"); - } - return; - } - if (!data) { - this.logger.warn("Received empty message, discarding..."); - return; - } - if (typeof data !== "string") { - // WebSocket binary message. - try { - finishedData = new TextDecoder().decode(new Uint8Array(data)); - // TextDecoder (above) is not supported by old browsers, but it correctly decodes UTF-8. - // The line below is an ISO 8859-1 (Latin 1) decoder, so just UTF-8 code points that are 1 byte. - // It's old code and works in old browsers (IE), so leaving it here in a comment in case someone needs it. - // finishedData = String.fromCharCode.apply(null, (new Uint8Array(data) as unknown as Array)); - } - catch (err) { - this.logger.error(err); - this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket binary message:\n\n" + finishedData + "\n"); - } - } - else { - // WebSocket text message. - finishedData = data; - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket text message:\n\n" + finishedData + "\n"); - } - } - if (this.state !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - this.logger.warn("Received message while not connected, discarding..."); - return; - } - if (this.onMessage) { - try { - this.onMessage(finishedData); - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onMessage callback"); - throw e; // rethrow unhandled exception - } - } - } - /** - * WebSocket "onopen" event handler. - * @param ev - Event. - */ - onWebSocketOpen(ev, ws) { - if (ws !== this._ws) { - return; - } - if (this._state === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - this.logger.log(`WebSocket opened ${this.server}`); - this.transitionState(_api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected); - } - } - /** - * Helper function to generate an Error. - * @param state - State transitioning to. - */ - transitionLoopDetectedError(state) { - let message = `A state transition loop has been detected.`; - message += ` An attempt to transition from ${this._state} to ${state} before the prior transition completed.`; - message += ` Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?`; - this.logger.error(message); - return new _api_exceptions__WEBPACK_IMPORTED_MODULE_1__["StateTransitionError"]("Loop detected."); - } - /** - * Transition transport state. - * @internal - */ - transitionState(newState, error) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - if (this.transitioningState) { - throw this.transitionLoopDetectedError(newState); - } - this.transitioningState = true; - // Validate state transition - switch (this._state) { - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected && - newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && - newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { - invalidTransition(); - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { - invalidTransition(); - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting && newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected) { - invalidTransition(); - } - break; - case _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected: - if (newState !== _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - invalidTransition(); - } - break; - default: - throw new Error("Unknown state."); - } - // Update state - const oldState = this._state; - this._state = newState; - // Local copies of connect promises (guarding against callbacks changing them indirectly) - // const connectPromise = this.connectPromise; - const connectResolve = this.connectResolve; - const connectReject = this.connectReject; - // Reset connect promises if no longer connecting - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - this.connectPromise = undefined; - this.connectResolve = undefined; - this.connectReject = undefined; - } - // Local copies of disconnect promises (guarding against callbacks changing them indirectly) - // const disconnectPromise = this.disconnectPromise; - const disconnectResolve = this.disconnectResolve; - const disconnectReject = this.disconnectReject; - // Reset disconnect promises if no longer disconnecting - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { - this.disconnectPromise = undefined; - this.disconnectResolve = undefined; - this.disconnectReject = undefined; - } - // Clear any outstanding connect timeout - if (this.connectTimeout) { - clearTimeout(this.connectTimeout); - this.connectTimeout = undefined; - } - this.logger.log(`Transitioned from ${oldState} to ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Transition to Connected - if (newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - this.startSendingKeepAlives(); - if (this.onConnect) { - try { - this.onConnect(); - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onConnect callback"); - throw e; // rethrow unhandled exception - } - } - } - // Transition from Connected - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected) { - this.stopSendingKeepAlives(); - if (this.onDisconnect) { - try { - if (error) { - this.onDisconnect(error); - } - else { - this.onDisconnect(); - } - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onDisconnect callback"); - throw e; // rethrow unhandled exception - } - } - } - // Complete connect promise - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connecting) { - if (!connectResolve) { - throw new Error("Connect resolve undefined."); - } - if (!connectReject) { - throw new Error("Connect reject undefined."); - } - newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Connected ? connectResolve() : connectReject(error || new Error("Connect aborted.")); - } - // Complete disconnect promise - if (oldState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnecting) { - if (!disconnectResolve) { - throw new Error("Disconnect resolve undefined."); - } - if (!disconnectReject) { - throw new Error("Disconnect reject undefined."); - } - newState === _api_transport_state__WEBPACK_IMPORTED_MODULE_2__["TransportState"].Disconnected - ? disconnectResolve() - : disconnectReject(error || new Error("Disconnect aborted.")); - } - this.transitioningState = false; - } - // TODO: Review "KeepAlive Stuff". - // It is not clear if it works and there are no tests for it. - // It was blindly lifted the keep alive code unchanged from earlier transport code. - // - // From the RFC... - // - // SIP WebSocket Clients and Servers may keep their WebSocket - // connections open by sending periodic WebSocket "Ping" frames as - // described in [RFC6455], Section 5.5.2. - // ... - // The indication and use of the CRLF NAT keep-alive mechanism defined - // for SIP connection-oriented transports in [RFC5626], Section 3.5.1 or - // [RFC6223] are, of course, usable over the transport defined in this - // specification. - // https://tools.ietf.org/html/rfc7118#section-6 - // - // and... - // - // The Ping frame contains an opcode of 0x9. - // https://tools.ietf.org/html/rfc6455#section-5.5.2 - // - // ============================== - // KeepAlive Stuff - // ============================== - clearKeepAliveTimeout() { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - } - /** - * Send a keep-alive (a double-CRLF sequence). - */ - sendKeepAlive() { - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return Promise.resolve(); - } - this.keepAliveDebounceTimeout = setTimeout(() => { - this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - } - /** - * Start sending keep-alives. - */ - startSendingKeepAlives() { - // Compute an amount of time in seconds to wait before sending another keep-alive. - const computeKeepAliveTimeout = (upperBound) => { - const lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); - }; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(() => { - this.sendKeepAlive(); - this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - } - /** - * Stop sending keep-alives. - */ - stopSendingKeepAlives() { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - } -} -Transport.defaultOptions = { - server: "", - connectionTimeout: 5, - keepAliveInterval: 0, - keepAliveDebounce: 10, - traceSip: true -}; - - -/***/ }), -/* 173 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 174 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); - -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(160); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _session_description_handler__WEBPACK_IMPORTED_MODULE_1__) if(["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _session_description_handler__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _simple_user__WEBPACK_IMPORTED_MODULE_2__) if(["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _simple_user__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transport__WEBPACK_IMPORTED_MODULE_3__) if(["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transport__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__)); - - - - - - -/***/ }), -/* 175 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTcpCandidates"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripTelephoneEvent"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["cleanJitsiSdpImageattr"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripG722"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripRtpPayload"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["stripVideo"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["addMidLines"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return _modifiers__WEBPACK_IMPORTED_MODULE_0__["holdModifier"]; }); - -/** - * SessionDescriptionHandlerModifer functions for web browsers. - * @packageDocumentation - */ - - - -/***/ }), -/* 176 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTcpCandidates", function() { return stripTcpCandidates; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripTelephoneEvent", function() { return stripTelephoneEvent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanJitsiSdpImageattr", function() { return cleanJitsiSdpImageattr; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripG722", function() { return stripG722; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripRtpPayload", function() { return stripRtpPayload; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripVideo", function() { return stripVideo; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addMidLines", function() { return addMidLines; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "holdModifier", function() { return holdModifier; }); -const stripPayload = (sdp, payload) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const mediaDescs = []; - const lines = sdp.split(/\r\n/); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let currentMediaDesc; - for (let i = 0; i < lines.length;) { - const line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - const rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (const mediaDesc of mediaDescs) { - const mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (let j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -const stripMediaDescription = (sdp, description) => { - const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - const groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - let midLineToRemove; - sdp = sdp.split(/^m=/gm).filter((section) => { - if (section.substr(0, description.length) === description) { - midLineToRemove = section.match(/^a=mid:.*$/gm); - if (midLineToRemove) { - const step = midLineToRemove[0].match(/:.+$/g); - if (step) { - midLineToRemove = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - const groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - let groupLinePortion = groupLine[0]; - // eslint-disable-next-line no-useless-escape - const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -/** - * Modifier. - * @public - */ -function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function stripRtpPayload(payload) { - return (description) => { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -/** - * Modifier. - * @public - */ -function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -function addMidLines(description) { - let sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - const mlines = sdp.match(/^m=.*$/gm); - const sdpArray = sdp.split(/^m=.*$/gm); - if (mlines) { - mlines.forEach((elem, idx) => { - mlines[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray.forEach((elem, idx) => { - if (mlines && mlines[idx]) { - sdpArray[idx] = elem + mlines[idx]; - } - }); - sdp = sdpArray.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -/** - * The modifier that should be used when the session would like to place the call on hold. - * @param description - The description that will be modified. - */ -function holdModifier(description) { - if (!description.sdp || !description.type) { - throw new Error("Invalid SDP"); - } - let sdp = description.sdp; - const type = description.type; - if (sdp) { - if (!/a=(sendrecv|sendonly|recvonly|inactive)/.test(sdp)) { - sdp = sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - sdp = sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - sdp = sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - } - return Promise.resolve({ sdp, type }); -} - - -/***/ }), -/* 177 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _simple_user__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return _simple_user__WEBPACK_IMPORTED_MODULE_0__["SimpleUser"]; }); - -/* harmony import */ var _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(179); -/* harmony import */ var _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__) if(["SimpleUser","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _simple_user_delegate__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/* harmony import */ var _simple_user_options__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(180); -/* harmony import */ var _simple_user_options__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_simple_user_options__WEBPACK_IMPORTED_MODULE_2__); -/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _simple_user_options__WEBPACK_IMPORTED_MODULE_2__) if(["SimpleUser","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _simple_user_options__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__)); -/** - * A simple SIP user implementation for web browsers. - * @packageDocumentation - */ - - - - - -/***/ }), -/* 178 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleUser", function() { return SimpleUser; }); -/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _modifiers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(175); -/* harmony import */ var _session_description_handler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); -/* harmony import */ var _transport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); - - - - -/** - * A simple SIP user class. - * @remarks - * While this class is completely functional for simple use cases, it is not intended - * to provide an interface which is suitable for most (must less all) applications. - * While this class has many limitations (for example, it only handles a single concurrent session), - * it is, however, intended to serve as a simple example of using the SIP.js API. - * @public - */ -class SimpleUser { - /** - * Constructs a new instance of the `SimpleUser` class. - * @param server - SIP WebSocket Server URL. - * @param options - Options bucket. See {@link SimpleUserOptions} for details. - */ - constructor(server, options = {}) { - this.attemptingReconnection = false; - this.connectRequested = false; - this.held = false; - this.registerer = undefined; - this.registerRequested = false; - this.session = undefined; - // Delegate - this.delegate = options.delegate; - // Copy options - this.options = Object.assign({}, options); - // UserAgentOptions - const userAgentOptions = Object.assign({}, options.userAgentOptions); - // Transport - if (!userAgentOptions.transportConstructor) { - userAgentOptions.transportConstructor = _transport__WEBPACK_IMPORTED_MODULE_3__["Transport"]; - } - // TransportOptions - if (!userAgentOptions.transportOptions) { - userAgentOptions.transportOptions = { - server - }; - } - // URI - if (!userAgentOptions.uri) { - // If an AOR was provided, convert it to a URI - if (options.aor) { - const uri = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(options.aor); - if (!uri) { - throw new Error(`Failed to create valid URI from ${options.aor}`); - } - userAgentOptions.uri = uri; - } - } - // UserAgent - this.userAgent = new _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"](userAgentOptions); - // UserAgent's delegate - this.userAgent.delegate = { - // Handle connection with server established - onConnect: () => { - this.logger.log(`[${this.id}] Connected`); - if (this.delegate && this.delegate.onServerConnect) { - this.delegate.onServerConnect(); - } - if (this.registerer && this.registerRequested) { - this.logger.log(`[${this.id}] Registering...`); - this.registerer.register().catch((e) => { - this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`); - this.logger.error(e.toString()); - }); - } - }, - // Handle connection with server lost - onDisconnect: (error) => { - this.logger.log(`[${this.id}] Disconnected`); - if (this.delegate && this.delegate.onServerDisconnect) { - this.delegate.onServerDisconnect(error); - } - if (this.session) { - this.logger.log(`[${this.id}] Hanging up...`); - this.hangup() // cleanup hung calls - .catch((e) => { - this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`); - this.logger.error(e.toString()); - }); - } - if (this.registerer) { - this.logger.log(`[${this.id}] Unregistering...`); - this.registerer - .unregister() // cleanup invalid registrations - .catch((e) => { - this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`); - this.logger.error(e.toString()); - }); - } - // Only attempt to reconnect if network/server dropped the connection. - if (error) { - this.attemptReconnection(); - } - }, - // Handle incoming invitations - onInvite: (invitation) => { - this.logger.log(`[${this.id}] Received INVITE`); - // Guard against a pre-existing session. This implementation only supports one session at a time. - // However an incoming INVITE request may be received at any time and/or while in the process - // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. - if (this.session) { - this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`); - invitation - .reject() - .then(() => { - this.logger.log(`[${this.id}] Rejected INVITE`); - }) - .catch((error) => { - this.logger.error(`[${this.id}] Failed to reject INVITE`); - this.logger.error(error.toString()); - }); - return; - } - // Use our configured constraints as options for any Inviter created as result of a REFER - const referralInviterOptions = { - sessionDescriptionHandlerOptions: { constraints: this.constraints } - }; - // Initialize our session - this.initSession(invitation, referralInviterOptions); - // Delegate - if (this.delegate && this.delegate.onCallReceived) { - this.delegate.onCallReceived(); - } - else { - this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`); - invitation - .reject() - .then(() => { - this.logger.log(`[${this.id}] Rejected INVITE`); - }) - .catch((error) => { - this.logger.error(`[${this.id}] Failed to reject INVITE`); - this.logger.error(error.toString()); - }); - } - }, - // Handle incoming messages - onMessage: (message) => { - message.accept().then(() => { - if (this.delegate && this.delegate.onMessageReceived) { - this.delegate.onMessageReceived(message.request.body); - } - }); - } - }; - // Use the SIP.js logger - this.logger = this.userAgent.getLogger("sip.SimpleUser"); - // Monitor network connectivity and attempt reconnection when we come online - window.addEventListener("online", () => { - this.logger.log(`[${this.id}] Online`); - this.attemptReconnection(); - }); - } - /** - * Instance identifier. - * @internal - */ - get id() { - return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; - } - /** The local media stream. Undefined if call not answered. */ - get localMediaStream() { - var _a; - const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; - if (!sdh) { - return undefined; - } - if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session description handler not instance of web SessionDescriptionHandler"); - } - return sdh.localMediaStream; - } - /** The remote media stream. Undefined if call not answered. */ - get remoteMediaStream() { - var _a; - const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; - if (!sdh) { - return undefined; - } - if (!(sdh instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session description handler not instance of web SessionDescriptionHandler"); - } - return sdh.remoteMediaStream; - } - /** - * The local audio track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localAudioTrack() { - var _a; - return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); - } - /** - * The local video track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localVideoTrack() { - var _a; - return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); - } - /** - * The remote audio track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteAudioTrack() { - var _a; - return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); - } - /** - * The remote video track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteVideoTrack() { - var _a; - return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); - } - /** - * Connect. - * @remarks - * Start the UserAgent's WebSocket Transport. - */ - connect() { - this.logger.log(`[${this.id}] Connecting UserAgent...`); - this.connectRequested = true; - if (this.userAgent.state !== _api__WEBPACK_IMPORTED_MODULE_0__["UserAgentState"].Started) { - return this.userAgent.start(); - } - return this.userAgent.reconnect(); - } - /** - * Disconnect. - * @remarks - * Stop the UserAgent's WebSocket Transport. - */ - disconnect() { - this.logger.log(`[${this.id}] Disconnecting UserAgent...`); - this.connectRequested = false; - return this.userAgent.stop(); - } - /** - * Return true if connected. - */ - isConnected() { - return this.userAgent.isConnected(); - } - /** - * Start receiving incoming calls. - * @remarks - * Send a REGISTER request for the UserAgent's AOR. - * Resolves when the REGISTER request is sent, otherwise rejects. - */ - register(registererOptions, registererRegisterOptions) { - this.logger.log(`[${this.id}] Registering UserAgent...`); - this.registerRequested = true; - if (!this.registerer) { - this.registerer = new _api__WEBPACK_IMPORTED_MODULE_0__["Registerer"](this.userAgent, registererOptions); - this.registerer.stateChange.addListener((state) => { - switch (state) { - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Initial: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Registered: - if (this.delegate && this.delegate.onRegistered) { - this.delegate.onRegistered(); - } - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Unregistered: - if (this.delegate && this.delegate.onUnregistered) { - this.delegate.onUnregistered(); - } - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["RegistererState"].Terminated: - this.registerer = undefined; - break; - default: - throw new Error("Unknown registerer state."); - } - }); - } - return this.registerer.register(registererRegisterOptions).then(() => { - return; - }); - } - /** - * Stop receiving incoming calls. - * @remarks - * Send an un-REGISTER request for the UserAgent's AOR. - * Resolves when the un-REGISTER request is sent, otherwise rejects. - */ - unregister(registererUnregisterOptions) { - this.logger.log(`[${this.id}] Unregistering UserAgent...`); - this.registerRequested = false; - if (!this.registerer) { - return Promise.resolve(); - } - return this.registerer.unregister(registererUnregisterOptions).then(() => { - return; - }); - } - /** - * Make an outgoing call. - * @remarks - * Send an INVITE request to create a new Session. - * Resolves when the INVITE request is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if Session is established. - * @param destination - The target destination to call. A SIP address to send the INVITE to. - * @param inviterOptions - Optional options for Inviter constructor. - * @param inviterInviteOptions - Optional options for Inviter.invite(). - */ - call(destination, inviterOptions, inviterInviteOptions) { - this.logger.log(`[${this.id}] Beginning Session...`); - if (this.session) { - return Promise.reject(new Error("Session already exists.")); - } - const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); - if (!target) { - return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); - } - // Use our configured constraints as InviterOptions if none provided - if (!inviterOptions) { - inviterOptions = {}; - } - if (!inviterOptions.sessionDescriptionHandlerOptions) { - inviterOptions.sessionDescriptionHandlerOptions = {}; - } - if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { - inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; - } - // Create a new Inviter for the outgoing Session - const inviter = new _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"](this.userAgent, target, inviterOptions); - // Send INVITE - return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => { - return; - }); - } - /** - * Hangup a call. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - hangup() { - this.logger.log(`[${this.id}] Hangup...`); - return this.terminate(); - } - /** - * Answer an incoming call. - * @remarks - * Accept an incoming INVITE request creating a new Session. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if and when call is established. - * @param invitationAcceptOptions - Optional options for Inviter.accept(). - */ - answer(invitationAcceptOptions) { - this.logger.log(`[${this.id}] Accepting Invitation...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { - return Promise.reject(new Error("Session not instance of Invitation.")); - } - // Use our configured constraints as InvitationAcceptOptions if none provided - if (!invitationAcceptOptions) { - invitationAcceptOptions = {}; - } - if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { - invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; - } - if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { - invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; - } - return this.session.accept(invitationAcceptOptions); - } - /** - * Decline an incoming call. - * @remarks - * Reject an incoming INVITE request. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - decline() { - this.logger.log(`[${this.id}] rejecting Invitation...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - if (!(this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"])) { - return Promise.reject(new Error("Session not instance of Invitation.")); - } - return this.session.reject(); - } - /** - * Hold call - * @remarks - * Send a re-INVITE with new offer indicating "hold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - hold() { - this.logger.log(`[${this.id}] holding session...`); - return this.setHold(true); - } - /** - * Unhold call. - * @remarks - * Send a re-INVITE with new offer indicating "unhold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - unhold() { - this.logger.log(`[${this.id}] unholding session...`); - return this.setHold(false); - } - /** - * Hold state. - * @remarks - * True if session media is on hold. - */ - isHeld() { - return this.held; - } - /** - * Mute call. - * @remarks - * Disable sender's media tracks. - */ - mute() { - this.logger.log(`[${this.id}] disabling media tracks...`); - this.setMute(true); - } - /** - * Unmute call. - * @remarks - * Enable sender's media tracks. - */ - unmute() { - this.logger.log(`[${this.id}] enabling media tracks...`); - this.setMute(false); - } - /** - * Mute state. - * @remarks - * True if sender's media track is disabled. - */ - isMuted() { - const track = this.localAudioTrack || this.localVideoTrack; - return track ? !track.enabled : false; - } - /** - * Send DTMF. - * @remarks - * Send an INFO request with content type application/dtmf-relay. - * @param tone - Tone to send. - */ - sendDTMF(tone) { - this.logger.log(`[${this.id}] sending DTMF...`); - // As RFC 6086 states, sending DTMF via INFO is not standardized... - // - // Companies have been using INFO messages in order to transport - // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are - // proprietary and have not been standardized. - // https://tools.ietf.org/html/rfc6086#section-2 - // - // It is however widely supported based on this draft: - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 - // Validate tone - if (!/^[0-9A-D#*,]$/.exec(tone)) { - return Promise.reject(new Error("Invalid DTMF tone.")); - } - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - // The UA MUST populate the "application/dtmf-relay" body, as defined - // earlier, with the button pressed and the duration it was pressed - // for. Technically, this actually requires the INFO to be generated - // when the user *releases* the button, however if the user has still - // not released a button after 5 seconds, which is the maximum duration - // supported by this mechanism, the UA should generate the INFO at that - // time. - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3 - this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`); - const dtmf = tone; - const duration = 2000; - const body = { - contentDisposition: "render", - contentType: "application/dtmf-relay", - content: "Signal=" + dtmf + "\r\nDuration=" + duration - }; - const requestOptions = { body }; - return this.session.info({ requestOptions }).then(() => { - return; - }); - } - /** - * Send a message. - * @remarks - * Send a MESSAGE request. - * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. - */ - message(destination, message) { - this.logger.log(`[${this.id}] sending message...`); - const target = _api__WEBPACK_IMPORTED_MODULE_0__["UserAgent"].makeURI(destination); - if (!target) { - return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); - } - return new _api__WEBPACK_IMPORTED_MODULE_0__["Messager"](this.userAgent, target, message).message(); - } - /** Media constraints. */ - get constraints() { - var _a; - let constraints = { audio: true, video: false }; // default to audio only calls - if ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.constraints) { - constraints = Object.assign({}, this.options.media.constraints); - } - return constraints; - } - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - attemptReconnection(reconnectionAttempt = 1) { - const reconnectionAttempts = this.options.reconnectionAttempts || 3; - const reconnectionDelay = this.options.reconnectionDelay || 4; - if (!this.connectRequested) { - this.logger.log(`[${this.id}] Reconnection not currently desired`); - return; // If intentionally disconnected, don't reconnect. - } - if (this.attemptingReconnection) { - this.logger.log(`[${this.id}] Reconnection attempt already in progress`); - } - if (reconnectionAttempt > reconnectionAttempts) { - this.logger.log(`[${this.id}] Reconnection maximum attempts reached`); - return; - } - if (reconnectionAttempt === 1) { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); - } - else { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`); - } - this.attemptingReconnection = true; - setTimeout(() => { - if (!this.connectRequested) { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`); - this.attemptingReconnection = false; - return; // If intentionally disconnected, don't reconnect. - } - this.userAgent - .reconnect() - .then(() => { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); - this.attemptingReconnection = false; - }) - .catch((error) => { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); - this.logger.error(error.message); - this.attemptingReconnection = false; - this.attemptReconnection(++reconnectionAttempt); - }); - }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); - } - /** Helper function to remove media from html elements. */ - cleanupMedia() { - if (this.options.media) { - if (this.options.media.local) { - if (this.options.media.local.video) { - this.options.media.local.video.srcObject = null; - this.options.media.local.video.pause(); - } - } - if (this.options.media.remote) { - if (this.options.media.remote.audio) { - this.options.media.remote.audio.srcObject = null; - this.options.media.remote.audio.pause(); - } - if (this.options.media.remote.video) { - this.options.media.remote.video.srcObject = null; - this.options.media.remote.video.pause(); - } - } - } - } - /** Helper function to enable/disable media tracks. */ - enableSenderTracks(enable) { - if (!this.session) { - throw new Error("Session does not exist."); - } - const sessionDescriptionHandler = this.session.sessionDescriptionHandler; - if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); - } - const peerConnection = sessionDescriptionHandler.peerConnection; - if (!peerConnection) { - throw new Error("Peer connection closed."); - } - peerConnection.getSenders().forEach((sender) => { - if (sender.track) { - sender.track.enabled = enable; - } - }); - } - /** - * Setup session delegate and state change handler. - * @param session - Session to setup - * @param referralInviterOptions - Options for any Inviter created as result of a REFER. - */ - initSession(session, referralInviterOptions) { - // Set session - this.session = session; - // Call session created callback - if (this.delegate && this.delegate.onCallCreated) { - this.delegate.onCallCreated(); - } - // Setup session state change handler - this.session.stateChange.addListener((state) => { - if (this.session !== session) { - return; // if our session has changed, just return - } - this.logger.log(`[${this.id}] session state changed to ${state}`); - switch (state) { - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: - this.setupLocalMedia(); - this.setupRemoteMedia(); - if (this.delegate && this.delegate.onCallAnswered) { - this.delegate.onCallAnswered(); - } - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: - // fall through - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: - this.session = undefined; - this.cleanupMedia(); - if (this.delegate && this.delegate.onCallHangup) { - this.delegate.onCallHangup(); - } - break; - default: - throw new Error("Unknown session state."); - } - }); - // Setup delegate - this.session.delegate = { - onInfo: (info) => { - // As RFC 6086 states, sending DTMF via INFO is not standardized... - // - // Companies have been using INFO messages in order to transport - // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are - // proprietary and have not been standardized. - // https://tools.ietf.org/html/rfc6086#section-2 - // - // It is however widely supported based on this draft: - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 - var _a; - // FIXME: TODO: We should reject correctly... - // - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - // https://tools.ietf.org/html/rfc6086#section-4.2.2 - // No delegate - if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) { - info.reject(); - return; - } - // Invalid content type - const contentType = info.request.getHeader("content-type"); - if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) { - info.reject(); - return; - } - // Invalid body - const body = info.request.body.split("\r\n", 2); - if (body.length !== 2) { - info.reject(); - return; - } - // Invalid tone - let tone; - const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; - if (toneRegExp.test(body[0])) { - tone = body[0].replace(toneRegExp, "$2"); - } - if (!tone) { - info.reject(); - return; - } - // Invalid duration - let duration; - const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - if (durationRegExp.test(body[1])) { - duration = parseInt(body[1].replace(durationRegExp, "$2"), 10); - } - if (!duration) { - info.reject(); - return; - } - info - .accept() - .then(() => { - if (this.delegate && this.delegate.onCallDTMFReceived) { - if (!tone || !duration) { - throw new Error("Tone or duration undefined."); - } - this.delegate.onCallDTMFReceived(tone, duration); - } - }) - .catch((error) => { - this.logger.error(error.message); - }); - }, - onRefer: (referral) => { - referral - .accept() - .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) - .catch((error) => { - this.logger.error(error.message); - }); - } - }; - } - /** Helper function to init send then send invite. */ - sendInvite(inviter, inviterOptions, inviterInviteOptions) { - // Initialize our session - this.initSession(inviter, inviterOptions); - // Send the INVITE - return inviter.invite(inviterInviteOptions).then(() => { - this.logger.log(`[${this.id}] sent INVITE`); - }); - } - /** - * Puts Session on hold. - * @param hold - Hold on if true, off if false. - */ - setHold(hold) { - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - // Just resolve if we are already in correct state - if (this.held === hold) { - return Promise.resolve(); - } - const sessionDescriptionHandler = this.session.sessionDescriptionHandler; - if (!(sessionDescriptionHandler instanceof _session_description_handler__WEBPACK_IMPORTED_MODULE_2__["SessionDescriptionHandler"])) { - throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); - } - const options = { - requestDelegate: { - onAccept: () => { - this.held = hold; - if (this.delegate && this.delegate.onCallHold) { - this.delegate.onCallHold(this.held); - } - }, - onReject: () => { - this.logger.warn(`[${this.id}] re-invite request was rejected`); - if (this.delegate && this.delegate.onCallHold) { - this.delegate.onCallHold(this.held); - } - } - } - }; - // Use hold modifier to produce the appropriate SDP offer to place call on hold - options.sessionDescriptionHandlerModifiers = hold ? [_modifiers__WEBPACK_IMPORTED_MODULE_1__["holdModifier"]] : []; - // Send re-INVITE - return this.session - .invite(options) - .then(() => { - this.enableSenderTracks(!hold); // mute/unmute - }) - .catch((error) => { - if (error instanceof _api__WEBPACK_IMPORTED_MODULE_0__["RequestPendingError"]) { - this.logger.error(`[${this.id}] A hold request is already in progress.`); - } - throw error; - }); - } - /** - * Puts Session on mute. - * @param mute - Mute on if true, off if false. - */ - setMute(mute) { - if (!this.session) { - this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`); - return; - } - if (this.session.state !== _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established) { - this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`); - return; - } - this.enableSenderTracks(!mute); - } - /** Helper function to attach local media to html elements. */ - setupLocalMedia() { - var _a, _b; - if (!this.session) { - throw new Error("Session does not exist."); - } - const mediaElement = (_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.local) === null || _b === void 0 ? void 0 : _b.video; - if (mediaElement) { - const localStream = this.localMediaStream; - if (!localStream) { - throw new Error("Local media stream undefiend."); - } - mediaElement.srcObject = localStream; - mediaElement.volume = 0; - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play local media`); - this.logger.error(error.message); - }); - } - } - /** Helper function to attach remote media to html elements. */ - setupRemoteMedia() { - var _a, _b, _c, _d; - if (!this.session) { - throw new Error("Session does not exist."); - } - const mediaElement = ((_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.remote) === null || _b === void 0 ? void 0 : _b.video) || ((_d = (_c = this.options.media) === null || _c === void 0 ? void 0 : _c.remote) === null || _d === void 0 ? void 0 : _d.audio); - if (mediaElement) { - const remoteStream = this.remoteMediaStream; - if (!remoteStream) { - throw new Error("Remote media stream undefiend."); - } - mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action - mediaElement.srcObject = remoteStream; - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play remote media`); - this.logger.error(error.message); - }); - remoteStream.onaddtrack = () => { - this.logger.log(`[${this.id}] Remote media onaddtrack`); - mediaElement.load(); // Safari hack, as it doesn't work otheriwse - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play remote media`); - this.logger.error(error.message); - }); - }; - } - } - /** - * End a session. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when Session is terminated. - */ - terminate() { - this.logger.log(`[${this.id}] Terminating...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - switch (this.session.state) { - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Initial: - if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { - return this.session.cancel().then(() => { - this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`); - }); - } - else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { - return this.session.reject().then(() => { - this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); - }); - } - else { - throw new Error("Unknown session type."); - } - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Establishing: - if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Inviter"]) { - return this.session.cancel().then(() => { - this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`); - }); - } - else if (this.session instanceof _api__WEBPACK_IMPORTED_MODULE_0__["Invitation"]) { - return this.session.reject().then(() => { - this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); - }); - } - else { - throw new Error("Unknown session type."); - } - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Established: - return this.session.bye().then(() => { - this.logger.log(`[${this.id}] Session ended (sent BYE)`); - }); - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminating: - break; - case _api__WEBPACK_IMPORTED_MODULE_0__["SessionState"].Terminated: - break; - default: - throw new Error("Unknown state"); - } - this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`); - return Promise.resolve(); - } -} - - -/***/ }), -/* 179 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 180 */ -/***/ (function(module, exports) { - - - -/***/ }) -/******/ ]); -}); \ No newline at end of file diff --git a/dist/sip.min.js b/dist/sip.min.js deleted file mode 100644 index de47189e9..000000000 --- a/dist/sip.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SIP=t():e.SIP=t()}(this,(function(){return function(e){var t={};function s(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,s),i.l=!0,i.exports}return s.m=e,s.c=t,s.d=function(e,t,r){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(s.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)s.d(r,i,function(t){return e[t]}.bind(null,i));return r},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=176)}([function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(r||(r={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(r||(r={}))},function(e,t,s){"use strict";s.r(t);var r=s(62);for(var i in r)"default"!==i&&function(e){s.d(t,e,(function(){return r[e]}))}(i);var n=s(51);s.d(t,"Exception",(function(){return n.a})),s.d(t,"TransactionStateError",(function(){return n.b})),s.d(t,"TransportError",(function(){return n.c}));var o=s(124);s.d(t,"Levels",(function(){return o.a})),s.d(t,"LoggerFactory",(function(){return o.c})),s.d(t,"Logger",(function(){return o.b}));var a=s(3);for(var i in a)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(i);var c=s(52);for(var i in c)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return c[e]}))}(i);var d=s(63);for(var i in d)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return d[e]}))}(i);var h=s(9);for(var i in h)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(i);var u=s(128);for(var i in u)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return u[e]}))}(i);var l=s(89);s.d(t,"ByeUserAgentClient",(function(){return l.a})),s.d(t,"ByeUserAgentServer",(function(){return l.b})),s.d(t,"CancelUserAgentClient",(function(){return l.c})),s.d(t,"InfoUserAgentClient",(function(){return l.d})),s.d(t,"InfoUserAgentServer",(function(){return l.e})),s.d(t,"InviteUserAgentClient",(function(){return l.f})),s.d(t,"InviteUserAgentServer",(function(){return l.g})),s.d(t,"MessageUserAgentClient",(function(){return l.h})),s.d(t,"MessageUserAgentServer",(function(){return l.i})),s.d(t,"NotifyUserAgentClient",(function(){return l.j})),s.d(t,"NotifyUserAgentServer",(function(){return l.k})),s.d(t,"PublishUserAgentClient",(function(){return l.n})),s.d(t,"PrackUserAgentClient",(function(){return l.l})),s.d(t,"PrackUserAgentServer",(function(){return l.m})),s.d(t,"ReInviteUserAgentClient",(function(){return l.o})),s.d(t,"ReInviteUserAgentServer",(function(){return l.p})),s.d(t,"ReSubscribeUserAgentClient",(function(){return l.q})),s.d(t,"ReSubscribeUserAgentServer",(function(){return l.r})),s.d(t,"ReferUserAgentClient",(function(){return l.s})),s.d(t,"ReferUserAgentServer",(function(){return l.t})),s.d(t,"RegisterUserAgentClient",(function(){return l.u})),s.d(t,"RegisterUserAgentServer",(function(){return l.v})),s.d(t,"SubscribeUserAgentClient",(function(){return l.w})),s.d(t,"SubscribeUserAgentServer",(function(){return l.x})),s.d(t,"UserAgentClient",(function(){return l.y})),s.d(t,"UserAgentServer",(function(){return l.z}));var g=s(11);s.d(t,"Timers",(function(){return g.a}));var p=s(132);for(var i in p)["Exception","TransactionStateError","TransportError","Levels","LoggerFactory","Logger","ByeUserAgentClient","ByeUserAgentServer","CancelUserAgentClient","InfoUserAgentClient","InfoUserAgentServer","InviteUserAgentClient","InviteUserAgentServer","MessageUserAgentClient","MessageUserAgentServer","NotifyUserAgentClient","NotifyUserAgentServer","PublishUserAgentClient","PrackUserAgentClient","PrackUserAgentServer","ReInviteUserAgentClient","ReInviteUserAgentServer","ReSubscribeUserAgentClient","ReSubscribeUserAgentServer","ReferUserAgentClient","ReferUserAgentServer","RegisterUserAgentClient","RegisterUserAgentServer","SubscribeUserAgentClient","SubscribeUserAgentServer","UserAgentClient","UserAgentServer","Timers","default"].indexOf(i)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(i)},function(e,t,s){"use strict";s.r(t);var r=s(33);s.d(t,"Grammar",(function(){return r.a})),s.d(t,"NameAddrHeader",(function(){return r.b})),s.d(t,"Parameters",(function(){return r.c})),s.d(t,"URI",(function(){return r.d}));var i=s(105);for(var n in i)["Grammar","NameAddrHeader","Parameters","URI","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(84);s.d(t,"fromBodyLegacy",(function(){return o.a})),s.d(t,"isBody",(function(){return o.c})),s.d(t,"getBody",(function(){return o.b}));var a=s(175);s.d(t,"DigestAuthentication",(function(){return a.a}));var c=s(40);s.d(t,"IncomingMessage",(function(){return c.a}));var d=s(35);s.d(t,"IncomingRequestMessage",(function(){return d.a}));var h=s(119);for(var n in h)["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(n);var u=s(27);s.d(t,"IncomingResponseMessage",(function(){return u.a}));var l=s(120);for(var n in l)["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(n);var g=s(46);s.d(t,"OutgoingRequestMessage",(function(){return g.a}));var p=s(121);for(var n in p)["Grammar","NameAddrHeader","Parameters","URI","fromBodyLegacy","isBody","getBody","DigestAuthentication","IncomingMessage","IncomingRequestMessage","IncomingResponseMessage","OutgoingRequestMessage","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(n);var f=s(85);s.d(t,"constructOutgoingResponse",(function(){return f.a}));var m=s(122);s.d(t,"Parser",(function(){return m.a}))},function(e,t,s){"use strict";var r,i;s.d(t,"a",(function(){return r})),s.d(t,"b",(function(){return i})),function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(r||(r={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(i||(i={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(r||(r={}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return i})),s.d(t,"b",(function(){return n})),s.d(t,"d",(function(){return o})),s.d(t,"c",(function(){return a})),s.d(t,"e",(function(){return c}));const r={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function i(e,t=32){let s="";for(let r=0;r{this.transaction&&this.transaction.state===n.a.Proceeding&&new a(o.a,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let r,i;if(401===s?(r=e.parseHeader("www-authenticate"),i="authorization"):(r=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!r)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==r.stale))return this.logger.warn(s+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,r))return!0;this.challenged=!0,r.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new i.a;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new i.a;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===n.a.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));const r=500,i={T1:r,T2:4e3,T4:5e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4}},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(r||(r={}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return d}));var r=s(28),i=s(85),n=s(6),o=s(17),a=s(0),c=s(20);class d{constructor(e,t,s,r){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=r,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:Object(n.d)(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new r.a(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new r.a(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new r.a(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError("Invalid statusCode: "+s);const i=new Array;return e.forEach(e=>i.push("Contact: "+e.toString())),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new r.a(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: "+t);return this.reply(e)}trying(e){if(!this.tryingable)throw new r.a(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding||this.transaction.state===a.a.Accepted;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying||this.transaction.state===a.a.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying||this.transaction.state===a.a.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying||this.transaction.state===a.a.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof o.a)return this.transaction.state===a.a.Proceeding;if(this.transaction instanceof c.a)return this.transaction.state===a.a.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=Object(i.a)(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===a.a.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(r||(r={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(r||(r={}))},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.Started="Started",e.Stopped="Stopped"}(r||(r={}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(3),i=s(11),n=s(41),o=s(0);class a extends n.a{constructor(e,t,s){super(e,t,s,o.a.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case o.a.Proceeding:if(e.method===r.C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case o.a.Accepted:if(e.method===r.C.INVITE)return;break;case o.a.Completed:if(e.method===r.C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===r.C.ACK)return void this.stateTransition(o.a.Confirmed);break;case o.a.Confirmed:case o.a.Terminated:if(e.method===r.C.INVITE||e.method===r.C.ACK)return;break;default:throw new Error("Invalid state "+this.state)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error("Invalid status code "+e);switch(this.state){case o.a.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(o.a.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(o.a.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case o.a.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case o.a.Completed:case o.a.Confirmed:case o.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===o.a.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case o.a.Proceeding:t();break;case o.a.Accepted:case o.a.Completed:this.state!==o.a.Proceeding&&t();break;case o.a.Confirmed:this.state!==o.a.Completed&&t();break;case o.a.Terminated:this.state!==o.a.Accepted&&this.state!==o.a.Completed&&this.state!==o.a.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===o.a.Accepted&&(this.L=setTimeout(()=>this.timerL(),i.a.TIMER_L)),e===o.a.Completed&&(this.H=setTimeout(()=>this.timerH(),i.a.TIMER_H)),e===o.a.Confirmed&&(this.I=setTimeout(()=>this.timerI(),i.a.TIMER_I)),e===o.a.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},i.a.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===o.a.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(o.a.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(o.a.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===o.a.Accepted&&this.stateTransition(o.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(11),i=s(43),n=s(0);class o extends i.a{constructor(e,t,s){super(e,t,s,n.a.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),r.a.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case n.a.Trying:if(t>=100&&t<=199)return this.stateTransition(n.a.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(n.a.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(n.a.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Completed:case n.a.Terminated:return;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(n.a.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case n.a.Trying:s();break;case n.a.Proceeding:this.state!==n.a.Trying&&s();break;case n.a.Completed:this.state!==n.a.Trying&&this.state!==n.a.Proceeding&&s();break;case n.a.Terminated:this.state!==n.a.Trying&&this.state!==n.a.Proceeding&&this.state!==n.a.Completed&&(t||s());break;default:s()}e===n.a.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),r.a.TIMER_K)),e===n.a.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==n.a.Trying&&this.state!==n.a.Proceeding||(this.onRequestTimeout(),this.stateTransition(n.a.Terminated))}timerK(){this.state===n.a.Completed&&this.stateTransition(n.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(11),i=s(41),n=s(0);class o extends i.a{constructor(e,t,s){super(e,t,s,n.a.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case n.a.Trying:break;case n.a.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case n.a.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case n.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}}receiveResponse(e,t){if(e<100||e>699)throw new Error("Invalid status code "+e);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case n.a.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(n.a.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(n.a.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case n.a.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(n.a.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case n.a.Completed:return;case n.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(n.a.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case n.a.Trying:s();break;case n.a.Proceeding:this.state!==n.a.Trying&&s();break;case n.a.Completed:this.state!==n.a.Trying&&this.state!==n.a.Proceeding&&s();break;case n.a.Terminated:this.state!==n.a.Proceeding&&this.state!==n.a.Completed&&(t||s());break;default:s()}e===n.a.Completed&&(this.J=setTimeout(()=>this.timerJ(),r.a.TIMER_J)),e===n.a.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===n.a.Completed&&this.stateTransition(n.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(3);const i=[r.C.ACK,r.C.BYE,r.C.CANCEL,r.C.INFO,r.C.INVITE,r.C.MESSAGE,r.C.NOTIFY,r.C.OPTIONS,r.C.PRACK,r.C.REFER,r.C.REGISTER,r.C.SUBSCRIBE]},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),s.d(t,"b",(function(){return i})),function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(r||(r={}));const i={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(39);class i extends r.a{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new i(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(11),i=s(43),n=s(0);class o extends i.a{constructor(e,t,s){super(e,t,s,n.a.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),r.a.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code "+t);switch(this.state){case n.a.Calling:if(t>=100&&t<=199)return this.stateTransition(n.a.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(n.a.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(n.a.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(n.a.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(n.a.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case n.a.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case n.a.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case n.a.Terminated:break;default:throw new Error("Invalid state "+this.state)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(n.a.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,r=this.request.cseq,i=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${i}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${r} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case n.a.Calling:s();break;case n.a.Proceeding:this.state!==n.a.Calling&&s();break;case n.a.Accepted:case n.a.Completed:this.state!==n.a.Calling&&this.state!==n.a.Proceeding&&s();break;case n.a.Terminated:this.state!==n.a.Calling&&this.state!==n.a.Accepted&&this.state!==n.a.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),n.a.Proceeding,e===n.a.Completed&&(this.D=setTimeout(()=>this.timerD(),r.a.TIMER_D)),e===n.a.Accepted&&(this.M=setTimeout(()=>this.timerM(),r.a.TIMER_M)),e===n.a.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===n.a.Calling&&(this.onRequestTimeout(),this.stateTransition(n.a.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===n.a.Completed&&this.stateTransition(n.a.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===n.a.Accepted&&this.stateTransition(n.a.Terminated)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(23),i=s(3);class n{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof r.a))throw new Error("Contact not instance of NameAddrHeader.");const n=i.uri,o=e.cseq,a=e.callId,c=e.fromTag,d=t.toTag;if(!a)throw new Error("Call id undefined.");if(!c)throw new Error("From tag undefined.");if(!d)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const h=e.from.uri,u=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+c+d,early:t.statusCode<200,callId:a,localTag:c,remoteTag:d,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:h,remoteURI:u,remoteTarget:n,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),n=e.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof r.a))throw new Error("Contact not instance of NameAddrHeader.");const o=n.uri,a=e.cseq,c=e.callId,d=t,h=e.fromTag,u=e.from.uri;return{id:c+d+h,early:s,callId:c,localTag:d,remoteTag:h,localSequenceNumber:void 0,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:u,remoteTarget:o,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==i.C.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,r=this.remoteTag,i=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,d=this.routeSet,h=t&&t.extraHeaders,u=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,i,s,{callId:o,cseq:a,fromTag:n,toTag:r,routeSet:d},h,u)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===i.C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(40);class i extends r.a{constructor(){super()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Transaction state error.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(r.a,i,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return g}));var r=s(2),i=s(28),n=s(11),o=s(6),a=s(58),c=s(90),d=s(59),h=s(34),u=s(1),l=s(22);class g extends h.a{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const n=s.getHeader("supported");if(n&&n.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(u.a.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===u.a.Initial&&(t.reject({statusCode:487}),this.stateTransition(u.a.Terminated))},e)}const o=this.request.getHeader("P-Asserted-Identity");o&&(this._assertedIdentity=r.Grammar.nameAddrHeaderParse(o)),this._contact=this.userAgent.contact.toString();const a=s.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case u.a.Initial:case u.a.Establishing:return this.reject().then(()=>super.dispose());case u.a.Established:case u.a.Terminating:case u.a.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==u.a.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(u.a.Establishing),this.sendAccept().then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(u.a.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==u.a.Initial){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===l.a.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==u.a.Initial&&this.state!==u.a.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:Object(o.b)(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const n=e.body?Object(r.fromBodyLegacy)(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:n}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n}),this.stateTransition(u.a.Terminated),Promise.resolve()}_onCancel(e){this.logger.log("Invitation._onCancel"),this.state===u.a.Initial||this.state===u.a.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(u.a.Terminated)):this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Object(r.getBody)(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case r.SignalingState.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case r.SignalingState.Stable:return this.setAnswer(t,s).then(()=>{});case r.SignalingState.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case r.SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case r.SignalingState.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof a.a?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof c.a?this.logger.error("A session description handler occurred while sending response"):e instanceof d.a?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof i.a&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===u.a.Initial||this.state===u.a.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(u.a.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(u.a.Terminated)}sendAccept(){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,e)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),n=e.body?Object(r.fromBodyLegacy)(e.body):void 0;if(183===t&&!n)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:r,extraHeaders:i,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();let o;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(o=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:r,extraHeaders:i,body:o}))).then(t=>{let c,h;this._dialog=t.session,t.session.delegate={onPrack:s=>{c=s,clearTimeout(u),clearTimeout(p),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(c).then(s=>{try{h=c.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:c,prackResponse:h,progressResponse:t})}catch(e){a(e)}}).catch(e=>a(e)))}};const u=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(p),this.reject({statusCode:504}).then(()=>a(new d.a)).catch(e=>a(e)))},64*n.a.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:r,extraHeaders:i,body:o})}catch(e){return this.waitingForPrack=!1,void a(e)}p=setTimeout(l,g*=2)};let g=n.a.T1,p=setTimeout(l,g)}).catch(e=>{this.waitingForPrack=!1,a(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new d.a),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}getDescription(e,t){var s,r;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const i=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(r=this.sessionDescriptionHandlerConfiguration)||void 0===r?void 0:r.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(i,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const r=s[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,i,n)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:r},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);case"have-local-offer":case"have-local-pranswer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],n=e=>{const n=e.kind;if("audio"!==n&&"video"!==n)throw new Error(`Unknown new track kind ${n}.`);const o=t.getSenders().find(e=>e.track&&e.track.kind===n);o?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${n} track`),e()}).then(()=>o.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===n);t&&(t.stop(),s.removeTrack(t),r.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),r.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${n} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${n} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${n} track`),e}s.addTrack(e),r.dispatchAddTrackEvent(s,e)}))},o=e.getAudioTracks();o.length&&n(o[0]);const a=e.getVideoTracks();return a.length&&n(a[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;case"have-local-pranswer":case"have-remote-offer":case"have-remote-pranswer":case"closed":default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),r.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),r.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),r.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),r.dispatchAddTrackEvent(t,e))}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const r=e.connectionState;this.logger.debug("SessionDescriptionHandler.onconnectionstatechange "+r),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const r=e.iceConnectionState;this.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange "+r),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const r=e.iceGatheringState;this.logger.debug("SessionDescriptionHandler.onicegatheringstatechange "+r),"complete"===r&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const r=e.signalingState;this.logger.debug("SessionDescriptionHandler.onsignalingstatechange "+r),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.onstatsended=e=>{var t;this.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onstatsended)&&this._peerConnectionDelegate.onstatsended(e)},e.ontrack=e=>{var t;const s=e.track.kind,r=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${r}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}},function(e,t,s){"use strict";var r=s(50);s.d(t,"a",(function(){return r.a}));var i=s(23);s.d(t,"b",(function(){return i.a}));var n=s(39);s.d(t,"c",(function(){return n.a}));var o=s(45);s.d(t,"d",(function(){return o.a}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return f}));var r=s(2),i=s(6),n=s(21),o=s(66),a=s(18),c=s(47),d=s(58),h=s(67),u=s(44),l=s(29),g=s(79),p=s(1);class f{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=p.a.Initial,this.delegate=t.delegate,this._stateEventEmitter=new a.a,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case p.a.Initial:case p.a.Establishing:break;case p.a.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case p.a.Terminating:case p.a.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case p.a.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case p.a.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case p.a.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case p.a.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case p.a.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error("Invalid session state "+this.state))}info(e={}){if(this.state!==p.a.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==p.a.Established)return Promise.reject(new Error("Invalid session state "+this.state));if(this.pendingReinvite)return Promise.reject(new c.a("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=Object(r.getBody)(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(p.a.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,r).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===p.a.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(p.a.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,r).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==p.a.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(p.a.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==p.a.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+n.a.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==p.a.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==p.a.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error("Invalid session state "+this.state))}const s=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return r.extraHeaders=r.extraHeaders?r.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,s,r)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case r.SessionState.Initial:case r.SessionState.Early:throw new Error("Invalid dialog state "+s.sessionState);case r.SessionState.AckWait:return this.stateTransition(p.a.Terminating),new Promise(r=>{s.delegate={onAck:()=>{const i=s.bye(e,t);return this.stateTransition(p.a.Terminated),r(i),Promise.resolve()},onAckTimeout:()=>{const i=s.bye(e,t);this.stateTransition(p.a.Terminated),r(i)}}});case r.SessionState.Confirmed:{const r=s.bye(e,t);return this.stateTransition(p.a.Terminated),Promise.resolve(r)}case r.SessionState.Terminated:throw new Error("Invalid dialog state "+s.sessionState);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:r})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==p.a.Established&&this.state!==p.a.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};switch(this.pendingReinviteAck=!1,t.signalingState){case r.SignalingState.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated),Promise.resolve()}case r.SignalingState.Stable:{const i=Object(r.getBody)(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(p.a.Terminated)}):Promise.resolve()}case r.SignalingState.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated),Promise.resolve()}case r.SignalingState.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(p.a.Terminated),Promise.resolve()}case r.SignalingState.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===p.a.Established){if(this.delegate&&this.delegate.onBye){const t=new o.a(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(p.a.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===p.a.Established)if(this.delegate&&this.delegate.onInfo){const t=new h.a(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==p.a.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=r.Grammar.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const r=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,200)}).catch(s=>{if(this.logger.error(s.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState!==r.SignalingState.Stable)this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(s=>{this.logger.error(s.message),this.logger.error("Failed to rollback offer on re-INVITE request");const r=e.reject({statusCode:488});if(this.state!==p.a.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(p.a.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,488)});else{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===p.a.Established)if(this.delegate&&this.delegate.onMessage){const t=new u.a(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===p.a.Established)if(this.onNotify){const t=new l.a(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new l.a(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===p.a.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==p.a.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new g.a(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=Object(r.getBody)(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case r.SignalingState.Initial:return this.getOffer(e);case r.SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case r.SignalingState.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case r.SignalingState.Stable:return this.state!==p.a.Established?Promise.resolve(void 0):this.getOffer(e);case r.SignalingState.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>Object(r.fromBodyLegacy)(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new d.a)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,r,i).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,n=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new d.a)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,i,n).then(()=>s.getDescription(i,n)).then(e=>Object(r.fromBodyLegacy)(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case p.a.Initial:e!==p.a.Establishing&&e!==p.a.Established&&e!==p.a.Terminating&&e!==p.a.Terminated&&t();break;case p.a.Establishing:e!==p.a.Established&&e!==p.a.Terminating&&e!==p.a.Terminated&&t();break;case p.a.Established:e!==p.a.Terminating&&e!==p.a.Terminated&&t();break;case p.a.Terminating:e!==p.a.Terminated&&t();break;case p.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===p.a.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let r=Object(i.b)(e);return!r&&t&&(r=t),"SIP;cause="+s+';text="'+r+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof r.URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),i=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${r}?Replaces=${encodeURIComponent(`${i};to-tag=${n};from-tag=${o}`)}>`}return t}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(40);class i extends r.a{constructor(){super()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return c}));var r=s(2),i=s(6),n=s(34),o=s(1),a=s(22);class c extends n.a{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=Object(i.d)(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const n=Object.assign({},s);n.params=Object.assign({},s.params);const o=s.anonymous||!1,c=e.contact.toString({anonymous:o,outbound:o?!e.contact.tempGruu:!e.contact.pubGruu});o&&e.configuration.uri&&(n.params.fromDisplayName="Anonymous",n.params.fromUri="sip:anonymous@anonymous.invalid");let d=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(d="string"==typeof n.params.fromUri?r.Grammar.URIParse(n.params.fromUri):n.params.fromUri),!d)throw new TypeError("Invalid from URI: "+n.params.fromUri);let h=t;if(n.params.toUri&&(h="string"==typeof n.params.toUri?r.Grammar.URIParse(n.params.toUri):n.params.toUri),!h)throw new TypeError("Invalid to URI: "+n.params.toUri);const u=Object.assign({},n.params);u.fromTag=this.fromTag;const l=(n.extraHeaders||[]).slice();o&&e.configuration.uri&&(l.push("P-Preferred-Identity: "+e.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+c),l.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===a.a.Required&&l.push("Require: 100rel"),e.configuration.sipExtensionReplaces===a.a.Required&&l.push("Require: replaces"),n.extraHeaders=l;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(r.C.INVITE,t,d,h,u,l,void 0),this._contact=c,this._referralInviterOptions=n,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case o.a.Initial:case o.a.Establishing:return this.cancel().then(()=>super.dispose());case o.a.Established:case o.a.Terminating:case o.a.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==o.a.Initial&&this.state!==o.a.Establishing){const e=new Error("Invalid session state "+this.state);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(o.a.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e){return"SIP;cause="+e+';text="'+(Object(i.b)(e)||t)+'"'}}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(o.a.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==o.a.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(o.a.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(o.a.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.stateTransition(o.a.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(o.a.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof n.a))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==o.a.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error("Invalid session state "+this.state));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=r.Grammar.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case r.SignalingState.Initial:case r.SignalingState.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(o.a.Terminated),Promise.reject(new Error("Bad Media Description"));case r.SignalingState.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(o.a.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(o.a.Terminated),t})}case r.SignalingState.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(o.a.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(o.a.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(o.a.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,r).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(o.a.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(o.a.Terminated),t})}case r.SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==o.a.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error("Invalid session state "+this.state));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=r.Grammar.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const n=s.getHeader("require"),a=s.getHeader("rseq"),c=!!(n&&n.includes("100rel")&&a?Number(a):void 0),d=[];switch(c&&d.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case r.SignalingState.Initial:return c&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:d})),Promise.resolve();case r.SignalingState.HaveLocalOffer:return c&&e.prack({extraHeaders:d}),Promise.resolve();case r.SignalingState.HaveRemoteOffer:if(!c)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:d,body:s})}).catch(e=>{throw this.stateTransition(o.a.Terminated),e})}case r.SignalingState.Stable:if(c&&e.prack({extraHeaders:d}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(o.a.Terminated),e})}return Promise.resolve();case r.SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===o.a.Establishing||this.state===o.a.Terminating?this.stateTransition(o.a.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===o.a.Establishing||this.state===o.a.Terminating?this.stateTransition(o.a.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===o.a.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"An error occurred during state transition.")}}},function(e,t,s){"use strict";var r=s(58);s.d(t,"a",(function(){return r.a}));var i=s(47);s.d(t,"b",(function(){return i.a}));var n=s(90);s.d(t,"c",(function(){return n.a}));var o=s(59);s.d(t,"d",(function(){return o.a}));var a=s(37);s.d(t,"e",(function(){return a.a}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!!e&&!!this.parameters.hasOwnProperty(e.toLowerCase())}deleteParam(e){if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(50),i=s(6);class n{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=Object(i.c)(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[Object(i.c)(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Object(i.c)(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[Object(i.c)(e)]}parseHeader(e,t=0){if(e=Object(i.c)(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const s=this.headers[e][t],n=s.raw;if(s.parsed)return s.parsed;const o=r.a.parse(n,e.replace(/-/g,"_"));return-1===o?void this.headers[e].splice(t,1):(s.parsed=o,o)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[Object(i.c)(e)]=[{raw:t}]}toString(){return this.data}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(42);class i extends r.a{constructor(e,t,s,r,i){super(t,s,e.viaBranch,r,i),this._request=e,this.user=s}get request(){return this._request}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(60);class i{constructor(e,t,s,r,i){this._transport=e,this._user=t,this._id=s,this._state=r,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof r.a)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new r.a(e.message):new r.a,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(42);class i extends r.a{constructor(e,t,s,r,n){super(t,s,i.makeId(e),r,n),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(39);class i extends r.a{constructor(e,t,s,r,i,n){if(super(i),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');e=e||"sip";for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:r},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:r}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new i(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),r=s.length;let i="";for(let e=0;e{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=["Retry-After: "+(Math.floor(10*Math.random())+1)];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==d.b.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===r.C.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof i.a))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case r.C.BYE:{const t=new f.a(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case r.C.INFO:{const t=new v.a(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info :"]})}break;case r.C.INVITE:{const t=new I.a(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case r.C.MESSAGE:{const t=new w.a(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case r.C.NOTIFY:{const t=new T.a(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case r.C.PRACK:{const t=new R.a(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case r.C.REFER:{const t=new $.a(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof l.a)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),r=t&&t.includes("100rel")&&s?Number(s):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0}signalingStateRollback(){this._signalingState!==d.b.HaveLocalOffer&&this.signalingState!==d.b.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=d.b.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Object(n.b)(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===d.b.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof o.a)switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.HaveRemoteOffer:case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof a.a)switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.HaveRemoteOffer:case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof c.a)switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:break;case d.b.HaveRemoteOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Object(n.c)(e))switch(this._signalingState){case d.b.Initial:case d.b.Stable:this._signalingState=d.b.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case d.b.HaveLocalOffer:break;case d.b.HaveRemoteOffer:this._signalingState=d.b.Stable,this._answer=t;break;case d.b.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof u.a){const e=this.initialTransaction;let t=h.a.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,h.a.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const r=()=>{e.state===g.a.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(r)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof u.a){const e=this.reinviteUserAgentServer.transaction;let t=h.a.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,h.a.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const r=()=>{e.state===g.a.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(r)}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return v}));var r=s(2),i=s(91),n=s(15),o=s(6),a=s(100),c=s(86),d=s(83),h=s(18),u=s(31),l=s(36),g=s(44),p=s(29),f=s(22),m=s(16);class v{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=m.a.Stopped,this.unloadListener=()=>{this.stop()},this._stateEventEmitter=new h.a,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},v.defaultOptions()),{sipjsId:Object(o.a)(5)}),{uri:new r.URI("sip","anonymous."+Object(o.a)(6),"anonymous.invalid")}),{viaHost:Object(o.a)(12)+".invalid"}),v.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new i.a,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=n.a.error;break;case"warn":this.loggerFactory.level=n.a.warn;break;case"log":this.loggerFactory.level=n.a.log;break;case"debug":this.loggerFactory.level=n.a.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("\xb7 "+e+": "+t);break;case"authorizationPassword":this.logger.log("\xb7 "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("\xb7 "+e+": "+t.name);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,r=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==r&&(this.options.reconnectionDelay=r),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._userAgentCore=this.initCore(),this.options.autoStart&&this.start()}static makeURI(e){return r.Grammar.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,hackWssInTransport:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sessionDescriptionHandlerFactory:Object(a.a)(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:f.a.Unsupported,sipExtensionReplaces:f.a.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:c.a,transportOptions:{},uri:new r.URI("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/"+d.a,viaHost:""}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===m.a.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){if(this.state===m.a.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting "+this.configuration.uri),this.transitionState(m.a.Started),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this.transport.connect()}async stop(){if(this.state===m.a.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log("Stopping "+this.configuration.uri),this.transitionState(m.a.Stopped),this.options.autoStop){const e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)}const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),r=Object.assign({},this._subscriptions),i=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in r)r[e]&&await r[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await i.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose()}_makeInviter(e,t){return new l.a(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=Object(o.a)(8),t=this.options.hackWssInTransport?"wss":"ws";return{pubGruu:void 0,tempGruu:void 0,uri:new r.URI("sip",e,this.options.viaHost,void 0,{transport:t}),toString:(e={})=>{const s=e.anonymous||!1,r=e.outbound||!1;let i="<";return i+=s?this.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport="+t:this.contact.pubGruu||this.contact.uri,r&&(i+=";ob"),i+=">",i}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===f.a.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===f.a.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>f.b[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new r.DigestAuthentication(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport},i={onInvite:e=>{var t;const s=new u.a(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==f.a.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const r=t.replaces_to_tag;if("string"!=typeof r)throw new Error("Type of to tag is not string");const i=t.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const n=e+r+i,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+i]||this._sessions[e+r]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new g.a(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new p.a(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}};return new r.UserAgentCore(s,i)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==m.a.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==m.a.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=r.Parser.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===m.a.Stopped&&t instanceof r.IncomingRequestMessage)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof r.IncomingRequestMessage){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=Object(o.e)(t.body),r=t.getHeader("content-length");if(r&&e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=Object(o.e)(t.body),r=t.getHeader("content-length");if(r&&e{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case m.a.Started:e!==m.a.Stopped&&s();break;case m.a.Stopped:e!==m.a.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(23),i=s(45);class n extends Error{constructor(e,t,s,r){super(),this.message=e,this.expected=t,this.found=s,this.location=r,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,n)}static buildMessage(e,t){function s(e){return e.charCodeAt(0).toString(16).toUpperCase()}function r(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(n);let s,r;if(t.sort(),t.length>0){for(s=1,r=1;s",w(">",!1),"\\",w("\\",!1),"[",w("[",!1),"]",w("]",!1),"{",w("{",!1),"}",w("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,S([["!","'"]],!1,!1),/^[*-[]/,S([["*","["]],!1,!1),/^[\]-~]/,S([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,S([["#","["]],!1,!1),/^[\0-\t]/,S([["\0","\t"]],!1,!1),/^[\x0B-\f]/,S([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,S([["\x0e","\x7f"]],!1,!1),function(){(t=t||{data:{}}).data.uri=new i.a(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new i.a(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",w("sips",!0),"sip",w("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(v().slice(0,-1))},function(){(t=t||{data:{}}).data.password=v()},function(){return(t=t||{data:{}}).data.host=v(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",v()},/^[a-zA-Z0-9_\-]/,S([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,S([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",w("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",w("25",!1),/^[0-5]/,S([["0","5"]],!1,!1),"2",w("2",!1),/^[0-4]/,S([["0","4"]],!1,!1),"1",w("1",!1),/^[1-9]/,S([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",w("transport=",!0),"udp",w("udp",!0),"tcp",w("tcp",!0),"sctp",w("sctp",!0),"tls",w("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",w("user=",!0),"phone",w("phone",!0),"ip",w("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",w("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",w("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",w("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",w("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new i.a(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",w("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},w("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",w("INVITE",!1),"ACK",w("ACK",!1),"VXACH",w("VXACH",!1),"OPTIONS",w("OPTIONS",!1),"BYE",w("BYE",!1),"CANCEL",w("CANCEL",!1),"REGISTER",w("REGISTER",!1),"SUBSCRIBE",w("SUBSCRIBE",!1),"NOTIFY",w("NOTIFY",!1),"REFER",w("REFER",!1),"PUBLISH",w("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=v(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=v()},function(){(t=t||{data:{}}).data=v()},function(){var e,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),I(";).# &;,"),I('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),I('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),I('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),I(';.." &"'),I("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),I('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I('4\\""5!7].# &;3'),I('4^""5!7_'),I('4`""5!7a'),I(';!.) &4b""5!7c'),I('%$;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x9e#0\x9b*;).\x95 &2F""6F7G.\x89 &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),I('%$;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/\x92#0\x8f*;).\x89 &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),I('2T""6T7U.\xe3 &2V""6V7W.\xd7 &2f""6f7g.\xcb &2h""6h7i.\xbf &2:""6:7;.\xb3 &2D""6D7E.\xa7 &22""6273.\x9b &28""6879.\x8f &2j""6j7k.\x83 &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),I('%$;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/\u0134#0\u0131*;).\u012b &2F""6F7G.\u011f &2J""6J7K.\u0113 &2L""6L7M.\u0107 &2X""6X7Y.\xfb &2P""6P7Q.\xef &2H""6H7I.\xe3 &2@""6@7A.\xd7 &2d""6d7e.\xcb &2R""6R7S.\xbf &2N""6N7O.\xb3 &2T""6T7U.\xa7 &2V""6V7W.\x9b &2f""6f7g.\x8f &2h""6h7i.\x83 &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),I("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),I("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),I("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),I("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),I("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),I('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),I('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),I("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),I("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),I("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),I("%;//0#;&/'$8\":~\" )(\"'#&'#"),I("%;&/0#;//'$8\":~\" )(\"'#&'#"),I("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),I('4\x7f""5!7\x80.A &4\x81""5!7\x82.5 &4\x83""5!7\x84.) &;3.# &;.'),I("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),I("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"),I(';..G &2L""6L7M.; &4\x86""5!7\x87./ &4\x83""5!7\x84.# &;3'),I('%2j""6j7k/J#4\x88""5!7\x89.5 &4\x8a""5!7\x8b.) &4\x8c""5!7\x8d/#$+")("\'#&\'#'),I("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8e$ )($'#(#'#(\"'#&'#"),I("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8f& )(&'#(%'#($'#(#'#(\"'#&'#"),I('%3\x90""5$7\x91.) &3\x92""5#7\x93/\' 8!:\x94!! )'),I('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:\x95# )(#\'#("\'#&\'#'),I("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),I('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),I('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:\x96! )'),I('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:\x97! )"),I('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:\x98# )(#\'#("\'#&\'#'),I('$4\x99""5!7\x9a/,#0)*4\x99""5!7\x9a&&&#'),I('%4$""5!7%/?#$4\x9b""5!7\x9c0)*4\x9b""5!7\x9c&/#$+")("\'#&\'#'),I('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:\x9d# )(#\'#("\'#&\'#'),I('%%;Z/\xb3#28""6879/\xa4$;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0790 &%2\x9e""6\x9e7\x9f/\xa4#;Z/\x9b$28""6879/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u06f9 &%2\x9e""6\x9e7\x9f/\x8c#;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u067a &%2\x9e""6\x9e7\x9f/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0613 &%2\x9e""6\x9e7\x9f/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u05c4 &%2\x9e""6\x9e7\x9f/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.\u058d &%2\x9e""6\x9e7\x9f/,#;[/#$+")("\'#&\'#.\u056e &%2\x9e""6\x9e7\x9f/,#;Z/#$+")("\'#&\'#.\u054f &%;Z/\x9b#2\x9e""6\x9e7\x9f/\x8c$;Z/\x83$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u04c7 &%;Z/\xaa#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x83$2\x9e""6\x9e7\x9f/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0430 &%;Z/\xb9#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x92$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2\x9e""6\x9e7\x9f/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u038a &%;Z/\xc8#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa1$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2\x9e""6\x9e7\x9f/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u02d5 &%;Z/\xd7#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0211 &%;Z/\xfe#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xd7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xb0$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x89$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2\x9e""6\x9e7\x9f/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.\u0126 &%;Z/\u011c#%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xf5$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xce$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\xa7$%28""6879/,#;Z/#$+")("\'#&\'#." &"/\x80$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2\x9e""6\x9e7\x9f/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!:\xa0! )'),I('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),I("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xa1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),I('%2\xa2""6\xa27\xa3/2#4\xa4""5!7\xa5/#$+")("\'#&\'#.\x98 &%2\xa6""6\xa67\xa7/;#4\xa8""5!7\xa9/,$;!/#$+#)(#\'#("\'#&\'#.j &%2\xaa""6\xaa7\xab/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4\xac""5!7\xad/,#;!/#$+")("\'#&\'#.# &;!'),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\xae!! )'),I('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),I(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),I('%3\xaf""5*7\xb0/a#3\xb1""5#7\xb2.G &3\xb3""5#7\xb4.; &3\xb5""5$7\xb6./ &3\xb7""5#7\xb8.# &;6/($8":\xb9"! )("\'#&\'#'),I('%3\xba""5%7\xbb/I#3\xbc""5%7\xbd./ &3\xbe""5"7\xbf.# &;6/($8":\xc0"! )("\'#&\'#'),I('%3\xc1""5\'7\xc2/1#;\x90/($8":\xc3"! )("\'#&\'#'),I('%3\xc4""5$7\xc5/1#;\xf0/($8":\xc6"! )("\'#&\'#'),I('%3\xc7""5&7\xc8/1#;T/($8":\xc9"! )("\'#&\'#'),I('%3\xca""5"7\xcb/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":\xcc" )("\'#&\'#'),I('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":\xcd""! )("\'#&\'#'),I('%$;j/�#*;j&&&#/"!&,)'),I('%$;j/�#*;j&&&#/"!&,)'),I(";k.) &;+.# &;-"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),I('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),I('%;n/A#2>""6>7?/2$;o/)$8#:\xce#"" )(#\'#("\'#&\'#'),I("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),I("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),I(";\x91.# &;r"),I("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"),I(";M.# &;t"),I("%;\x7f/E#28\"\"6879/6$;u.# &;x/'$8#:\xcf# )(#'#(\"'#&'#"),I('%;v.# &;w/J#%26""6677/,#;\x83/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I('%2\xd0""6\xd07\xd1/:#;\x80/1$;w." &"/#$+#)(#\'#("\'#&\'#'),I('%24""6475/,#;{/#$+")("\'#&\'#'),I("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),I(";*.) &;+.# &;-"),I(';+.\x8f &;-.\x89 &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),I('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I("$;~0#*;~&"),I(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),I('%%;"/\x87#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:\xd2! )'),I(";\x81.# &;\x82"),I('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),I('$;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/\x8c#0\x89*;+.\x83 &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),I("$;y0#*;y&"),I('%3\x92""5#7\xd3/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:\xd4% )(%\'#($\'#(#\'#("\'#&\'#'),I('2\xd5""6\xd57\xd6'),I('2\xd7""6\xd77\xd8'),I('2\xd9""6\xd97\xda'),I('2\xdb""6\xdb7\xdc'),I('2\xdd""6\xdd7\xde'),I('2\xdf""6\xdf7\xe0'),I('2\xe1""6\xe17\xe2'),I('2\xe3""6\xe37\xe4'),I('2\xe5""6\xe57\xe6'),I('2\xe7""6\xe77\xe8'),I('2\xe9""6\xe97\xea'),I("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8a.A &;\x8b.; &;\x8c.5 &;\x8f./ &;\x8d.) &;\x8e.# &;6/& 8!:\xeb! )"),I("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%;\x93/' 8!:\xec!! )"),I("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),I("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xed! )"),I("%;\xb6/Y#$%;A/,#;\xb6/#$+\")(\"'#&'#06*%;A/,#;\xb6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":\xee" )("\'#&\'#'),I("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xef! )"),I("%;L.# &;\x99/]#$%;B/,#;\x9b/#$+\")(\"'#&'#06*%;B/,#;\x9b/#$+\")(\"'#&'#&/'$8\":\xf0\" )(\"'#&'#"),I("%;\x9a.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),I("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xf1!! )"),I(";\x9c.) &;\x9d.# &;\xa0"),I("%3\xf2\"\"5!7\xf3/:#;$;\xcf/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%$;!/�#*;!&&&#/' 8!:\u014b!! )"),I("%;\xd1/]#$%;A/,#;\xd1/#$+\")(\"'#&'#06*%;A/,#;\xd1/#$+\")(\"'#&'#&/'$8\":\u014c\" )(\"'#&'#"),I("%;\x99/]#$%;B/,#;\xa0/#$+\")(\"'#&'#06*%;B/,#;\xa0/#$+\")(\"'#&'#&/'$8\":\u014d\" )(\"'#&'#"),I('%;L.O &;\x99.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#;\xa0/#$+")("\'#&\'#06*%;B/,#;\xa0/#$+")("\'#&\'#&/\'$8":\u014e" )("\'#&\'#'),I("%;\xd4/]#$%;B/,#;\xd5/#$+\")(\"'#&'#06*%;B/,#;\xd5/#$+\")(\"'#&'#&/'$8\":\u014f\" )(\"'#&'#"),I("%;\x96/& 8!:\u0150! )"),I('%3\u0151""5(7\u0152/:#;$;6/5$;;/,$;\xec/#$+%)(%'#($'#(#'#(\"'#&'#"),I('%3\x92""5#7\xd3.# &;6/\' 8!:\u018b!! )'),I('%3\xb1""5#7\u018c.G &3\xb3""5#7\u018d.; &3\xb7""5#7\u018e./ &3\xb5""5$7\u018f.# &;6/\' 8!:\u0190!! )'),I('%;\xee/D#%;C/,#;\xef/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:\u0191! )"),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:\u0192!! )'),I('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:\u0193!! )'),I(";\xbe"),I('%;\x9e/^#$%;B/,#;\xf3/#$+")("\'#&\'#06*%;B/,#;\xf3/#$+")("\'#&\'#&/($8":\u0194"!!)("\'#&\'#'),I(";\xf4.# &;\xa0"),I('%2\u0195""6\u01957\u0196/L#;""6>7?'),I('%;\u0100/b#28""6879/S$;\xfb/J$%2\u01a3""6\u01a37\u01a4/,#;\xec/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I('%3\u01a5""5%7\u01a6.) &3\u01a7""5$7\u01a8/\' 8!:\u01a1!! )'),I('%3\xb1""5#7\xb2.6 &3\xb3""5#7\xb4.* &$;+0#*;+&/\' 8!:\u01a9!! )'),I("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01aa) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),I("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),I("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"),I("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"),I("%;q/T#$;m0#*;m&/D$%; /,#;\xf8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),I('%2\u01ab""6\u01ab7\u01ac.) &2\u01ad""6\u01ad7\u01ae/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#0<*%;B/2#;\u0109.# &;\xa0/#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),I(";\x99.# &;L"),I("%2\u01af\"\"6\u01af7\u01b0/5#;p&&(p=h,f=[]),f.push(e))}function y(e,t,s){return new n(n.buildMessage(e,t),e,t,s)}function I(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},g=function t(r){const i=d[r];let n=0;const o=[];let a=i.length;const l=[],g=[];let p;for(;;){for(;nh?(a=n+3+i[n+1],n+=3):(a=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 18:l.push(a),o.push(n+4+i[n+2]+i[n+3]),e.substr(h,c[i[n+1]].length)===c[i[n+1]]?(a=n+4+i[n+2],n+=4):(a=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 19:l.push(a),o.push(n+4+i[n+2]+i[n+3]),e.substr(h,c[i[n+1]].length).toLowerCase()===c[i[n+1]]?(a=n+4+i[n+2],n+=4):(a=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 20:l.push(a),o.push(n+4+i[n+2]+i[n+3]),c[i[n+1]].test(e.charAt(h))?(a=n+4+i[n+2],n+=4):(a=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 21:g.push(e.substr(h,i[n+1])),h+=i[n+1],n+=2;break;case 22:g.push(c[i[n+1]]),h+=c[i[n+1]].length,n+=2;break;case 23:g.push(s),0===m&&R(c[i[n+1]]),n+=2;break;case 24:u=g[g.length-1-i[n+1]],n+=2;break;case 25:u=h,n++;break;case 26:p=i.slice(n+4,n+4+i[n+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-i[n+2],i[n+2],c[i[n+1]].apply(null,p)),n+=4+i[n+3];break;case 27:g.push(t(i[n+1])),n+=2;break;case 28:m++,n++;break;case 29:m--,n++;break;default:throw new Error("Invalid opcode: "+i[n]+".")}if(!(l.length>0))break;a=l.pop(),n=o.pop()}return g[0]}(a),g!==s&&h===e.length)return g;throw g!==s&&h=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))switch(super.receiveRequest(e),e.method){case i.C.NOTIFY:this.onNotify(e);break;default:this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+a.a.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){if(this.subscriptionState!==n.a.Pending&&this.subscriptionState!==n.a.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const s=new d.a(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(()=>this.timerN(),o.a.TIMER_N),s}terminate(){this.stateTransition(n.a.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+a.a.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const r=s.state,i=s.expires?Math.max(s.expires,0):void 0;switch(r){case"pending":this.stateTransition(n.a.Pending,i);break;case"active":this.stateTransition(n.a.Active,i);break;case"terminated":this.stateTransition(n.a.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const o=new c.a(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case n.a.Initial:case n.a.NotifyWait:return void s();case n.a.Pending:if(this.subscriptionState!==n.a.NotifyWait&&this.subscriptionState!==n.a.Pending)return void s();break;case n.a.Active:case n.a.Terminated:if(this.subscriptionState!==n.a.NotifyWait&&this.subscriptionState!==n.a.Pending&&this.subscriptionState!==n.a.Active)return void s();break;default:return void s()}e===n.a.Pending&&t&&(this.subscriptionExpires=t),e===n.a.Active&&t&&(this.subscriptionExpires=t),e===n.a.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==n.a.Terminated&&(this.stateTransition(n.a.Terminated),this.onTerminated())}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(15);class i{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(r.a.error,e)}warn(e){this.genericLog(r.a.warn,e)}log(e){this.genericLog(r.a.log,e)}debug(e){this.genericLog(r.a.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Unsupported content type.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(){super("The session has terminated.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Unspecified transport error.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return h}));var r=s(26),i=s(48),n=s(28),o=s(4),a=s(17),c=s(21),d=s(13);class h extends d.a{constructor(e,t,s){super(a.a,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new n.a(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof a.a))throw new Error("Transaction not instance of InviteClientTransaction.");const t=r.a.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new i.a(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact.toString(),d="Allow: "+c.a.toString();if(!e.body)if(this.confirmedDialog.signalingState===o.b.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===o.b.Initial||this.confirmedDialog.signalingState===o.b.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(d),e.extraHeaders.push(s);const h=super.accept(e),u=this.confirmedDialog,l=Object.assign(Object.assign({},h),{session:u});return e.body&&this.confirmedDialog.signalingState!==o.b.Stable&&this.confirmedDialog.signalingStateTransition(e.body),l}progress(e={statusCode:180}){if(!this.progressable)throw new n.a(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof a.a))throw new Error("Transaction not instance of InviteClientTransaction.");const t=r.a.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new i.a(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>"Record-Route: "+e),s="Contact: "+this.core.configuration.contact;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const c=super.progress(e),d=this.earlyDialog,h=Object.assign(Object.assign({},c),{session:d});return e.body&&this.earlyDialog.signalingState!==o.b.Stable&&this.earlyDialog.signalingStateTransition(e.body),h}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}},function(e,t,s){"use strict";s.r(t);var r=s(26);s.d(t,"Dialog",(function(){return r.a}));var i=s(123);for(var n in i)["Dialog","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(48);s.d(t,"SessionDialog",(function(){return o.a}));var a=s(56);s.d(t,"SubscriptionDialog",(function(){return a.a}))},function(e,t,s){"use strict";s.r(t);var r=s(8);s.d(t,"SubscriptionState",(function(){return r.a}));var i=s(126);for(var n in i)["SubscriptionState","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n)},function(e,t,s){"use strict";s.r(t);var r=s(81);s.d(t,"defaultMediaStreamFactory",(function(){return r.a}));var i=s(164);for(var n in i)["defaultMediaStreamFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(82);s.d(t,"defaultPeerConnectionConfiguration",(function(){return o.a}));var a=s(165);for(var n in a)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(n);var c=s(166);for(var n in c)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return c[e]}))}(n);var d=s(100);s.d(t,"defaultSessionDescriptionHandlerFactory",(function(){return d.a}));var h=s(167);for(var n in h)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(n);var u=s(168);for(var n in u)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return u[e]}))}(n);var l=s(169);for(var n in l)["defaultMediaStreamFactory","defaultPeerConnectionConfiguration","defaultSessionDescriptionHandlerFactory","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(n);var g=s(32);s.d(t,"SessionDescriptionHandler",(function(){return g.a}))},function(e,t,s){"use strict";s.r(t);var r=s(86);s.d(t,"Transport",(function(){return r.a}));var i=s(174);for(var n in i)["Transport","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n)},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));class r{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.BYE,s);super(i.a,e.userAgentCore,n,t),e.dispose()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.INFO,s);super(i.a,e.userAgentCore,n,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(24),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.INVITE,s);super(i.a,e.userAgentCore,n,t),this.delegate=t,e.signalingStateTransition(n),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code "+t)}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.NOTIFY,s);super(i.a,e.userAgentCore,n,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.PRACK,s);super(i.a,e.userAgentCore,n,t),e.signalingStateTransition(n)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.REFER,s);super(i.a,e.userAgentCore,n,t)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(17),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>"Record-Route: "+e));const t=super.accept(e),s=this.dialog,r=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),r}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,r=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),r}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(3),i=s(19),n=s(10);class o extends n.a{constructor(e,t,s){const n=e.createOutgoingRequestMessage(r.C.SUBSCRIBE,s);super(i.a,e.userAgentCore,n,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(2);class i{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof r.NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){return this.referTo.uri.getHeader("replaces")}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&s.push("Replaces: "+decodeURIComponent(r));const i=this.referredBy;return i&&s.push("Referred-By: "+i),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(18),i=s(14);class n{constructor(e,t={}){this._disposed=!1,this._state=i.a.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new r.a,this._userAgent=e,this.delegate=t.delegate}dispose(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()}get dialog(){return this._dialog}get disposed(){return this._disposed}get state(){return this._state}get stateChange(){return this._stateEventEmitter}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case i.a.Initial:e!==i.a.NotifyWait&&e!==i.a.Terminated&&t();break;case i.a.NotifyWait:e!==i.a.Subscribed&&e!==i.a.Terminated&&t();break;case i.a.Subscribed:e!==i.a.Terminated&&t();break;case i.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log(`Subscription ${this._dialog?this._dialog.id:void 0} transitioned to ${this._state}`),this._stateEventEmitter.emit(this._state),e===i.a.Terminated&&this.dispose())}}},function(e,t,s){"use strict";function r(){return e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream)}s.d(t,"a",(function(){return r}))},function(e,t,s){"use strict";function r(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}}s.d(t,"a",(function(){return r}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));const r="0.17.1"},function(e,t,s){"use strict";s.d(t,"a",(function(){return a})),s.d(t,"c",(function(){return c})),s.d(t,"b",(function(){return d}));var r=s(35),i=s(27),n=s(46);function o(e){return"application/sdp"===e?"session":"render"}function a(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:o(s),contentType:s,content:t}}function c(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function d(e){let t,s,a;if(e instanceof r.a&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),a=e.body}if(e instanceof i.a&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),a=e.body}if(e instanceof n.a&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");a=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,a=e.body.body}if(c(e)&&(t=e.contentDisposition,s=e.contentType,a=e.content),a){if(s&&!t&&(t=o(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:a}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(6);function i(e,t){if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const s=t.reasonPhrase?t.reasonPhrase:Object(r.b)(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+s+"\r\n";t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+"\r\n",o="Call-ID: "+e.callId+"\r\n",a="CSeq: "+e.cseq+" "+e.method+"\r\n",c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+"\r\n","");let d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Object(r.d)()),d+=";tag="+e}d+="\r\n";let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+"\r\n");let u="";t.userAgent&&(u="User-Agent: "+t.userAgent+"\r\n");let l="";return t.extraHeaders&&(l=t.extraHeaders.reduce((e,t)=>e+t.trim()+"\r\n","")),i+=c,i+=n,i+=d,i+=a,i+=o,i+=h,i+=u,i+=l,t.body?(i+="Content-Type: "+t.body.contentType+"\r\n",i+="Content-Length: "+Object(r.e)(t.body.content)+"\r\n\r\n",i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(18),i=s(37),n=s(5),o=s(2);class a{constructor(e,t){if(this._state=n.a.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new r.a,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,r=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},a.defaultOptions),t);const s=this.configuration.server,i=o.Grammar.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===n.a.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log("Connecting "+this.server),this.state){case n.a.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case n.a.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case n.a.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(n.a.Connecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;case n.a.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(n.a.Connecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(n.a.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log("Disconnecting "+this.server),this.state){case n.a.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(n.a.Disconnecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;case n.a.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(n.a.Disconnecting)}catch(e){if(e instanceof i.a)return Promise.reject(e);throw e}break;case n.a.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case n.a.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(n.a.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==n.a.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,r=this.disconnectPromise?void 0:new Error(s);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(n.a.Disconnected,r)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let r;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{r=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+r+"\n")}else r=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+r+"\n");if(this.state===n.a.Connected){if(this.onMessage)try{this.onMessage(r)}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===n.a.Connecting&&(this.logger.log("WebSocket opened "+this.server),this.transitionState(n.a.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new i.a("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case n.a.Connecting:e!==n.a.Connected&&e!==n.a.Disconnecting&&e!==n.a.Disconnected&&s();break;case n.a.Connected:e!==n.a.Disconnecting&&e!==n.a.Disconnected&&s();break;case n.a.Disconnecting:e!==n.a.Connecting&&e!==n.a.Disconnected&&s();break;case n.a.Disconnected:e!==n.a.Connecting&&s();break;default:throw new Error("Unknown state.")}const r=this._state;this._state=e;const i=this.connectResolve,o=this.connectReject;r===n.a.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const a=this.disconnectResolve,c=this.disconnectReject;if(r===n.a.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${r} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===n.a.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onConnect callback"),e}if(r===n.a.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onDisconnect callback"),e}if(r===n.a.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===n.a.Connected?i():o(t||new Error("Connect aborted."))}if(r===n.a.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!c)throw new Error("Disconnect reject undefined.");e===n.a.Disconnected?a():c(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}a.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0}},function(e,t,s){"use strict";s.r(t);var r=s(38);s.d(t,"ContentTypeUnsupportedError",(function(){return r.a})),s.d(t,"RequestPendingError",(function(){return r.b})),s.d(t,"SessionDescriptionHandlerError",(function(){return r.c})),s.d(t,"SessionTerminatedError",(function(){return r.d})),s.d(t,"StateTransitionError",(function(){return r.e}));var i=s(66);s.d(t,"Bye",(function(){return i.a}));var n=s(18);s.d(t,"EmitterImpl",(function(){return n.a}));var o=s(67);s.d(t,"Info",(function(){return o.a}));var a=s(102);for(var c in a)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(c);var d=s(103);for(var c in d)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return d[e]}))}(c);var h=s(104);for(var c in h)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(c);var u=s(31);s.d(t,"Invitation",(function(){return u.a}));var l=s(133);for(var c in l)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(c);var g=s(134);for(var c in g)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return g[e]}))}(c);var p=s(135);for(var c in p)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(c);var f=s(36);s.d(t,"Inviter",(function(){return f.a}));var m=s(44);s.d(t,"Message",(function(){return m.a}));var v=s(136);for(var c in v)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return v[e]}))}(c);var b=s(137);for(var c in b)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return b[e]}))}(c);var w=s(98);s.d(t,"Messager",(function(){return w.a}));var S=s(29);s.d(t,"Notification",(function(){return S.a}));var T=s(138);for(var c in T)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return T[e]}))}(c);var E=s(139);for(var c in E)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return E[e]}))}(c);var R=s(12);s.d(t,"PublisherState",(function(){return R.a}));var y=s(140);for(var c in y)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return y[e]}))}(c);var I=s(141);s.d(t,"Publisher",(function(){return I.a}));var C=s(79);s.d(t,"Referral",(function(){return C.a}));var $=s(142);for(var c in $)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return $[e]}))}(c);var A=s(143);for(var c in A)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return A[e]}))}(c);var D=s(7);s.d(t,"RegistererState",(function(){return D.a}));var H=s(144);for(var c in H)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return H[e]}))}(c);var x=s(99);s.d(t,"Registerer",(function(){return x.a}));var P=s(145);for(var c in P)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return P[e]}))}(c);var q=s(146);for(var c in q)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return q[e]}))}(c);var _=s(147);for(var c in _)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return _[e]}))}(c);var k=s(148);for(var c in k)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return k[e]}))}(c);var O=s(149);for(var c in O)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return O[e]}))}(c);var M=s(150);for(var c in M)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return M[e]}))}(c);var N=s(151);for(var c in N)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return N[e]}))}(c);var U=s(152);for(var c in U)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return U[e]}))}(c);var j=s(153);for(var c in j)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return j[e]}))}(c);var F=s(1);s.d(t,"SessionState",(function(){return F.a}));var L=s(34);s.d(t,"Session",(function(){return L.a}));var B=s(154);for(var c in B)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return B[e]}))}(c);var G=s(155);for(var c in G)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return G[e]}))}(c);var V=s(156);s.d(t,"Subscriber",(function(){return V.a}));var K=s(157);for(var c in K)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return K[e]}))}(c);var W=s(158);for(var c in W)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return W[e]}))}(c);var Y=s(14);s.d(t,"SubscriptionState",(function(){return Y.a}));var J=s(159);for(var c in J)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return J[e]}))}(c);var Z=s(160);for(var c in Z)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return Z[e]}))}(c);var z=s(80);s.d(t,"Subscription",(function(){return z.a}));var X=s(161);for(var c in X)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return X[e]}))}(c);var Q=s(5);s.d(t,"TransportState",(function(){return Q.a}));var ee=s(162);for(var c in ee)["ContentTypeUnsupportedError","RequestPendingError","SessionDescriptionHandlerError","SessionTerminatedError","StateTransitionError","Bye","EmitterImpl","Info","Invitation","Inviter","Message","Messager","Notification","PublisherState","Publisher","Referral","RegistererState","Registerer","SessionState","Session","Subscriber","SubscriptionState","Subscription","TransportState","default"].indexOf(c)<0&&function(e){s.d(t,e,(function(){return ee[e]}))}(c);var te=s(22);s.d(t,"SIPExtension",(function(){return te.a})),s.d(t,"UserAgentRegisteredOptionTags",(function(){return te.b}));var se=s(16);s.d(t,"UserAgentState",(function(){return se.a}));var re=s(49);s.d(t,"UserAgent",(function(){return re.a}))},function(e,t,s){"use strict";var r=s(101);s.d(t,"a",(function(){return r.a})),s.d(t,"b",(function(){return r.b})),s.d(t,"c",(function(){return r.c})),s.d(t,"d",(function(){return r.d})),s.d(t,"e",(function(){return r.e})),s.d(t,"f",(function(){return r.f})),s.d(t,"g",(function(){return r.g})),s.d(t,"h",(function(){return r.h}))},function(e,t,s){"use strict";s.d(t,"a",(function(){return r.a})),s.d(t,"b",(function(){return i.a})),s.d(t,"c",(function(){return a})),s.d(t,"d",(function(){return c.a})),s.d(t,"e",(function(){return d.a})),s.d(t,"f",(function(){return h.a})),s.d(t,"g",(function(){return u.a})),s.d(t,"h",(function(){return l.a})),s.d(t,"i",(function(){return g.a})),s.d(t,"j",(function(){return p.a})),s.d(t,"k",(function(){return f.a})),s.d(t,"n",(function(){return m.a})),s.d(t,"l",(function(){return v.a})),s.d(t,"m",(function(){return b.a})),s.d(t,"o",(function(){return w.a})),s.d(t,"p",(function(){return S.a})),s.d(t,"q",(function(){return T.a})),s.d(t,"r",(function(){return y})),s.d(t,"s",(function(){return I.a})),s.d(t,"t",(function(){return C.a})),s.d(t,"u",(function(){return $.a})),s.d(t,"v",(function(){return A.a})),s.d(t,"w",(function(){return D.a})),s.d(t,"x",(function(){return H.a})),s.d(t,"y",(function(){return o.a})),s.d(t,"z",(function(){return R.a}));var r=s(68),i=s(74),n=s(19),o=s(10);class a extends o.a{constructor(e,t,s){super(n.a,e,t,s)}}var c=s(69),d=s(75),h=s(92),u=s(61),l=s(53),g=s(54),p=s(71),f=s(30),m=s(93),v=s(72),b=s(77),w=s(70),S=s(76),T=s(78),E=s(20),R=s(13);class y extends R.a{constructor(e,t,s){super(E.a,e.userAgentCore,t,s)}}var I=s(73),C=s(55),$=s(94),A=s(96),D=s(95),H=s(97)},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(25);class i extends r.a{constructor(e){super(e||"Unspecified session description handler error.")}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(15),i=s(57);class n{constructor(){this.builtinEnabled=!0,this._level=r.a.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:r.a.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new i.a(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new i.a(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(r.a[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case r.a.error:console.error(i);break;case r.a.warn:console.warn(i);break;case r.a.log:console.log(i);break;case r.a.debug:console.debug(i)}}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return d}));var r=s(26),i=s(48),n=s(4),o=s(24),a=s(0),c=s(10);class d extends c.a{constructor(e,t,s){super(o.a,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===a.a.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=r.a.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof o.a))throw new Error("Transaction not instance of InviteClientTransaction.");s=new i.a(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==n.b.Initial&&s.signalingState!==n.b.HaveLocalOffer||s.signalingStateTransition(e);const a=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:a,prack:e=>a.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=r.a.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof o.a))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof o.a))throw new Error("Transaction not instance of InviteClientTransaction.");s=new i.a(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==n.b.Initial&&s.signalingState!==n.b.HaveLocalOffer||s.signalingStateTransition(e);const a=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:a,ack:e=>{const t=a.ack(e);return this.confirmedDialogAcks.set(a.id,t),t}});else{const e=a.ack();this.confirmedDialogAcks.set(a.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code "+t)}throw new Error(`Executing what should be an unreachable code path receiving ${t} response.`)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(19),i=s(10);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(19),i=s(10);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s)}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return c}));var r=s(56),i=s(8),n=s(11),o=s(19),a=s(10);class c extends a.a{constructor(e,t,s){const r=t.getHeader("Event");if(!r)throw new Error("Event undefined");const n=t.getHeader("Expires");if(!n)throw new Error("Expires undefined");super(o.a,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+r,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(n),this.subscriptionEvent=r,this.subscriptionState=i.a.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const n=s.state;switch(n){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state "+n),void e.reject({statusCode:489})}if("terminated"!==n){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=i.a.Pending;break;case"active":this.subscriptionState=i.a.Active;break;case"terminated":this.subscriptionState=i.a.Terminated;break;default:throw new Error(`Unrecognized state ${n}.`)}if(this.subscriptionState!==i.a.Terminated){const t=r.a.initialDialogStateForSubscription(this.message,e.message);this.dialog=new r.a(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),n.a.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ethis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s),this.core=e}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var r=s(20),i=s(13);class n extends i.a{constructor(e,t,s){super(r.a,e,t,s),this.core=e}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return i}));var r=s(2);class i{constructor(e,t,s,i="text/plain",n={}){this.logger=e.getLogger("sip.Messager"),n.params=n.params||{};let o=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(o="string"==typeof n.params.fromUri?r.Grammar.URIParse(n.params.fromUri):n.params.fromUri),!o)throw new TypeError("Invalid from URI: "+n.params.fromUri);let a=t;if(n.params.toUri&&(a="string"==typeof n.params.toUri?r.Grammar.URIParse(n.params.toUri):n.params.toUri),!a)throw new TypeError("Invalid to URI: "+n.params.toUri);const c=n.params?Object.assign({},n.params):{},d=(n.extraHeaders||[]).slice(),h={contentDisposition:"render",contentType:i,content:s};this.request=e.userAgentCore.makeOutgoingRequestMessage(r.C.MESSAGE,t,o,a,c,d,h),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}},function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var r=s(2),i=s(18),n=s(47),o=s(7);class a{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=o.a.Initial,this._waiting=!1,this._stateEventEmitter=new i.a,this._waitingEventEmitter=new i.a,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},a.defaultOptions()),{registrar:s}),a.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=a.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===r.Grammar.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const n=this.options.registrar,c=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,d=this.options.params&&this.options.params.toUri||e.configuration.uri,h=this.options.params||{},u=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(r.C.REGISTER,n,c,d,h,u,void 0),this.expires=this.options.expires||a.defaultExpires,this.expires<0)throw new Error("Invalid expires.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"registrar":this.logger.log("\xb7 "+e+": "+t);break;default:this.logger.log("\xb7 "+e+": "+JSON.stringify(t))}})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:a.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new r.URI("sip","anonymous","anonymous.invalid")}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===o.a.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===o.a.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new n.a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,n=this._contacts.length;if(!n)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;n--;){if(i=t.message.parseHeader("contact",n),!i)throw new Error("Contact undefined");if(i.uri.user===this.userAgent.contact.uri.user){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=r.Grammar.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=r.Grammar.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn("Failed to register, status code "+t.message.statusCode);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===o.a.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==o.a.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new n.a("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===o.a.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error("Unregister rejected with status code "+t.message.statusCode),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},1e3*e-3e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==o.a.Registered&&this.stateTransition(o.a.Registered)}unregistered(){this.clearTimers(),this._state!==o.a.Unregistered&&this.stateTransition(o.a.Unregistered)}terminated(){this.clearTimers(),this._state!==o.a.Terminated&&this.stateTransition(o.a.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case o.a.Initial:e!==o.a.Registered&&e!==o.a.Unregistered&&e!==o.a.Terminated&&t();break;case o.a.Registered:e!==o.a.Unregistered&&e!==o.a.Terminated&&t();break;case o.a.Unregistered:e!==o.a.Registered&&e!==o.a.Terminated&&t();break;case o.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===o.a.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log("Waiting toggled to "+this._waiting),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===o.a.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}a.defaultExpires=600},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(81),i=s(82),n=s(32);function o(e){return(t,s)=>{void 0===e&&(e=Object(r.a)());const o={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},Object(i.a)()),null==s?void 0:s.peerConnectionConfiguration)},a=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new n.a(a,e,o)}}},function(e,t,s){"use strict";s.d(t,"f",(function(){return i})),s.d(t,"g",(function(){return n})),s.d(t,"b",(function(){return o})),s.d(t,"d",(function(){return a})),s.d(t,"e",(function(){return c})),s.d(t,"h",(function(){return d})),s.d(t,"a",(function(){return h})),s.d(t,"c",(function(){return u}));const r=(e,t)=>{const s=[],r=e.split(/\r\n/);let i;for(let e=0;e(t.sdp=r(t.sdp||"",e),Promise.resolve(t))}function d(e){return e.sdp=((e,t)=>{const s=new RegExp("m="+t+".*$","gm"),r=new RegExp("^a=group:.*$","gm");if(s.test(e)){let s;const i=(e=e.split(/^m=/gm).filter(e=>{if(e.substr(0,t.length)===t){if(s=e.match(/^a=mid:.*$/gm),s){const e=s[0].match(/:.+$/g);e&&(s=e[0].substr(1))}return!1}return!0}).join("m=")).match(r);if(i&&1===i.length){let t=i[0];const n=new RegExp(" *"+s+"[^ ]*","g");t=t.replace(n,""),e=e.split(r).join(t)}}return e})(e.sdp||"","video"),Promise.resolve(e)}function h(e){let t=e.sdp||"";if(-1===t.search(/^a=mid.*$/gm)){const s=t.match(/^m=.*$/gm),r=t.split(/^m=.*$/gm);s&&s.forEach((e,t)=>{s[t]=e+"\na=mid:"+t}),r.forEach((e,t)=>{s&&s[t]&&(r[t]=e+s[t])}),t=r.join(""),e.sdp=t}return Promise.resolve(e)}function u(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const s=e.type;return t&&(/a=(sendrecv|sendonly|recvonly|inactive)/.test(t)?(t=t.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),t=t.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):t=t.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n")),Promise.resolve({sdp:t,type:s})}},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(106);s.d(t,"C",(function(){return r.a}));var i=s(107);for(var n in i)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(108);for(var n in o)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n);var a=s(109);for(var n in a)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(n);var c=s(110);for(var n in c)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return c[e]}))}(n);var d=s(111);for(var n in d)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return d[e]}))}(n);var h=s(112);for(var n in h)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return h[e]}))}(n);var u=s(113);for(var n in u)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return u[e]}))}(n);var l=s(114);for(var n in l)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return l[e]}))}(n);var g=s(115);for(var n in g)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return g[e]}))}(n);var p=s(116);for(var n in p)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return p[e]}))}(n);var f=s(117);for(var n in f)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return f[e]}))}(n);var m=s(118);for(var n in m)["C","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return m[e]}))}(n)},function(e,t,s){"use strict";var r;s.d(t,"a",(function(){return r})),function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));var r,i=s(50),n=s(35),o=s(27);!function(e){function t(e,t){let s=t,r=0,i=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===r;){if(i=e.indexOf("\r\n",s),-1===i)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?s=i+2:r=i}return r}function s(e,t,s,r){const n=t.indexOf(":",s),a=t.substring(s,n).trim(),c=t.substring(n+1,r).trim();let d;switch(a.toLowerCase()){case"via":case"v":e.addHeader("via",c),1===e.getHeaders("via").length?(d=e.parseHeader("Via"),d&&(e.via=d,e.viaBranch=d.branch)):d=0;break;case"from":case"f":e.setHeader("from",c),d=e.parseHeader("from"),d&&(e.from=d,e.fromTag=d.getParam("tag"));break;case"to":case"t":e.setHeader("to",c),d=e.parseHeader("to"),d&&(e.to=d,e.toTag=d.getParam("tag"));break;case"record-route":if(d=i.a.parse(c,"Record_Route"),-1===d){d=void 0;break}if(!(d instanceof Array)){d=void 0;break}d.forEach(t=>{e.addHeader("record-route",c.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",c),d=e.parseHeader("call-id"),d&&(e.callId=c);break;case"contact":case"m":if(d=i.a.parse(c,"Contact"),-1===d){d=void 0;break}if(!(d instanceof Array)){d=void 0;break}d.forEach(t=>{e.addHeader("contact",c.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",c),d=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",c),d=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",c),d=e.parseHeader("cseq"),d&&(e.cseq=d.value),e instanceof o.a&&(e.method=d.method);break;case"max-forwards":e.setHeader("max-forwards",c),d=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",c),d=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",c),d=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",c),d=e.parseHeader("refer-to"),d&&(e.referTo=d);break;default:e.addHeader(a.toLowerCase(),c),d=0}return void 0!==d||{error:"error parsing header '"+a+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,r){let a=0,c=e.indexOf("\r\n");if(-1===c)return void r.warn("no CRLF found, not a SIP message, discarded");const d=e.substring(0,c),h=i.a.parse(d,"Request_Response");let u,l;if(-1!==h){for(h.status_code?(u=new o.a,u.statusCode=h.status_code,u.reasonPhrase=h.reason_phrase):(u=new n.a,u.method=h.method,u.ruri=h.uri),u.data=e,a=c+2;;){if(c=t(e,a),-2===c){l=a+2;break}if(-1===c)return void r.error("malformed message");if(!0!==s(u,e,a,c))return void r.error(h.error);a=c+2}return u.hasHeader("content-length")?u.body=e.substr(l,Number(u.getHeader("content-length"))):u.body=e.substring(l),u}r.warn('error parsing first line of SIP message: "'+d+'"')}}(r||(r={}))},function(e,t){},function(e,t,s){"use strict";var r=s(15);s.d(t,"a",(function(){return r.a}));var i=s(91);s.d(t,"c",(function(){return i.a}));var n=s(57);s.d(t,"b",(function(){return n.a}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(129);s.d(t,"UserAgentCore",(function(){return r.a}));var i=s(130);for(var n in i)["UserAgentCore","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(131);for(var n in o)["UserAgentCore","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n)},function(e,t,s){"use strict";s.d(t,"a",(function(){return R}));var r=s(3),i=s(46),n=s(85),o=s(19),a=s(0),c=s(17),d=s(92),h=s(53),u=s(93),l=s(94),g=s(95),p=s(10),f=s(61),m=s(30),v=s(54),b=s(55),w=s(96),S=s(97),T=s(21);const E=["application/sdp","application/dtmf-relay"];class R{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new d.a(this,e,t)}message(e,t){return new h.a(this,e,t)}publish(e,t){return new u.a(this,e,t)}register(e,t){return new l.a(this,e,t)}subscribe(e,t){return new g.a(this,e,t)}request(e,t){return new p.a(o.a,this,e,t)}makeOutgoingRequestMessage(e,t,s,n,o,a,c){const d=this.configuration.sipjsId,h=this.configuration.displayName,u=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,g=this.configuration.supportedOptionTags.slice();e===r.C.REGISTER&&g.push("path","gruu"),e===r.C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&g.push("gruu");const p={callIdPrefix:d,forceRport:u,fromDisplayName:h,hackViaTcp:l,optionTags:g,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=Object.assign(Object.assign({},p),o);return new i.a(e,t,s,n,f,a,c)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:r});const i=Object(n.a)(e,t);return this.transport.send(i.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),i}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===r.C.ACK&&s&&s.transaction.state===a.a.Accepted&&s instanceof f.a?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==r.C.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof c.a&&s.transaction.state===a.a.Proceeding&&s instanceof f.a&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!T.a.includes(e.method)){const t="Allow: "+T.a.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==r.C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==r.C.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===r.C.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,r=this.subscribers.get(s);if(r){const t=new m.a(this,e);return void r.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===r.C.OPTIONS){const t="Allow: "+T.a.toString(),s="Accept: "+E.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==r.C.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case r.C.ACK:break;case r.C.BYE:this.replyStateless(e,{statusCode:481});break;case r.C.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case r.C.INFO:this.replyStateless(e,{statusCode:405});break;case r.C.INVITE:{const t=new f.a(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case r.C.MESSAGE:{const t=new v.a(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case r.C.NOTIFY:{const t=new m.a(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case r.C.OPTIONS:{const t="Allow: "+T.a.toString(),s="Accept: "+E.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case r.C.REFER:{const t=new b.a(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case r.C.REGISTER:{const t=new w.a(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case r.C.SUBSCRIBE:{const t=new S.a(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));var r=s(2),i=s(18),n=s(12);class o{constructor(e,t,s,o={}){this.disposed=!1,this._state=n.a.Initial,this._stateEventEmitter=new i.a,this.userAgent=e,o.extraHeaders=(o.extraHeaders||[]).slice(),o.contentType=o.contentType||"text/plain","number"!=typeof o.expires||o.expires%1!=0?o.expires=3600:o.expires=Number(o.expires),"boolean"!=typeof o.unpublishOnClose&&(o.unpublishOnClose=!0),this.target=t,this.event=s,this.options=o,this.pubRequestExpires=o.expires,this.logger=e.getLogger("sip.Publisher");const a=o.params||{},c=a.fromUri?a.fromUri:e.userAgentCore.configuration.aor,d=a.toUri?a.toUri:t;let h;if(o.body&&o.contentType){h={contentDisposition:"render",contentType:o.contentType,content:o.body}}const u=(o.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage(r.C.PUBLISH,t,c,d,a,u,h),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===n.a.Published?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0,Promise.resolve()))}get state(){return this._state}get stateChange(){return this._stateEventEmitter}publish(e,t={}){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires){if(void 0===this.options.expires)throw new Error("Expires undefined.");this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0}return this.sendPublishRequest(),Promise.resolve()}unpublish(e={}){return this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest(),Promise.resolve()}receiveResponse(e){const t=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(t.toString()):break;case/^2[0-9]{2}$/.test(t.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){const t=Number(e.getHeader("Expires"));"number"==typeof t&&t>=0&&t<=this.pubRequestExpires?this.pubRequestExpires=t:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout(()=>this.refreshRequest(),900*this.pubRequestExpires),this.stateTransition(n.a.Published)):this.stateTransition(n.a.Unpublished);break;case/^412$/.test(t.toString()):if(void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires){if(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated);break;case/^423$/.test(t.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){const t=Number(e.getHeader("Min-Expires"));if("number"==typeof t||t>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=t,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(n.a.Unpublished),this.stateTransition(n.a.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)}send(){return this.userAgent.userAgentCore.publish(this.request,{onAccept:e=>this.receiveResponse(e.message),onProgress:e=>this.receiveResponse(e.message),onRedirect:e=>this.receiveResponse(e.message),onReject:e=>this.receiveResponse(e.message),onTrying:e=>this.receiveResponse(e.message)})}refreshRequest(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new Error("Etag undefined");if(0===this.pubRequestExpires)throw new Error("Expires zero");this.sendPublishRequest()}sendPublishRequest(){const e=Object.assign({},this.options);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);const t=this.target,s=this.options.params||{};let i,n;if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");i={body:this.pubRequestBody,contentType:this.options.contentType}}return i&&(n=Object(r.fromBodyLegacy)(i)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(r.C.PUBLISH,t,s.fromUri?s.fromUri:this.userAgent.userAgentCore.configuration.aor,s.toUri?s.toUri:this.target,s,e.extraHeaders,n),this.send()}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case n.a.Initial:e!==n.a.Published&&e!==n.a.Unpublished&&e!==n.a.Terminated&&t();break;case n.a.Published:e!==n.a.Unpublished&&e!==n.a.Terminated&&t();break;case n.a.Unpublished:e!==n.a.Published&&e!==n.a.Terminated&&t();break;case n.a.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state "+this._state),this._stateEventEmitter.emit(this._state),e===n.a.Terminated&&this.dispose()}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return c}));var r=s(2),i=s(21),n=s(29),o=s(80),a=s(14);class c extends o.a{constructor(e,t,s,r={}){super(e,r),this.body=void 0,this.logger=e.getLogger("sip.Subscriber"),r.body&&(this.body={body:r.body,contentType:r.contentType?r.contentType:"application/sdp"}),this.targetURI=t,this.event=s,void 0===r.expires?this.expires=3600:"number"!=typeof r.expires?(this.logger.warn('Option "expires" must be a number. Using default of 3600.'),this.expires=3600):this.expires=r.expires,this.extraHeaders=(r.extraHeaders||[]).slice(),this.subscriberRequest=this.initSubscriberRequest(),this.outgoingRequestMessage=this.subscriberRequest.message,this.id=this.outgoingRequestMessage.callId+this.outgoingRequestMessage.from.parameters.tag+this.event,this._userAgent._subscriptions[this.id]=this}dispose(){return this.disposed?Promise.resolve():(this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),super.dispose().then(()=>{if(this.state===a.a.Subscribed){if(!this._dialog)throw new Error("Dialog undefined.");if(this._dialog.subscriptionState===r.SubscriptionState.Pending||this._dialog.subscriptionState===r.SubscriptionState.Active){const e=this._dialog;return new Promise((t,s)=>{e.delegate={onTerminated:()=>t()},e.unsubscribe()})}}}))}subscribe(e={}){switch(this.subscriberRequest.state){case r.SubscriptionState.Initial:this.state===a.a.Initial&&this.stateTransition(a.a.NotifyWait),this.subscriberRequest.subscribe().then(e=>{e.success?(e.success.subscription&&(this._dialog=e.success.subscription,this._dialog.delegate={onNotify:e=>this.onNotify(e),onRefresh:e=>this.onRefresh(e),onTerminated:()=>{this.state!==a.a.Terminated&&this.stateTransition(a.a.Terminated)}}),this.onNotify(e.success.request)):e.failure&&this.unsubscribe()});break;case r.SubscriptionState.NotifyWait:case r.SubscriptionState.Pending:break;case r.SubscriptionState.Active:if(this._dialog){this._dialog.refresh().delegate={onAccept:e=>this.onAccepted(e),onRedirect:e=>this.unsubscribe(),onReject:e=>this.unsubscribe()}}break;case r.SubscriptionState.Terminated:}return Promise.resolve()}unsubscribe(e={}){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case r.SubscriptionState.Initial:case r.SubscriptionState.NotifyWait:break;case r.SubscriptionState.Pending:case r.SubscriptionState.Active:this._dialog&&this._dialog.unsubscribe();break;case r.SubscriptionState.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(a.a.Terminated),Promise.resolve()}_refresh(){return this.subscriberRequest.state===r.SubscriptionState.Active?this.subscribe():Promise.resolve()}onAccepted(e){}onNotify(e){if(this.disposed)return void e.accept();if(this.state!==a.a.Subscribed&&this.stateTransition(a.a.Subscribed),this.delegate&&this.delegate.onNotify){const t=new n.a(e);this.delegate.onNotify(t)}else e.accept();const t=e.message.parseHeader("Subscription-State");if(t&&t.state)switch(t.state){case"terminated":if(t.reason)switch(this.logger.log("Terminated subscription with reason "+t.reason),t.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(t.params&&t.params["retry-after"]?this.retryAfterTimer=setTimeout(()=>{this.subscribe()},t.params["retry-after"]):this.subscribe())}this.unsubscribe()}}onRefresh(e){e.delegate={onAccept:e=>this.onAccepted(e)}}initSubscriberRequest(){const e={extraHeaders:this.extraHeaders,body:this.body?Object(r.fromBodyLegacy)(this.body):void 0};return this.subscriberRequest=new d(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,e),this.subscriberRequest.delegate={onAccept:e=>this.onAccepted(e)},this.subscriberRequest}}class d{constructor(e,t,s,n,o,a){this.core=e,this.target=t,this.event=s,this.expires=n,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=a;const c="Allow: "+i.a.toString(),d=(o&&o.extraHeaders||[]).slice();d.push(c),d.push("Event: "+this.event),d.push("Expires: "+this.expires),d.push("Contact: "+this.core.configuration.contact.toString());const h=o&&o.body;this.message=e.makeOutgoingRequestMessage(r.C.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},d,h)}dispose(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)}get state(){return this.subscription?this.subscription.subscriptionState:this.subscribed?r.SubscriptionState.NotifyWait:r.SubscriptionState.Initial}subscribe(){return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(e=>{if(!this.message)throw new Error("Message undefined.");this.request=this.core.subscribe(this.message,{onAccept:e=>{this.delegate&&this.delegate.onAccept&&this.delegate.onAccept(e)},onNotify:t=>{this.subscription=t.subscription,this.subscription&&(this.subscription.autoRefresh=!0),e({success:t})},onNotifyTimeout:()=>{e({failure:{}})},onRedirect:t=>{e({failure:{response:t}})},onReject:t=>{e({failure:{response:t}})}})}))}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(88);s.d(t,"stripTcpCandidates",(function(){return r.f})),s.d(t,"stripTelephoneEvent",(function(){return r.g})),s.d(t,"cleanJitsiSdpImageattr",(function(){return r.b})),s.d(t,"stripG722",(function(){return r.d})),s.d(t,"stripRtpPayload",(function(){return r.e})),s.d(t,"stripVideo",(function(){return r.h})),s.d(t,"addMidLines",(function(){return r.a})),s.d(t,"holdModifier",(function(){return r.c}));var i=s(64);for(var n in i)["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(170);for(var n in o)["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n);var a=s(65);for(var n in a)["stripTcpCandidates","stripTelephoneEvent","cleanJitsiSdpImageattr","stripG722","stripRtpPayload","stripVideo","addMidLines","holdModifier","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return a[e]}))}(n)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.r(t);var r=s(171);s.d(t,"SimpleUser",(function(){return r.a}));var i=s(172);for(var n in i)["SimpleUser","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(173);for(var n in o)["SimpleUser","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return o[e]}))}(n)},function(e,t,s){"use strict";s.d(t,"a",(function(){return f}));var r=s(49),i=s(16),n=s(99),o=s(7),a=s(36),c=s(31),d=s(98),h=s(1),u=s(47),l=s(101),g=s(32),p=s(86);class f{constructor(e,t={}){this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=Object.assign({},t);const s=Object.assign({},t.userAgentOptions);if(s.transportConstructor||(s.transportConstructor=p.a),s.transportOptions||(s.transportOptions={server:e}),!s.uri&&t.aor){const e=r.a.makeURI(t.aor);if(!e)throw new Error("Failed to create valid URI from "+t.aor);s.uri=e}this.userAgent=new r.a(s),this.userAgent.delegate={onConnect:()=>{this.logger.log(`[${this.id}] Connected`),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.registerer&&this.registerRequested&&(this.logger.log(`[${this.id}] Registering...`),this.registerer.register().catch(e=>{this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`),this.logger.error(e.toString())}))},onDisconnect:e=>{this.logger.log(`[${this.id}] Disconnected`),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),this.session&&(this.logger.log(`[${this.id}] Hanging up...`),this.hangup().catch(e=>{this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`),this.logger.error(e.toString())})),this.registerer&&(this.logger.log(`[${this.id}] Unregistering...`),this.registerer.unregister().catch(e=>{this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`),this.logger.error(e.toString())})),e&&this.attemptReconnection()},onInvite:e=>{if(this.logger.log(`[${this.id}] Received INVITE`),this.session)return this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())});const t={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,t),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived():(this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${this.id}] Rejected INVITE`)}).catch(e=>{this.logger.error(`[${this.id}] Failed to reject INVITE`),this.logger.error(e.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",()=>{this.logger.log(`[${this.id}] Online`),this.attemptReconnection()})}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof g.a))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}get remoteMediaStream(){var e;const t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof g.a))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}get localAudioTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get localVideoTrack(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}get remoteAudioTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"audio"===e.kind)}get remoteVideoTrack(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(e=>"video"===e.kind)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.connectRequested=!0,this.userAgent.state!==i.a.Started?this.userAgent.start():this.userAgent.reconnect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.connectRequested=!1,this.userAgent.stop()}isConnected(){return this.userAgent.isConnected()}register(e,t){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.registerRequested=!0,this.registerer||(this.registerer=new n.a(this.userAgent,e),this.registerer.stateChange.addListener(e=>{switch(e){case o.a.Initial:break;case o.a.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case o.a.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered();break;case o.a.Terminated:this.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(()=>{})}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):Promise.resolve()}call(e,t,s){if(this.logger.log(`[${this.id}] Beginning Session...`),this.session)return Promise.reject(new Error("Session already exists."));const i=r.a.makeURI(e);if(!i)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);const n=new a.a(this.userAgent,i,t);return this.sendInvite(n,t,s).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.terminate()}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.session instanceof c.a?(e||(e={}),e.sessionDescriptionHandlerOptions||(e.sessionDescriptionHandlerOptions={}),e.sessionDescriptionHandlerOptions.constraints||(e.sessionDescriptionHandlerOptions.constraints=this.constraints),this.session.accept(e)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.session instanceof c.a?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.setHold(!0)}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.setHold(!1)}isHeld(){return this.held}mute(){this.logger.log(`[${this.id}] disabling media tracks...`),this.setMute(!0)}unmute(){this.logger.log(`[${this.id}] enabling media tracks...`),this.setMute(!1)}isMuted(){const e=this.localAudioTrack||this.localVideoTrack;return!!e&&!e.enabled}sendDTMF(e){if(this.logger.log(`[${this.id}] sending DTMF...`),!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.session)return Promise.reject(new Error("Session does not exist."));this.logger.log(`[${this.id}] Sending DTMF tone: ${e}`);const t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(()=>{})}message(e,t){this.logger.log(`[${this.id}] sending message...`);const s=r.a.makeURI(e);return s?new d.a(this.userAgent,s,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}get constraints(){var e;let t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=Object.assign({},this.options.media.constraints)),t}attemptReconnection(e=1){const t=this.options.reconnectionAttempts||3,s=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log(`[${this.id}] Reconnection attempt already in progress`),e>t?this.logger.log(`[${this.id}] Reconnection maximum attempts reached`):(1===e?this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - trying in ${s} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.connectRequested)return this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(s=>{this.logger.log(`[${this.id}] Reconnection attempt ${e} of ${t} - failed`),this.logger.error(s.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*s))):this.logger.log(`[${this.id}] Reconnection not currently desired`)}cleanupMedia(){this.options.media&&(this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause()),this.options.media.remote&&(this.options.media.remote.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause()),this.options.media.remote.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause())))}enableSenderTracks(e){if(!this.session)throw new Error("Session does not exist.");const t=this.session.sessionDescriptionHandler;if(!(t instanceof g.a))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const s=t.peerConnection;if(!s)throw new Error("Peer connection closed.");s.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}initSession(e,t){this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(t=>{if(this.session===e)switch(this.logger.log(`[${this.id}] session state changed to ${t}`),t){case h.a.Initial:case h.a.Establishing:break;case h.a.Established:this.setupLocalMedia(),this.setupRemoteMedia(),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered();break;case h.a.Terminating:case h.a.Terminated:this.session=void 0,this.cleanupMedia(),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:e=>{var t;if(void 0===(null===(t=this.delegate)||void 0===t?void 0:t.onCallDTMFReceived))return void e.reject();const s=e.request.getHeader("content-type");if(!s||!/^application\/dtmf-relay/i.exec(s))return void e.reject();const r=e.request.body.split("\r\n",2);if(2!==r.length)return void e.reject();let i;const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(n.test(r[0])&&(i=r[0].replace(n,"$2")),!i)return void e.reject();let o;const a=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;a.test(r[1])&&(o=parseInt(r[1].replace(a,"$2"),10)),o?e.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!i||!o)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(i,o)}}).catch(e=>{this.logger.error(e.message)}):e.reject()},onRefer:e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(t),t)).catch(e=>{this.logger.error(e.message)})}}}sendInvite(e,t,s){return this.initSession(e,t),e.invite(s).then(()=>{this.logger.log(`[${this.id}] sent INVITE`)})}setHold(e){if(!this.session)return Promise.reject(new Error("Session does not exist."));if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof g.a))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const t={requestDelegate:{onAccept:()=>{this.held=e,this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)},onReject:()=>{this.logger.warn(`[${this.id}] re-invite request was rejected`),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(this.held)}}};return t.sessionDescriptionHandlerModifiers=e?[l.c]:[],this.session.invite(t).then(()=>{this.enableSenderTracks(!e)}).catch(e=>{throw e instanceof u.a&&this.logger.error(`[${this.id}] A hold request is already in progress.`),e})}setMute(e){this.session?this.session.state===h.a.Established?this.enableSenderTracks(!e):this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`):this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`)}setupLocalMedia(){var e,t;if(!this.session)throw new Error("Session does not exist.");const s=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(s){const e=this.localMediaStream;if(!e)throw new Error("Local media stream undefiend.");s.srcObject=e,s.volume=0,s.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play local media`),this.logger.error(e.message)})}}setupRemoteMedia(){var e,t,s,r;if(!this.session)throw new Error("Session does not exist.");const i=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(r=null===(s=this.options.media)||void 0===s?void 0:s.remote)||void 0===r?void 0:r.audio);if(i){const e=this.remoteMediaStream;if(!e)throw new Error("Remote media stream undefiend.");i.autoplay=!0,i.srcObject=e,i.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)}),e.onaddtrack=()=>{this.logger.log(`[${this.id}] Remote media onaddtrack`),i.load(),i.play().catch(e=>{this.logger.error(`[${this.id}] Failed to play remote media`),this.logger.error(e.message)})}}}terminate(){if(this.logger.log(`[${this.id}] Terminating...`),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case h.a.Initial:if(this.session instanceof a.a)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`)});if(this.session instanceof c.a)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case h.a.Establishing:if(this.session instanceof a.a)return this.session.cancel().then(()=>{this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`)});if(this.session instanceof c.a)return this.session.reject().then(()=>{this.logger.log(`[${this.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case h.a.Established:return this.session.bye().then(()=>{this.logger.log(`[${this.id}] Session ended (sent BYE)`)});case h.a.Terminating:case h.a.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`),Promise.resolve()}}},function(e,t){},function(e,t){},function(e,t){},function(e,t,s){"use strict";s.d(t,"a",(function(){return o}));class r{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=r.hexChars,s=r.hexOut;let i,n,o,a;for(a=0;a<4;a+=1)for(n=8*a,i=e[a],o=0;o<8;o+=2)s[n+1+o]=t.charAt(15&i),i>>>=4,s[n+0+o]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],r=e[1],i=e[2],n=e[3];s+=(r&i|~r&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[2]+606105819|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[3]-1044525330|0,r=(r<<22|r>>>10)+i|0,s+=(r&i|~r&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[6]-1473231341|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[7]-45705983|0,r=(r<<22|r>>>10)+i|0,s+=(r&i|~r&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[10]-42063|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[11]-1990404162|0,r=(r<<22|r>>>10)+i|0,s+=(r&i|~r&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+r|0,n+=(s&r|~s&i)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,i+=(n&s|~n&r)+t[14]-1502002290|0,i=(i<<17|i>>>15)+n|0,r+=(i&n|~i&s)+t[15]+1236535329|0,r=(r<<22|r>>>10)+i|0,s+=(r&n|i&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[11]+643717713|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[0]-373897302|0,r=(r<<20|r>>>12)+i|0,s+=(r&n|i&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[15]-660478335|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[4]-405537848|0,r=(r<<20|r>>>12)+i|0,s+=(r&n|i&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[3]-187363961|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[8]+1163531501|0,r=(r<<20|r>>>12)+i|0,s+=(r&n|i&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+r|0,n+=(s&i|r&~i)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,i+=(n&r|s&~r)+t[7]+1735328473|0,i=(i<<14|i>>>18)+n|0,r+=(i&s|n&~s)+t[12]-1926607734|0,r=(r<<20|r>>>12)+i|0,s+=(r^i^n)+t[5]-378558|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[11]+1839030562|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[14]-35309556|0,r=(r<<23|r>>>9)+i|0,s+=(r^i^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[7]-155497632|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[10]-1094730640|0,r=(r<<23|r>>>9)+i|0,s+=(r^i^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[3]-722521979|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[6]+76029189|0,r=(r<<23|r>>>9)+i|0,s+=(r^i^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+r|0,n+=(s^r^i)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,i+=(n^s^r)+t[15]+530742520|0,i=(i<<16|i>>>16)+n|0,r+=(i^n^s)+t[2]-995338651|0,r=(r<<23|r>>>9)+i|0,s+=(i^(r|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[14]-1416354905|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[5]-57434055|0,r=(r<<21|r>>>11)+i|0,s+=(i^(r|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[10]-1051523|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[1]-2054922799|0,r=(r<<21|r>>>11)+i|0,s+=(i^(r|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[6]-1560198380|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[13]+1309151649|0,r=(r<<21|r>>>11)+i|0,s+=(i^(r|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+r|0,n+=(r^(s|~i))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,i+=(s^(n|~r))+t[2]+718787259|0,i=(i<<15|i>>>17)+n|0,r+=(n^(i|~s))+t[9]-343485551|0,r=(r<<21|r>>>11)+i|0,e[0]=s+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(r.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,n,o=this._bufferLength;for(n=0;n>>6),t[o++]=63&i|128;else if(i<55296||i>56319)t[o++]=224+(i>>>12),t[o++]=i>>>6&63|128,t[o++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++n)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[o++]=240+(i>>>18),t[o++]=i>>>12&63|128,t[o++]=i>>>6&63|128,t[o++]=63&i|128}o>=64&&(this._dataLength+=64,r._md5cycle(this._state,s),o-=64,s[0]=s[16])}return this._bufferLength=o,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,n=this._bufferLength,o=0;for(;;){for(i=Math.min(e.length-o,64-n);i--;)t[n++]=e.charCodeAt(o++);if(n<64)break;this._dataLength+=64,r._md5cycle(this._state,s),n=0}return this._bufferLength=n,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,n=this._bufferLength,o=0;for(;;){for(i=Math.min(e.length-o,64-n);i--;)t[n++]=e[o++];if(n<64)break;this._dataLength+=64,r._md5cycle(this._state,s),n=0}return this._bufferLength=n,this}getState(){const e=this._state;return{buffer:String.fromCharCode.apply(null,this._buffer8),buflen:this._bufferLength,length:this._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(e){const t=e.buffer,s=e.state,r=this._state;let i;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=s[0],r[1]=s[1],r[2]=s[2],r[3]=s[3],i=0;i>2);let o;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(r.buffer32Identity.subarray(n),n),t>55&&(r._md5cycle(this._state,i),i.set(r.buffer32Identity)),o=8*this._dataLength,o<=4294967295)i[14]=o;else{const e=o.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return r._md5cycle(this._state,i),e?this._state:r._hex(this._state)}}r.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),r.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),r.hexChars="0123456789abcdef",r.hexOut=[],r.onePassHasher=new r,"5d41402abc4b2a76b9719d911017c592"!==r.hashStr("hello")&&console.error("Md5 self test failed.");var i=s(6);function n(e){return r.hashStr(e)}class o{constructor(e,t,s,r){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=Object(i.a)(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=n(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=n(this.method+":"+this.uri),this.response=n(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=n(this.method+":"+this.uri+":"+n(e||"")),this.response=n(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=n(this.method+":"+this.uri),this.response=n(t+":"+this.nonce+":"+s))}}},function(e,t,s){"use strict";s.r(t),s.d(t,"name",(function(){return h})),s.d(t,"version",(function(){return d}));var r=s(83),i=s(87);for(var n in i)["name","version","Core","Web","default"].indexOf(n)<0&&function(e){s.d(t,e,(function(){return i[e]}))}(n);var o=s(33);s.d(t,"Grammar",(function(){return o.a})),s.d(t,"NameAddrHeader",(function(){return o.b})),s.d(t,"Parameters",(function(){return o.c})),s.d(t,"URI",(function(){return o.d}));var a=s(2);s.d(t,"Core",(function(){return a}));var c=s(163);s.d(t,"Web",(function(){return c}));const d=r.a,h="sip.js"}])})); \ No newline at end of file diff --git a/lib/api/bye.d.ts b/lib/api/bye.d.ts deleted file mode 100644 index 3ab581000..000000000 --- a/lib/api/bye.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingByeRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * A request to end a {@link Session} (incoming BYE). - * @public - */ -export declare class Bye { - private incomingByeRequest; - /** @internal */ - constructor(incomingByeRequest: IncomingByeRequest); - /** Incoming BYE request message. */ - get request(): IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=bye.d.ts.map \ No newline at end of file diff --git a/lib/api/bye.d.ts.map b/lib/api/bye.d.ts.map deleted file mode 100644 index 121d3414e..000000000 --- a/lib/api/bye.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye.d.ts","sourceRoot":"","sources":["../../src/api/bye.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEtF;;;GAGG;AACH,qBAAa,GAAG;IAEK,OAAO,CAAC,kBAAkB;IAD7C,gBAAgB;gBACW,kBAAkB,EAAE,kBAAkB;IAEjE,oCAAoC;IACpC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/bye.js b/lib/api/bye.js deleted file mode 100644 index 87b919f7c..000000000 --- a/lib/api/bye.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A request to end a {@link Session} (incoming BYE). - * @public - */ -export class Bye { - /** @internal */ - constructor(incomingByeRequest) { - this.incomingByeRequest = incomingByeRequest; - } - /** Incoming BYE request message. */ - get request() { - return this.incomingByeRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingByeRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingByeRequest.reject(options); - return Promise.resolve(); - } -} diff --git a/lib/api/dtmf.d.ts b/lib/api/dtmf.d.ts deleted file mode 100644 index ae952ab34..000000000 --- a/lib/api/dtmf.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { IncomingInfoRequest } from "../core"; -import { Info } from "./info"; -/** - * A DTMF signal (incoming INFO). - * @deprecated Use `Info`. - * @internal - */ -export declare class DTMF extends Info { - private _tone; - private _duration; - /** @internal */ - constructor(incomingInfoRequest: IncomingInfoRequest, tone: string, duration: number); - get tone(): string; - get duration(): number; -} -//# sourceMappingURL=dtmf.d.ts.map \ No newline at end of file diff --git a/lib/api/dtmf.d.ts.map b/lib/api/dtmf.d.ts.map deleted file mode 100644 index fd9a3e2c0..000000000 --- a/lib/api/dtmf.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dtmf.d.ts","sourceRoot":"","sources":["../../src/api/dtmf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE9B;;;;GAIG;AACH,qBAAa,IAAK,SAAQ,IAAI;IAC5B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,SAAS,CAAS;IAE1B,gBAAgB;gBACG,mBAAmB,EAAE,mBAAmB,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAM3F,IAAW,IAAI,IAAI,MAAM,CAExB;IAED,IAAW,QAAQ,IAAI,MAAM,CAE5B;CACF"} \ No newline at end of file diff --git a/lib/api/dtmf.js b/lib/api/dtmf.js deleted file mode 100644 index 28b161d7f..000000000 --- a/lib/api/dtmf.js +++ /dev/null @@ -1,20 +0,0 @@ -import { Info } from "./info"; -/** - * A DTMF signal (incoming INFO). - * @deprecated Use `Info`. - * @internal - */ -export class DTMF extends Info { - /** @internal */ - constructor(incomingInfoRequest, tone, duration) { - super(incomingInfoRequest); - this._tone = tone; - this._duration = duration; - } - get tone() { - return this._tone; - } - get duration() { - return this._duration; - } -} diff --git a/lib/api/emitter.d.ts b/lib/api/emitter.d.ts deleted file mode 100644 index 97968c2e3..000000000 --- a/lib/api/emitter.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Generic observable. - * @public - */ -export interface Emitter { - /** - * Sets up a function that will be called whenever the target changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addListener(listener: (data: T) => void, options?: { - once?: boolean; - }): void; - /** - * Removes from the listener previously registered with addListener. - * @param listener - Callback function. - */ - removeListener(listener: (data: T) => void): void; - /** - * Registers a listener. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - on(listener: (data: T) => void): void; - /** - * Unregisters a listener. - * @param listener - Callback function. - * @deprecated Use removeListener. - */ - off(listener: (data: T) => void): void; - /** - * Registers a listener then unregisters the listener after one event emission. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - once(listener: (data: T) => void): void; -} -/** - * An {@link Emitter} implementation. - * @internal - */ -export declare class EmitterImpl implements Emitter { - private listeners; - /** - * Sets up a function that will be called whenever the target changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addListener(listener: (data: T) => void, options?: { - once?: boolean; - }): void; - /** - * Emit change. - * @param data - Data to emit. - */ - emit(data: T): void; - /** - * Removes all listeners previously registered with addListener. - */ - removeAllListeners(): void; - /** - * Removes a listener previously registered with addListener. - * @param listener - Callback function. - */ - removeListener(listener: (data: T) => void): void; - /** - * Registers a listener. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - on(listener: (data: T) => void): void; - /** - * Unregisters a listener. - * @param listener - Callback function. - * @deprecated Use removeListener. - */ - off(listener: (data: T) => void): void; - /** - * Registers a listener then unregisters the listener after one event emission. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - once(listener: (data: T) => void): void; -} -//# sourceMappingURL=emitter.d.ts.map \ No newline at end of file diff --git a/lib/api/emitter.d.ts.map b/lib/api/emitter.d.ts.map deleted file mode 100644 index 75bed8d6f..000000000 --- a/lib/api/emitter.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"emitter.d.ts","sourceRoot":"","sources":["../../src/api/emitter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,OAAO,CAAC,CAAC;IACxB;;;;;;OAMG;IACH,WAAW,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;IAC7E;;;OAGG;IACH,cAAc,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IAClD;;;;OAIG;IACH,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IACtC;;;;OAIG;IACH,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;IACvC;;;;OAIG;IACH,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI,CAAC;CACzC;AAED;;;GAGG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,YAAW,OAAO,CAAC,CAAC,CAAC;IAC/C,OAAO,CAAC,SAAS,CAAkC;IAEnD;;;;;;OAMG;IACI,WAAW,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;IAQnF;;;OAGG;IACI,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,IAAI;IAI1B;;OAEG;IACI,kBAAkB,IAAI,IAAI;IAIjC;;;OAGG;IACI,cAAc,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;IAIxD;;;;OAIG;IACI,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;IAI5C;;;;OAIG;IACI,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;IAI7C;;;;OAIG;IACI,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,GAAG,IAAI;CAG/C"} \ No newline at end of file diff --git a/lib/api/emitter.js b/lib/api/emitter.js deleted file mode 100644 index c3470c4ec..000000000 --- a/lib/api/emitter.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * An {@link Emitter} implementation. - * @internal - */ -export class EmitterImpl { - constructor() { - this.listeners = new Array(); - } - /** - * Sets up a function that will be called whenever the target changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addListener(listener, options) { - const onceWrapper = (data) => { - this.removeListener(onceWrapper); - listener(data); - }; - (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); - } - /** - * Emit change. - * @param data - Data to emit. - */ - emit(data) { - this.listeners.slice().forEach((listener) => listener(data)); - } - /** - * Removes all listeners previously registered with addListener. - */ - removeAllListeners() { - this.listeners = []; - } - /** - * Removes a listener previously registered with addListener. - * @param listener - Callback function. - */ - removeListener(listener) { - this.listeners = this.listeners.filter((l) => l !== listener); - } - /** - * Registers a listener. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - on(listener) { - return this.addListener(listener); - } - /** - * Unregisters a listener. - * @param listener - Callback function. - * @deprecated Use removeListener. - */ - off(listener) { - return this.removeListener(listener); - } - /** - * Registers a listener then unregisters the listener after one event emission. - * @param listener - Callback function. - * @deprecated Use addListener. - */ - once(listener) { - return this.addListener(listener, { once: true }); - } -} diff --git a/lib/api/exceptions/content-type-unsupported.d.ts b/lib/api/exceptions/content-type-unsupported.d.ts deleted file mode 100644 index 386826e0c..000000000 --- a/lib/api/exceptions/content-type-unsupported.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating an unsupported content type prevented execution. - * @public - */ -export declare class ContentTypeUnsupportedError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=content-type-unsupported.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/content-type-unsupported.d.ts.map b/lib/api/exceptions/content-type-unsupported.d.ts.map deleted file mode 100644 index 0d3bfbb8d..000000000 --- a/lib/api/exceptions/content-type-unsupported.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"content-type-unsupported.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/content-type-unsupported.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,2BAA4B,SAAQ,SAAS;gBACrC,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/content-type-unsupported.js b/lib/api/exceptions/content-type-unsupported.js deleted file mode 100644 index 705325bb4..000000000 --- a/lib/api/exceptions/content-type-unsupported.js +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating an unsupported content type prevented execution. - * @public - */ -export class ContentTypeUnsupportedError extends Exception { - constructor(message) { - super(message ? message : "Unsupported content type."); - } -} diff --git a/lib/api/exceptions/index.d.ts b/lib/api/exceptions/index.d.ts deleted file mode 100644 index 658d1660e..000000000 --- a/lib/api/exceptions/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from "./content-type-unsupported"; -export * from "./request-pending"; -export * from "./session-description-handler"; -export * from "./session-terminated"; -export * from "./state-transition"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/index.d.ts.map b/lib/api/exceptions/index.d.ts.map deleted file mode 100644 index 93e3ddca1..000000000 --- a/lib/api/exceptions/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mBAAmB,CAAC;AAClC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC"} \ No newline at end of file diff --git a/lib/api/exceptions/index.js b/lib/api/exceptions/index.js deleted file mode 100644 index aea43f163..000000000 --- a/lib/api/exceptions/index.js +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./content-type-unsupported"; -export * from "./request-pending"; -export * from "./session-description-handler"; -export * from "./session-terminated"; -export * from "./state-transition"; diff --git a/lib/api/exceptions/request-pending.d.ts b/lib/api/exceptions/request-pending.d.ts deleted file mode 100644 index ce12eb574..000000000 --- a/lib/api/exceptions/request-pending.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating an outstanding prior request prevented execution. - * @public - */ -export declare class RequestPendingError extends Exception { - /** @internal */ - constructor(message?: string); -} -//# sourceMappingURL=request-pending.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/request-pending.d.ts.map b/lib/api/exceptions/request-pending.d.ts.map deleted file mode 100644 index 503a9dcff..000000000 --- a/lib/api/exceptions/request-pending.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"request-pending.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/request-pending.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,SAAS;IAChD,gBAAgB;gBACG,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/request-pending.js b/lib/api/exceptions/request-pending.js deleted file mode 100644 index 415fd6985..000000000 --- a/lib/api/exceptions/request-pending.js +++ /dev/null @@ -1,11 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating an outstanding prior request prevented execution. - * @public - */ -export class RequestPendingError extends Exception { - /** @internal */ - constructor(message) { - super(message ? message : "Request pending."); - } -} diff --git a/lib/api/exceptions/session-description-handler.d.ts b/lib/api/exceptions/session-description-handler.d.ts deleted file mode 100644 index 8bb15d10e..000000000 --- a/lib/api/exceptions/session-description-handler.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating a session description handler error occured. - * @public - */ -export declare class SessionDescriptionHandlerError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/session-description-handler.d.ts.map b/lib/api/exceptions/session-description-handler.d.ts.map deleted file mode 100644 index 185c078c6..000000000 --- a/lib/api/exceptions/session-description-handler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/session-description-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,8BAA+B,SAAQ,SAAS;gBACxC,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/session-description-handler.js b/lib/api/exceptions/session-description-handler.js deleted file mode 100644 index 2f62ac9ea..000000000 --- a/lib/api/exceptions/session-description-handler.js +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating a session description handler error occured. - * @public - */ -export class SessionDescriptionHandlerError extends Exception { - constructor(message) { - super(message ? message : "Unspecified session description handler error."); - } -} diff --git a/lib/api/exceptions/session-terminated.d.ts b/lib/api/exceptions/session-terminated.d.ts deleted file mode 100644 index fc76671bf..000000000 --- a/lib/api/exceptions/session-terminated.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating the session terminated before the action completed. - * @public - */ -export declare class SessionTerminatedError extends Exception { - constructor(); -} -//# sourceMappingURL=session-terminated.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/session-terminated.d.ts.map b/lib/api/exceptions/session-terminated.d.ts.map deleted file mode 100644 index e8b222bbe..000000000 --- a/lib/api/exceptions/session-terminated.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-terminated.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/session-terminated.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,SAAS;;CAIpD"} \ No newline at end of file diff --git a/lib/api/exceptions/session-terminated.js b/lib/api/exceptions/session-terminated.js deleted file mode 100644 index 1dc9d862d..000000000 --- a/lib/api/exceptions/session-terminated.js +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating the session terminated before the action completed. - * @public - */ -export class SessionTerminatedError extends Exception { - constructor() { - super("The session has terminated."); - } -} diff --git a/lib/api/exceptions/state-transition.d.ts b/lib/api/exceptions/state-transition.d.ts deleted file mode 100644 index b60bdb000..000000000 --- a/lib/api/exceptions/state-transition.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating an invalid state transition error occured. - * @public - */ -export declare class StateTransitionError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=state-transition.d.ts.map \ No newline at end of file diff --git a/lib/api/exceptions/state-transition.d.ts.map b/lib/api/exceptions/state-transition.d.ts.map deleted file mode 100644 index a75b1a256..000000000 --- a/lib/api/exceptions/state-transition.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"state-transition.d.ts","sourceRoot":"","sources":["../../../src/api/exceptions/state-transition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;gBAC9B,OAAO,CAAC,EAAE,MAAM;CAGpC"} \ No newline at end of file diff --git a/lib/api/exceptions/state-transition.js b/lib/api/exceptions/state-transition.js deleted file mode 100644 index 3ba45265c..000000000 --- a/lib/api/exceptions/state-transition.js +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "../../core"; -/** - * An exception indicating an invalid state transition error occured. - * @public - */ -export class StateTransitionError extends Exception { - constructor(message) { - super(message ? message : "An error occurred during state transition."); - } -} diff --git a/lib/api/index.d.ts b/lib/api/index.d.ts deleted file mode 100644 index c312ee698..000000000 --- a/lib/api/index.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. - * @packageDocumentation - */ -export * from "./exceptions"; -export * from "./bye"; -export * from "./emitter"; -export * from "./info"; -export * from "./invitation-accept-options"; -export * from "./invitation-progress-options"; -export * from "./invitation-reject-options"; -export * from "./invitation"; -export * from "./inviter-cancel-options"; -export * from "./inviter-invite-options"; -export * from "./inviter-options"; -export * from "./inviter"; -export * from "./message"; -export * from "./messager-message-options"; -export * from "./messager-options"; -export * from "./messager"; -export * from "./notification"; -export * from "./publisher-options"; -export * from "./publisher-publish-options"; -export * from "./publisher-state"; -export * from "./publisher-unpublish-options"; -export * from "./publisher"; -export * from "./referral"; -export * from "./registerer-options"; -export * from "./registerer-register-options"; -export * from "./registerer-state"; -export * from "./registerer-unregister-options"; -export * from "./registerer"; -export * from "./session-bye-options"; -export * from "./session-delegate"; -export * from "./session-description-handler-factory"; -export * from "./session-description-handler"; -export * from "./session-info-options"; -export * from "./session-invite-options"; -export * from "./session-message-options"; -export * from "./session-options"; -export * from "./session-refer-options"; -export * from "./session-state"; -export * from "./session"; -export * from "./subscriber-options"; -export * from "./subscriber-subscribe-options"; -export * from "./subscriber"; -export * from "./subscription-delegate"; -export * from "./subscription-options"; -export * from "./subscription-state"; -export * from "./subscription-subscribe-options"; -export * from "./subscription-unsubscribe-options"; -export * from "./subscription"; -export * from "./transport"; -export * from "./transport-state"; -export * from "./user-agent-delegate"; -export * from "./user-agent-options"; -export * from "./user-agent-state"; -export * from "./user-agent"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/api/index.d.ts.map b/lib/api/index.d.ts.map deleted file mode 100644 index 323f79b18..000000000 --- a/lib/api/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC;AACtB,cAAc,WAAW,CAAC;AAC1B,cAAc,QAAQ,CAAC;AACvB,cAAc,6BAA6B,CAAC;AAC5C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,cAAc,CAAC;AAC7B,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,mBAAmB,CAAC;AAClC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,sBAAsB,CAAC;AACrC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,oBAAoB,CAAC;AACnC,cAAc,iCAAiC,CAAC;AAChD,cAAc,cAAc,CAAC;AAC7B,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,uCAAuC,CAAC;AACtD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,cAAc,CAAC;AAC7B,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,kCAAkC,CAAC;AACjD,cAAc,oCAAoC,CAAC;AACnD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/lib/api/index.js b/lib/api/index.js deleted file mode 100644 index 88daf1474..000000000 --- a/lib/api/index.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * A simple yet powerful API which takes care of SIP signaling and WebRTC media sessions for you. - * @packageDocumentation - */ -export * from "./exceptions"; -export * from "./bye"; -export * from "./emitter"; -export * from "./info"; -export * from "./invitation-accept-options"; -export * from "./invitation-progress-options"; -export * from "./invitation-reject-options"; -export * from "./invitation"; -export * from "./inviter-cancel-options"; -export * from "./inviter-invite-options"; -export * from "./inviter-options"; -export * from "./inviter"; -export * from "./message"; -export * from "./messager-message-options"; -export * from "./messager-options"; -export * from "./messager"; -export * from "./notification"; -export * from "./publisher-options"; -export * from "./publisher-publish-options"; -export * from "./publisher-state"; -export * from "./publisher-unpublish-options"; -export * from "./publisher"; -export * from "./referral"; -export * from "./registerer-options"; -export * from "./registerer-register-options"; -export * from "./registerer-state"; -export * from "./registerer-unregister-options"; -export * from "./registerer"; -export * from "./session-bye-options"; -export * from "./session-delegate"; -export * from "./session-description-handler-factory"; -export * from "./session-description-handler"; -export * from "./session-info-options"; -export * from "./session-invite-options"; -export * from "./session-message-options"; -export * from "./session-options"; -export * from "./session-refer-options"; -export * from "./session-state"; -export * from "./session"; -export * from "./subscriber-options"; -export * from "./subscriber-subscribe-options"; -export * from "./subscriber"; -export * from "./subscription-delegate"; -export * from "./subscription-options"; -export * from "./subscription-state"; -export * from "./subscription-subscribe-options"; -export * from "./subscription-unsubscribe-options"; -export * from "./subscription"; -export * from "./transport"; -export * from "./transport-state"; -export * from "./user-agent-delegate"; -export * from "./user-agent-options"; -export * from "./user-agent-state"; -export * from "./user-agent"; diff --git a/lib/api/info.d.ts b/lib/api/info.d.ts deleted file mode 100644 index 9305dbe6e..000000000 --- a/lib/api/info.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingInfoRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * An exchange of information (incoming INFO). - * @public - */ -export declare class Info { - private incomingInfoRequest; - /** @internal */ - constructor(incomingInfoRequest: IncomingInfoRequest); - /** Incoming MESSAGE request message. */ - get request(): IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=info.d.ts.map \ No newline at end of file diff --git a/lib/api/info.d.ts.map b/lib/api/info.d.ts.map deleted file mode 100644 index 6f6c26905..000000000 --- a/lib/api/info.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../src/api/info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEvF;;;GAGG;AACH,qBAAa,IAAI;IAEI,OAAO,CAAC,mBAAmB;IAD9C,gBAAgB;gBACW,mBAAmB,EAAE,mBAAmB;IAEnE,wCAAwC;IACxC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/info.js b/lib/api/info.js deleted file mode 100644 index 1929cc08d..000000000 --- a/lib/api/info.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * An exchange of information (incoming INFO). - * @public - */ -export class Info { - /** @internal */ - constructor(incomingInfoRequest) { - this.incomingInfoRequest = incomingInfoRequest; - } - /** Incoming MESSAGE request message. */ - get request() { - return this.incomingInfoRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingInfoRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingInfoRequest.reject(options); - return Promise.resolve(); - } -} diff --git a/lib/api/invitation-accept-options.d.ts b/lib/api/invitation-accept-options.d.ts deleted file mode 100644 index 341908975..000000000 --- a/lib/api/invitation-accept-options.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Invitation.accept}. - * @public - */ -export interface InvitationAcceptOptions { - /** - * Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. - */ - sessionDescriptionHandlerModifiers?: Array; - /** - * Options to pass to SessionDescriptionHandler during the initial INVITE transaction. - */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; -} -//# sourceMappingURL=invitation-accept-options.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation-accept-options.d.ts.map b/lib/api/invitation-accept-options.d.ts.map deleted file mode 100644 index 4a690a2f3..000000000 --- a/lib/api/invitation-accept-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation-accept-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-accept-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;CACrE"} \ No newline at end of file diff --git a/lib/api/invitation-accept-options.js b/lib/api/invitation-accept-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/invitation-progress-options.d.ts b/lib/api/invitation-progress-options.d.ts deleted file mode 100644 index 67d19dbc6..000000000 --- a/lib/api/invitation-progress-options.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Invitation.progress}. - * @public - */ -export interface InvitationProgressOptions { - /** - * Body - */ - body?: string | { - body: string; - contentType: string; - }; - /** - * Array of extra headers added to the response. - */ - extraHeaders?: Array; - /** - * Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. - */ - sessionDescriptionHandlerModifiers?: Array; - /** - * Options to pass to SessionDescriptionHandler during the initial INVITE transaction. - */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** - * Status code for response. - */ - statusCode?: number; - /** - * Reason phrase for response. - */ - reasonPhrase?: string; - /** - * Send reliable response. - */ - rel100?: boolean; -} -//# sourceMappingURL=invitation-progress-options.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation-progress-options.d.ts.map b/lib/api/invitation-progress-options.d.ts.map deleted file mode 100644 index f18712a02..000000000 --- a/lib/api/invitation-progress-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation-progress-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-progress-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB"} \ No newline at end of file diff --git a/lib/api/invitation-progress-options.js b/lib/api/invitation-progress-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/invitation-reject-options.d.ts b/lib/api/invitation-reject-options.d.ts deleted file mode 100644 index 98221ac8c..000000000 --- a/lib/api/invitation-reject-options.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Options for {@link Invitation.reject}. - * @public - */ -export interface InvitationRejectOptions { - /** - * Body - */ - body?: string | { - body: string; - contentType: string; - }; - /** - * Array of extra headers added to the response. - */ - extraHeaders?: Array; - /** - * Status code for response. - */ - statusCode?: number; - /** - * Reason phrase for response. - */ - reasonPhrase?: string; -} -//# sourceMappingURL=invitation-reject-options.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation-reject-options.d.ts.map b/lib/api/invitation-reject-options.d.ts.map deleted file mode 100644 index 69c351da8..000000000 --- a/lib/api/invitation-reject-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation-reject-options.d.ts","sourceRoot":"","sources":["../../src/api/invitation-reject-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB"} \ No newline at end of file diff --git a/lib/api/invitation-reject-options.js b/lib/api/invitation-reject-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/invitation.d.ts b/lib/api/invitation.d.ts deleted file mode 100644 index 2a93a2eb4..000000000 --- a/lib/api/invitation.d.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { IncomingInviteRequest, IncomingRequestMessage, Logger, NameAddrHeader } from "../core"; -import { InvitationAcceptOptions } from "./invitation-accept-options"; -import { InvitationProgressOptions } from "./invitation-progress-options"; -import { InvitationRejectOptions } from "./invitation-reject-options"; -import { Session } from "./session"; -import { UserAgent } from "./user-agent"; -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -export declare class Invitation extends Session { - private incomingInviteRequest; - /** - * Logger. - */ - protected logger: Logger; - /** @internal */ - protected _id: string; - /** True if dispose() has been called. */ - private disposed; - /** INVITE will be rejected if not accepted within a certain period time. */ - private expiresTimer; - /** True if this Session has been Terminated due to a CANCEL request. */ - private isCanceled; - /** Are reliable provisional responses required or supported. */ - private rel100; - /** The current RSeq header value. */ - private rseq; - /** INVITE will be rejected if final response not sent in a certain period time. */ - private userNoAnswerTimer; - /** True if waiting for a PRACK before sending a 200 Ok. */ - private waitingForPrack; - /** A Promise providing a defer when waiting for a PRACK. */ - private waitingForPrackPromise; - /** Function to resolve when PRACK arrives. */ - private waitingForPrackResolve; - /** Function to reject when PRACK never arrives. */ - private waitingForPrackReject; - /** @internal */ - constructor(userAgent: UserAgent, incomingInviteRequest: IncomingInviteRequest); - /** - * Destructor. - */ - dispose(): Promise; - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - get autoSendAnInitialProvisionalResponse(): boolean; - /** - * Initial incoming INVITE request message body. - */ - get body(): string | undefined; - /** - * The identity of the local user. - */ - get localIdentity(): NameAddrHeader; - /** - * The identity of the remote user. - */ - get remoteIdentity(): NameAddrHeader; - /** - * Initial incoming INVITE request message. - */ - get request(): IncomingRequestMessage; - /** - * Accept the invitation. - * - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * Resolves once the response sent, otherwise rejects. - * - * This method may reject for a variety of reasons including - * the receipt of a CANCEL request before `accept` is able - * to construct a response. - * @param options - Options bucket. - */ - accept(options?: InvitationAcceptOptions): Promise; - /** - * Indicate progress processing the invitation. - * - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * Resolves once the response sent, otherwise rejects. - * @param options - Options bucket. - */ - progress(options?: InvitationProgressOptions): Promise; - /** - * Reject the invitation. - * - * @remarks - * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. - * Resolves once the response sent, otherwise rejects. - * - * The expectation is that this method is used to reject an INVITE request. - * That is indeed the case - a call to `progress` followed by `reject` is - * a typical way to "decline" an incoming INVITE request. However it may - * also be called after calling `accept` (but only before it completes) - * which will reject the call and cause `accept` to reject. - * @param options - Options bucket. - */ - reject(options?: InvitationRejectOptions): Promise; - /** - * Handle CANCEL request. - * - * @param message - CANCEL message. - * @internal - */ - _onCancel(message: IncomingRequestMessage): void; - /** - * Helper function to handle offer/answer in a PRACK. - */ - private handlePrackOfferAnswer; - /** - * A handler for errors which occur while attempting to send 1xx and 2xx responses. - * In all cases, an attempt is made to reject the request if it is still outstanding. - * And while there are a variety of things which can go wrong and we log something here - * for all errors, there are a handful of common exceptions we pay some extra attention to. - * @param error - The error which occurred. - */ - private handleResponseError; - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - private onAckTimeout; - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - private sendAccept; - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - private sendProgress; - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - private sendProgressWithSDP; - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - private sendProgressReliable; - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - private sendProgressReliableWaitForPrack; - /** - * A version of `progress` which resolves when a 100 Trying provisional response is sent. - */ - private sendProgressTrying; - /** - * When attempting to accept the INVITE, an invitation waits - * for any outstanding PRACK to arrive before sending the 200 Ok. - * It will be waiting on this Promise to resolve which lets it know - * the PRACK has arrived and it may proceed to send the 200 Ok. - */ - private waitForArrivalOfPrack; - /** - * Here we are resolving the promise which in turn will cause - * the accept to proceed (it may still fail for other reasons, but...). - */ - private prackArrived; - /** - * Here we are rejecting the promise which in turn will cause - * the accept to fail and the session to transition to "terminated". - */ - private prackNeverArrived; -} -//# sourceMappingURL=invitation.d.ts.map \ No newline at end of file diff --git a/lib/api/invitation.d.ts.map b/lib/api/invitation.d.ts.map deleted file mode 100644 index 5f5c269c3..000000000 --- a/lib/api/invitation.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invitation.d.ts","sourceRoot":"","sources":["../../src/api/invitation.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,qBAAqB,EAErB,sBAAsB,EAEtB,MAAM,EACN,cAAc,EAMf,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAMzC;;;GAGG;AACH,qBAAa,UAAW,SAAQ,OAAO;IA+BI,OAAO,CAAC,qBAAqB;IA9BtE;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,gBAAgB;IAChB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC;IAEtB,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAS;IACzB,4EAA4E;IAC5E,OAAO,CAAC,YAAY,CAAiC;IACrD,wEAAwE;IACxE,OAAO,CAAC,UAAU,CAAS;IAC3B,gEAAgE;IAChE,OAAO,CAAC,MAAM,CAA6C;IAC3D,qCAAqC;IACrC,OAAO,CAAC,IAAI,CAAqC;IACjD,mFAAmF;IACnF,OAAO,CAAC,iBAAiB,CAAiC;IAC1D,2DAA2D;IAC3D,OAAO,CAAC,eAAe,CAAS;IAChC,4DAA4D;IAC5D,OAAO,CAAC,sBAAsB,CAA4B;IAC1D,8CAA8C;IAC9C,OAAO,CAAC,sBAAsB,CAA8B;IAC5D,mDAAmD;IACnD,OAAO,CAAC,qBAAqB,CAA6B;IAE1D,gBAAgB;gBACG,SAAS,EAAE,SAAS,EAAU,qBAAqB,EAAE,qBAAqB;IA6E7F;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC/B;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAW,oCAAoC,IAAI,OAAO,CAEzD;IAED;;OAEG;IACH,IAAW,IAAI,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,cAAc,CAEzC;IAED;;OAEG;IACH,IAAW,cAAc,IAAI,cAAc,CAE1C;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED;;;;;;;;;;;;OAYG;IACI,MAAM,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IAiDnE;;;;;;;;OAQG;IACI,QAAQ,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;IAsEvE;;;;;;;;;;;;;OAaG;IACI,MAAM,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IA+BnE;;;;;OAKG;IAEI,SAAS,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAkBvD;;OAEG;IACH,OAAO,CAAC,sBAAsB;IA4C9B;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB;IA0D3B;;;OAGG;IACH,OAAO,CAAC,YAAY;IAUpB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAgClB;;;OAGG;IACH,OAAO,CAAC,YAAY;IA2BpB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAkB3B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAO5B;;;OAGG;IACH,OAAO,CAAC,gCAAgC;IA4FxC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAS1B;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAW7B;;;OAGG;IACH,OAAO,CAAC,YAAY;IASpB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;CAQ1B"} \ No newline at end of file diff --git a/lib/api/invitation.js b/lib/api/invitation.js deleted file mode 100644 index 3b5741354..000000000 --- a/lib/api/invitation.js +++ /dev/null @@ -1,708 +0,0 @@ -import { fromBodyLegacy, getBody, Grammar, SignalingState, Timers, TransactionStateError } from "../core"; -import { getReasonPhrase } from "../core/messages/utils"; -import { ContentTypeUnsupportedError, SessionDescriptionHandlerError, SessionTerminatedError } from "./exceptions"; -import { Session } from "./session"; -import { SessionState } from "./session-state"; -import { SIPExtension } from "./user-agent-options"; -/** - * An invitation is an offer to establish a {@link Session} (incoming INVITE). - * @public - */ -export class Invitation extends Session { - /** @internal */ - constructor(userAgent, incomingInviteRequest) { - super(userAgent); - this.incomingInviteRequest = incomingInviteRequest; - /** True if dispose() has been called. */ - this.disposed = false; - /** INVITE will be rejected if not accepted within a certain period time. */ - this.expiresTimer = undefined; - /** True if this Session has been Terminated due to a CANCEL request. */ - this.isCanceled = false; - /** Are reliable provisional responses required or supported. */ - this.rel100 = "none"; - /** The current RSeq header value. */ - this.rseq = Math.floor(Math.random() * 10000); - /** INVITE will be rejected if final response not sent in a certain period time. */ - this.userNoAnswerTimer = undefined; - /** True if waiting for a PRACK before sending a 200 Ok. */ - this.waitingForPrack = false; - this.logger = userAgent.getLogger("sip.Invitation"); - const incomingRequestMessage = this.incomingInviteRequest.message; - // Set 100rel if necessary - const requireHeader = incomingRequestMessage.getHeader("require"); - if (requireHeader && requireHeader.toLowerCase().includes("100rel")) { - this.rel100 = "required"; - } - const supportedHeader = incomingRequestMessage.getHeader("supported"); - if (supportedHeader && supportedHeader.toLowerCase().includes("100rel")) { - this.rel100 = "supported"; - } - // FIXME: HACK: This is a hack to port an existing behavior. - // Set the toTag on the incoming request message to the toTag which - // will be used in the response to the incoming request!!! - // The behavior being ported appears to be a hack itself, - // so this is a hack to port a hack. At least one test spec - // relies on it (which is yet another hack). - // eslint-disable-next-line @typescript-eslint/no-explicit-any - incomingRequestMessage.toTag = incomingInviteRequest.toTag; - if (typeof incomingRequestMessage.toTag !== "string") { - throw new TypeError("toTag should have been a string."); - } - // The following mapping values are RECOMMENDED: - // ... - // 19 no answer from the user 480 Temporarily unavailable - // https://tools.ietf.org/html/rfc3398#section-7.2.4.1 - this.userNoAnswerTimer = setTimeout(() => { - incomingInviteRequest.reject({ statusCode: 480 }); - this.stateTransition(SessionState.Terminated); - }, this.userAgent.configuration.noAnswerTimeout ? this.userAgent.configuration.noAnswerTimeout * 1000 : 60000); - // 1. If the request is an INVITE that contains an Expires header - // field, the UAS core sets a timer for the number of seconds - // indicated in the header field value. When the timer fires, the - // invitation is considered to be expired. If the invitation - // expires before the UAS has generated a final response, a 487 - // (Request Terminated) response SHOULD be generated. - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - if (incomingRequestMessage.hasHeader("expires")) { - const expires = Number(incomingRequestMessage.getHeader("expires") || 0) * 1000; - this.expiresTimer = setTimeout(() => { - if (this.state === SessionState.Initial) { - incomingInviteRequest.reject({ statusCode: 487 }); - this.stateTransition(SessionState.Terminated); - } - }, expires); - } - // Session parent properties - const assertedIdentity = this.request.getHeader("P-Asserted-Identity"); - if (assertedIdentity) { - this._assertedIdentity = Grammar.nameAddrHeaderParse(assertedIdentity); - } - this._contact = this.userAgent.contact.toString(); - const contentDisposition = incomingRequestMessage.parseHeader("Content-Disposition"); - if (contentDisposition && contentDisposition.type === "render") { - this._renderbody = incomingRequestMessage.body; - this._rendertype = incomingRequestMessage.getHeader("Content-Type"); - } - // Identifier - this._id = incomingRequestMessage.callId + incomingRequestMessage.fromTag; - // Add to the user agent's session collection. - this.userAgent._sessions[this._id] = this; - } - /** - * Destructor. - */ - dispose() { - // Only run through this once. It can and does get called multiple times - // depending on the what the sessions state is when first called. - // For example, if called when "establishing" it will be called again - // at least once when the session transitions to "terminated". - // Regardless, running through this more than once is pointless. - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - // Clear timers - if (this.expiresTimer) { - clearTimeout(this.expiresTimer); - this.expiresTimer = undefined; - } - if (this.userNoAnswerTimer) { - clearTimeout(this.userNoAnswerTimer); - this.userNoAnswerTimer = undefined; - } - // If accept() is still waiting for a PRACK, make sure it rejects - this.prackNeverArrived(); - // If the final response for the initial INVITE not yet been sent, reject it - switch (this.state) { - case SessionState.Initial: - return this.reject().then(() => super.dispose()); - case SessionState.Establishing: - return this.reject().then(() => super.dispose()); - case SessionState.Established: - return super.dispose(); - case SessionState.Terminating: - return super.dispose(); - case SessionState.Terminated: - return super.dispose(); - default: - throw new Error("Unknown state."); - } - } - /** - * If true, a first provisional response after the 100 Trying - * will be sent automatically. This is false it the UAC required - * reliable provisional responses (100rel in Require header), - * otherwise it is true. The provisional is sent by calling - * `progress()` without any options. - * - * FIXME: TODO: It seems reasonable that the ISC user should - * be able to optionally disable this behavior. As the provisional - * is sent prior to the "invite" event being emitted, it's a known - * issue that the ISC user cannot register listeners or do any other - * setup prior to the call to `progress()`. As an example why this is - * an issue, setting `ua.configuration.rel100` to REQUIRED will result - * in an attempt by `progress()` to send a 183 with SDP produced by - * calling `getDescription()` on a session description handler, but - * the ISC user cannot perform any potentially required session description - * handler initialization (thus preventing the utilization of setting - * `ua.configuration.rel100` to REQUIRED). That begs the question of - * why this behavior is disabled when the UAC requires 100rel but not - * when the UAS requires 100rel? But ignoring that, it's just one example - * of a class of cases where the ISC user needs to do something prior - * to the first call to `progress()` and is unable to do so. - * @internal - */ - get autoSendAnInitialProvisionalResponse() { - return this.rel100 === "required" ? false : true; - } - /** - * Initial incoming INVITE request message body. - */ - get body() { - return this.incomingInviteRequest.message.body; - } - /** - * The identity of the local user. - */ - get localIdentity() { - return this.request.to; - } - /** - * The identity of the remote user. - */ - get remoteIdentity() { - return this.request.from; - } - /** - * Initial incoming INVITE request message. - */ - get request() { - return this.incomingInviteRequest.message; - } - /** - * Accept the invitation. - * - * @remarks - * Accept the incoming INVITE request to start a Session. - * Replies to the INVITE request with a 200 Ok response. - * Resolves once the response sent, otherwise rejects. - * - * This method may reject for a variety of reasons including - * the receipt of a CANCEL request before `accept` is able - * to construct a response. - * @param options - Options bucket. - */ - accept(options = {}) { - this.logger.log("Invitation.accept"); - // validate state - if (this.state !== SessionState.Initial) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // transition state - this.stateTransition(SessionState.Establishing); - return (this.sendAccept() - // eslint-disable-next-line @typescript-eslint/no-unused-vars - .then(({ message, session }) => { - session.delegate = { - onAck: (ackRequest) => this.onAckRequest(ackRequest), - onAckTimeout: () => this.onAckTimeout(), - onBye: (byeRequest) => this.onByeRequest(byeRequest), - onInfo: (infoRequest) => this.onInfoRequest(infoRequest), - onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), - onMessage: (messageRequest) => this.onMessageRequest(messageRequest), - onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), - onPrack: (prackRequest) => this.onPrackRequest(prackRequest), - onRefer: (referRequest) => this.onReferRequest(referRequest) - }; - this._dialog = session; - this.stateTransition(SessionState.Established); - // TODO: Reconsider this "automagic" send of a BYE to replacee behavior. - // This behavior has been ported forward from legacy versions. - if (this._replacee) { - this._replacee._bye(); - } - }) - .catch((error) => this.handleResponseError(error))); - } - /** - * Indicate progress processing the invitation. - * - * @remarks - * Report progress to the the caller. - * Replies to the INVITE request with a 1xx provisional response. - * Resolves once the response sent, otherwise rejects. - * @param options - Options bucket. - */ - progress(options = {}) { - this.logger.log("Invitation.progress"); - // validate state - if (this.state !== SessionState.Initial) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // Ported - const statusCode = options.statusCode || 180; - if (statusCode < 100 || statusCode > 199) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // After the first reliable provisional response for a request has been - // acknowledged, the UAS MAY send additional reliable provisional - // responses. The UAS MUST NOT send a second reliable provisional - // response until the first is acknowledged. After the first, it is - // RECOMMENDED that the UAS not send an additional reliable provisional - // response until the previous is acknowledged. The first reliable - // provisional response receives special treatment because it conveys - // the initial sequence number. If additional reliable provisional - // responses were sent before the first was acknowledged, the UAS could - // not be certain these were received in order. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.waitingForPrack) { - this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"); - return Promise.resolve(); - } - // Trying provisional response - if (options.statusCode === 100) { - return this.sendProgressTrying() - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - // Standard provisional response - if (!(this.rel100 === "required") && - !(this.rel100 === "supported" && options.rel100) && - !(this.rel100 === "supported" && this.userAgent.configuration.sipExtension100rel === SIPExtension.Required)) { - return this.sendProgress(options) - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - // Reliable provisional response - return this.sendProgressReliableWaitForPrack(options) - .then(() => { - return; - }) - .catch((error) => this.handleResponseError(error)); - } - /** - * Reject the invitation. - * - * @remarks - * Replies to the INVITE request with a 4xx, 5xx, or 6xx final response. - * Resolves once the response sent, otherwise rejects. - * - * The expectation is that this method is used to reject an INVITE request. - * That is indeed the case - a call to `progress` followed by `reject` is - * a typical way to "decline" an incoming INVITE request. However it may - * also be called after calling `accept` (but only before it completes) - * which will reject the call and cause `accept` to reject. - * @param options - Options bucket. - */ - reject(options = {}) { - this.logger.log("Invitation.reject"); - // validate state - if (this.state !== SessionState.Initial && this.state !== SessionState.Establishing) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - const statusCode = options.statusCode || 480; - const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : getReasonPhrase(statusCode); - const extraHeaders = options.extraHeaders || []; - if (statusCode < 300 || statusCode > 699) { - throw new TypeError("Invalid statusCode: " + statusCode); - } - const body = options.body ? fromBodyLegacy(options.body) : undefined; - // FIXME: Need to redirect to someplace - statusCode < 400 - ? this.incomingInviteRequest.redirect([], { statusCode, reasonPhrase, extraHeaders, body }) - : this.incomingInviteRequest.reject({ statusCode, reasonPhrase, extraHeaders, body }); - this.stateTransition(SessionState.Terminated); - return Promise.resolve(); - } - /** - * Handle CANCEL request. - * - * @param message - CANCEL message. - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _onCancel(message) { - this.logger.log("Invitation._onCancel"); - // validate state - if (this.state !== SessionState.Initial && this.state !== SessionState.Establishing) { - this.logger.error(`CANCEL received while in state ${this.state}, dropping request`); - return; - } - // flag canceled - this.isCanceled = true; - // reject INVITE with 487 status code - this.incomingInviteRequest.reject({ statusCode: 487 }); - this.stateTransition(SessionState.Terminated); - } - /** - * Helper function to handle offer/answer in a PRACK. - */ - handlePrackOfferAnswer(request) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - // If the PRACK doesn't have an offer/answer, nothing to be done. - const body = getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return Promise.resolve(undefined); - } - const options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // https://tools.ietf.org/html/rfc3262#section-5 - switch (this.dialog.signalingState) { - case SignalingState.Initial: - // State should never be reached as first reliable provisional response must have answer/offer. - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - case SignalingState.Stable: - // Receved answer. - return this.setAnswer(body, options).then(() => undefined); - case SignalingState.HaveLocalOffer: - // State should never be reached as local offer would be answered by this PRACK - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - case SignalingState.HaveRemoteOffer: - // Received offer, generate answer. - return this.setOfferAndGetAnswer(body, options); - case SignalingState.Closed: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - } - } - /** - * A handler for errors which occur while attempting to send 1xx and 2xx responses. - * In all cases, an attempt is made to reject the request if it is still outstanding. - * And while there are a variety of things which can go wrong and we log something here - * for all errors, there are a handful of common exceptions we pay some extra attention to. - * @param error - The error which occurred. - */ - handleResponseError(error) { - let statusCode = 480; // "Temporarily Unavailable" - // Log Error message - if (error instanceof Error) { - this.logger.error(error.message); - } - else { - // We don't actually know what a session description handler implementation might throw our way, - // and more generally as a last resort catch all, just assume we are getting an "unknown" and log it. - this.logger.error(error); - } - // Log Exception message - if (error instanceof ContentTypeUnsupportedError) { - this.logger.error("A session description handler occurred while sending response (content type unsupported"); - statusCode = 415; // "Unsupported Media Type" - } - else if (error instanceof SessionDescriptionHandlerError) { - this.logger.error("A session description handler occurred while sending response"); - } - else if (error instanceof SessionTerminatedError) { - this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"); - } - else if (error instanceof TransactionStateError) { - this.logger.error("Session changed state before response could be formulated and sent"); - } - // Reject if still in "initial" or "establishing" state. - if (this.state === SessionState.Initial || this.state === SessionState.Establishing) { - try { - this.incomingInviteRequest.reject({ statusCode }); - this.stateTransition(SessionState.Terminated); - } - catch (e) { - this.logger.error("An error occurred attempting to reject the request while handling another error"); - throw e; // This is not a good place to be... - } - } - // FIXME: TODO: - // Here we are squelching the throwing of errors due to an race condition. - // We have an internal race between calling `accept()` and handling an incoming - // CANCEL request. As there is no good way currently to delegate the handling of - // these race errors to the caller of `accept()`, we are squelching the throwing - // of ALL errors when/if they occur after receiving a CANCEL to catch the ONE we know - // is a "normal" exceptional condition. While this is a completely reasonable approach, - // the decision should be left up to the library user. Furthermore, as we are eating - // ALL errors in this case, we are potentially (likely) hiding "real" errors which occur. - // - // Only rethrow error if the session has not been canceled. - if (this.isCanceled) { - this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE." + - " However a CANCEL was received and processed while doing so which can (and often does) result" + - " in errors occurring as the session terminates in the meantime. Said error is being ignored."); - return; - } - throw error; - } - /** - * Callback for when ACK for a 2xx response is never received. - * @param session - Session the ACK never arrived for. - */ - onAckTimeout() { - this.logger.log("Invitation.onAckTimeout"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.log("No ACK received for an extended period of time, terminating session"); - this.dialog.bye(); - this.stateTransition(SessionState.Terminated); - } - /** - * A version of `accept` which resolves a session when the 200 Ok response is sent. - * @param options - Options bucket. - */ - sendAccept() { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - // The UAS MAY send a final response to the initial request before - // having received PRACKs for all unacknowledged reliable provisional - // responses, unless the final response is 2xx and any of the - // unacknowledged reliable provisional responses contained a session - // description. In that case, it MUST NOT send a final response until - // those provisional responses are acknowledged. If the UAS does send a - // final response when reliable responses are still unacknowledged, it - // SHOULD NOT continue to retransmit the unacknowledged reliable - // provisional responses, but it MUST be prepared to process PRACK - // requests for those outstanding responses. A UAS MUST NOT send new - // reliable provisional responses (as opposed to retransmissions of - // unacknowledged ones) after sending a final response to a request. - // https://tools.ietf.org/html/rfc3262#section-3 - if (this.waitingForPrack) { - return this.waitForArrivalOfPrack() - .then(() => clearTimeout(this.userNoAnswerTimer)) // Ported - .then(() => this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions)) - .then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); - } - clearTimeout(this.userNoAnswerTimer); // Ported - return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions).then((body) => this.incomingInviteRequest.accept({ statusCode: 200, body })); - } - /** - * A version of `progress` which resolves when the provisional response is sent. - * @param options - Options bucket. - */ - sendProgress(options = {}) { - const statusCode = options.statusCode || 180; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - const body = options.body ? fromBodyLegacy(options.body) : undefined; - // The 183 (Session Progress) response is used to convey information - // about the progress of the call that is not otherwise classified. The - // Reason-Phrase, header fields, or message body MAY be used to convey - // more details about the call progress. - // https://tools.ietf.org/html/rfc3261#section-21.1.5 - // It is the de facto industry standard to utilize 183 with SDP to provide "early media". - // While it is unlikely someone would want to send a 183 without SDP, so it should be an option. - if (statusCode === 183 && !body) { - return this.sendProgressWithSDP(options); - } - try { - const progressResponse = this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - this._dialog = progressResponse.session; - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - } - /** - * A version of `progress` which resolves when the provisional response with sdp is sent. - * @param options - Options bucket. - */ - sendProgressWithSDP(options = {}) { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - const statusCode = options.statusCode || 183; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - // Get an offer/answer and send a reply. - return this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) - .then((body) => this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body })) - .then((progressResponse) => { - this._dialog = progressResponse.session; - return progressResponse; - }); - } - /** - * A version of `progress` which resolves when the reliable provisional response is sent. - * @param options - Options bucket. - */ - sendProgressReliable(options = {}) { - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push("Require: 100rel"); - options.extraHeaders.push("RSeq: " + Math.floor(Math.random() * 10000)); - return this.sendProgressWithSDP(options); - } - /** - * A version of `progress` which resolves when the reliable provisional response is acknowledged. - * @param options - Options bucket. - */ - sendProgressReliableWaitForPrack(options = {}) { - const responseOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers - }; - const statusCode = options.statusCode || 183; - const reasonPhrase = options.reasonPhrase; - const extraHeaders = (options.extraHeaders || []).slice(); - extraHeaders.push("Require: 100rel"); - extraHeaders.push("RSeq: " + this.rseq++); - let body; - return new Promise((resolve, reject) => { - this.waitingForPrack = true; - this.generateResponseOfferAnswer(this.incomingInviteRequest, responseOptions) - .then((offerAnswer) => { - body = offerAnswer; - return this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - }) - .then((progressResponse) => { - this._dialog = progressResponse.session; - let prackRequest; - let prackResponse; - progressResponse.session.delegate = { - onPrack: (request) => { - prackRequest = request; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(prackWaitTimeoutTimer); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(rel1xxRetransmissionTimer); - if (!this.waitingForPrack) { - return; - } - this.waitingForPrack = false; - this.handlePrackOfferAnswer(prackRequest) - .then((prackResponseBody) => { - try { - prackResponse = prackRequest.accept({ statusCode: 200, body: prackResponseBody }); - this.prackArrived(); - resolve({ prackRequest, prackResponse, progressResponse }); - } - catch (error) { - reject(error); - } - }) - .catch((error) => reject(error)); - } - }; - // https://tools.ietf.org/html/rfc3262#section-3 - const prackWaitTimeout = () => { - if (!this.waitingForPrack) { - return; - } - this.waitingForPrack = false; - this.logger.warn("No PRACK received, rejecting INVITE."); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(rel1xxRetransmissionTimer); - this.reject({ statusCode: 504 }) - .then(() => reject(new SessionTerminatedError())) - .catch((error) => reject(error)); - }; - const prackWaitTimeoutTimer = setTimeout(prackWaitTimeout, Timers.T1 * 64); - // https://tools.ietf.org/html/rfc3262#section-3 - const rel1xxRetransmission = () => { - try { - this.incomingInviteRequest.progress({ statusCode, reasonPhrase, extraHeaders, body }); - } - catch (error) { - this.waitingForPrack = false; - reject(error); - return; - } - // eslint-disable-next-line @typescript-eslint/no-use-before-define - rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, (timeout *= 2)); - }; - let timeout = Timers.T1; - let rel1xxRetransmissionTimer = setTimeout(rel1xxRetransmission, timeout); - }) - .catch((error) => { - this.waitingForPrack = false; - reject(error); - }); - }); - } - /** - * A version of `progress` which resolves when a 100 Trying provisional response is sent. - */ - sendProgressTrying() { - try { - const progressResponse = this.incomingInviteRequest.trying(); - return Promise.resolve(progressResponse); - } - catch (error) { - return Promise.reject(error); - } - } - /** - * When attempting to accept the INVITE, an invitation waits - * for any outstanding PRACK to arrive before sending the 200 Ok. - * It will be waiting on this Promise to resolve which lets it know - * the PRACK has arrived and it may proceed to send the 200 Ok. - */ - waitForArrivalOfPrack() { - if (this.waitingForPrackPromise) { - throw new Error("Already waiting for PRACK"); - } - this.waitingForPrackPromise = new Promise((resolve, reject) => { - this.waitingForPrackResolve = resolve; - this.waitingForPrackReject = reject; - }); - return this.waitingForPrackPromise; - } - /** - * Here we are resolving the promise which in turn will cause - * the accept to proceed (it may still fail for other reasons, but...). - */ - prackArrived() { - if (this.waitingForPrackResolve) { - this.waitingForPrackResolve(); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - } - /** - * Here we are rejecting the promise which in turn will cause - * the accept to fail and the session to transition to "terminated". - */ - prackNeverArrived() { - if (this.waitingForPrackReject) { - this.waitingForPrackReject(new SessionTerminatedError()); - } - this.waitingForPrackPromise = undefined; - this.waitingForPrackResolve = undefined; - this.waitingForPrackReject = undefined; - } -} diff --git a/lib/api/inviter-cancel-options.d.ts b/lib/api/inviter-cancel-options.d.ts deleted file mode 100644 index 1eee02922..000000000 --- a/lib/api/inviter-cancel-options.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Options for {@link Inviter.cancel}. - * @public - */ -export interface InviterCancelOptions { - extraHeaders?: Array; - reasonPhrase?: string; - statusCode?: number; -} -//# sourceMappingURL=inviter-cancel-options.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter-cancel-options.d.ts.map b/lib/api/inviter-cancel-options.d.ts.map deleted file mode 100644 index 720656225..000000000 --- a/lib/api/inviter-cancel-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter-cancel-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-cancel-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB"} \ No newline at end of file diff --git a/lib/api/inviter-cancel-options.js b/lib/api/inviter-cancel-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/inviter-invite-options.d.ts b/lib/api/inviter-invite-options.d.ts deleted file mode 100644 index 0fab0afa4..000000000 --- a/lib/api/inviter-invite-options.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Inviter.invite}. - * @public - */ -export interface InviterInviteOptions { - /** - * See `core` API. - */ - requestDelegate?: OutgoingRequestDelegate; - /** - * See `core` API. - */ - requestOptions?: RequestOptions; - /** - * Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. - */ - sessionDescriptionHandlerModifiers?: Array; - /** - * Options to pass to SessionDescriptionHandler during the initial INVITE transaction. - */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** - * If true, send INVITE without SDP. Default is false. - */ - withoutSdp?: boolean; -} -//# sourceMappingURL=inviter-invite-options.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter-invite-options.d.ts.map b/lib/api/inviter-invite-options.d.ts.map deleted file mode 100644 index 7f153f7e3..000000000 --- a/lib/api/inviter-invite-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter-invite-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-invite-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/api/inviter-invite-options.js b/lib/api/inviter-invite-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/inviter-options.d.ts b/lib/api/inviter-options.d.ts deleted file mode 100644 index 4cda297bd..000000000 --- a/lib/api/inviter-options.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { URI } from "../core"; -import { SessionDescriptionHandlerModifier } from "./session-description-handler"; -import { SessionDescriptionHandlerOptions } from "./session-description-handler"; -import { SessionOptions } from "./session-options"; -/** - * Options for {@link Inviter} constructor. - * @public - */ -export interface InviterOptions extends SessionOptions { - /** If true, an anonymous call. */ - anonymous?: boolean; - /** - * If true, the first answer to the local offer is immediately utilized for media. - * Requires that the INVITE request MUST NOT fork. - * Has no effect if `inviteWithoutSdp` is true. - * Default is false. - */ - earlyMedia?: boolean; - /** Array of extra headers added to the INVITE. */ - extraHeaders?: Array; - /** If true, send INVITE without SDP. Default is false. */ - inviteWithoutSdp?: boolean; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: string | URI; - toDisplayName?: string; - toUri?: string | URI; - }; - /** @deprecated TODO: provide alternative. */ - renderbody?: string; - /** @deprecated TODO: provide alternative. */ - rendertype?: string; - /** Modifiers to pass to SessionDescriptionHandler during the initial INVITE transaction. */ - sessionDescriptionHandlerModifiers?: Array; - /** Options to pass to SessionDescriptionHandler during the initial INVITE transaction. */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** Modifiers to pass to SessionDescriptionHandler during re-INVITE transactions. */ - sessionDescriptionHandlerModifiersReInvite?: Array; - /** Options to pass to SessionDescriptionHandler during re-INVITE transactions. */ - sessionDescriptionHandlerOptionsReInvite?: SessionDescriptionHandlerOptions; -} -//# sourceMappingURL=inviter-options.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter-options.d.ts.map b/lib/api/inviter-options.d.ts.map deleted file mode 100644 index 9d3d205f8..000000000 --- a/lib/api/inviter-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter-options.d.ts","sourceRoot":"","sources":["../../src/api/inviter-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;;GAGG;AACH,MAAM,WAAW,cAAe,SAAQ,cAAc;IACpD,kCAAkC;IAClC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,kDAAkD;IAClD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,0DAA0D;IAC1D,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;QACvB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;KACtB,CAAC;IACF,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,4FAA4F;IAC5F,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E,0FAA0F;IAC1F,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE,oFAAoF;IACpF,0CAA0C,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACtF,kFAAkF;IAClF,wCAAwC,CAAC,EAAE,gCAAgC,CAAC;CAC7E"} \ No newline at end of file diff --git a/lib/api/inviter-options.js b/lib/api/inviter-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/inviter.d.ts b/lib/api/inviter.d.ts deleted file mode 100644 index 14d7fa100..000000000 --- a/lib/api/inviter.d.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { Logger, NameAddrHeader, OutgoingInviteRequest, OutgoingRequestMessage, URI } from "../core"; -import { InviterCancelOptions } from "./inviter-cancel-options"; -import { InviterInviteOptions } from "./inviter-invite-options"; -import { InviterOptions } from "./inviter-options"; -import { Session } from "./session"; -import { BodyAndContentType } from "./session-description-handler"; -import { UserAgent } from "./user-agent"; -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -export declare class Inviter extends Session { - /** - * If this Inviter was created as a result of a REFER, the referred Session. Otherwise undefined. - * @internal - */ - _referred: Session | undefined; - /** - * Logger. - */ - protected logger: Logger; - /** @internal */ - protected _id: string; - /** True if dispose() has been called. */ - private disposed; - /** True if early media use is enabled. */ - private earlyMedia; - /** The early media session. */ - private earlyMediaDialog; - /** The early media session description handlers. */ - private earlyMediaSessionDescriptionHandlers; - /** Our From tag. */ - private fromTag; - /** True if cancel() was called. */ - private isCanceled; - /** True if initial INVITE without SDP. */ - private inviteWithoutSdp; - /** Initial INVITE request sent by core. Undefined until sent. */ - private outgoingInviteRequest; - /** Initial INVITE message provided to core to send. */ - private outgoingRequestMessage; - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, options?: InviterOptions); - /** - * Destructor. - */ - dispose(): Promise; - /** - * Initial outgoing INVITE request message body. - */ - get body(): BodyAndContentType | undefined; - /** - * The identity of the local user. - */ - get localIdentity(): NameAddrHeader; - /** - * The identity of the remote user. - */ - get remoteIdentity(): NameAddrHeader; - /** - * Initial outgoing INVITE request message. - */ - get request(): OutgoingRequestMessage; - /** - * Cancels the INVITE request. - * - * @remarks - * Sends a CANCEL request. - * Resolves once the response sent, otherwise rejects. - * - * After sending a CANCEL request the expectation is that a 487 final response - * will be received for the INVITE. However a 200 final response to the INVITE - * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before - * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect - * is that this method will terminate the session regardless of the race. - * @param options - Options bucket. - */ - cancel(options?: InviterCancelOptions): Promise; - /** - * Sends the INVITE request. - * - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behavior may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behavior of the SIP - * servers being utilized is configured to disallow forking. - */ - invite(options?: InviterInviteOptions): Promise; - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - private sendInvite; - private disposeEarlyMedia; - private notifyReferer; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - private onAccept; - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - private onProgress; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - private onRedirect; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - private onReject; - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - private onTrying; -} -//# sourceMappingURL=inviter.d.ts.map \ No newline at end of file diff --git a/lib/api/inviter.d.ts.map b/lib/api/inviter.d.ts.map deleted file mode 100644 index 5bcdb3084..000000000 --- a/lib/api/inviter.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inviter.d.ts","sourceRoot":"","sources":["../../src/api/inviter.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,MAAM,EACN,cAAc,EACd,qBAAqB,EACrB,sBAAsB,EAMtB,GAAG,EACJ,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAA6B,MAAM,+BAA+B,CAAC;AAE9F,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC;;;GAGG;AACH,qBAAa,OAAQ,SAAQ,OAAO;IAClC;;;OAGG;IACI,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IAEtC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,gBAAgB;IAChB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC;IAEtB,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAS;IACzB,0CAA0C;IAC1C,OAAO,CAAC,UAAU,CAAS;IAC3B,+BAA+B;IAC/B,OAAO,CAAC,gBAAgB,CAA4B;IACpD,oDAAoD;IACpD,OAAO,CAAC,oCAAoC,CAAgD;IAC5F,oBAAoB;IACpB,OAAO,CAAC,OAAO,CAAS;IACxB,mCAAmC;IACnC,OAAO,CAAC,UAAU,CAAS;IAC3B,0CAA0C;IAC1C,OAAO,CAAC,gBAAgB,CAAS;IACjC,iEAAiE;IACjE,OAAO,CAAC,qBAAqB,CAAoC;IACjE,uDAAuD;IACvD,OAAO,CAAC,sBAAsB,CAAyB;IAEvD;;;;;OAKG;gBACgB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,GAAE,cAAmB;IA0HrF;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA+B/B;;OAEG;IACH,IAAW,IAAI,IAAI,kBAAkB,GAAG,SAAS,CAEhD;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,cAAc,CAEzC;IAED;;OAEG;IACH,IAAW,cAAc,IAAI,cAAc,CAE1C;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED;;;;;;;;;;;;;OAaG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IA0ChE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmFG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAkDjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAsCG;IACH,OAAO,CAAC,UAAU;IAkPlB,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,aAAa;IA+CrB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAgJhB;;;OAGG;IACH,OAAO,CAAC,UAAU;IA+IlB;;;OAGG;IAEH,OAAO,CAAC,UAAU;IAalB;;;OAGG;IAEH,OAAO,CAAC,QAAQ;IAahB;;;OAGG;IAEH,OAAO,CAAC,QAAQ;CASjB"} \ No newline at end of file diff --git a/lib/api/inviter.js b/lib/api/inviter.js deleted file mode 100644 index 39669bcdb..000000000 --- a/lib/api/inviter.js +++ /dev/null @@ -1,977 +0,0 @@ -import { C, Grammar, SignalingState } from "../core"; -import { getReasonPhrase, newTag } from "../core/messages/utils"; -import { Session } from "./session"; -import { SessionState } from "./session-state"; -import { SIPExtension } from "./user-agent-options"; -/** - * An inviter offers to establish a {@link Session} (outgoing INVITE). - * @public - */ -export class Inviter extends Session { - /** - * Constructs a new instance of the `Inviter` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param options - Options bucket. See {@link InviterOptions} for details. - */ - constructor(userAgent, targetURI, options = {}) { - super(userAgent, options); - /** True if dispose() has been called. */ - this.disposed = false; - /** True if early media use is enabled. */ - this.earlyMedia = false; - /** The early media session description handlers. */ - this.earlyMediaSessionDescriptionHandlers = new Map(); - /** True if cancel() was called. */ - this.isCanceled = false; - /** True if initial INVITE without SDP. */ - this.inviteWithoutSdp = false; - this.logger = userAgent.getLogger("sip.Inviter"); - // Early media - this.earlyMedia = options.earlyMedia !== undefined ? options.earlyMedia : this.earlyMedia; - // From tag - this.fromTag = newTag(); - // Invite without SDP - this.inviteWithoutSdp = options.inviteWithoutSdp !== undefined ? options.inviteWithoutSdp : this.inviteWithoutSdp; - // Inviter options (could do better copying these options) - const inviterOptions = Object.assign({}, options); - inviterOptions.params = Object.assign({}, options.params); - // Anonymous call - const anonymous = options.anonymous || false; - // Contact - const contact = userAgent.contact.toString({ - anonymous, - // Do not add ;ob in initial forming dialog requests if the - // registration over the current connection got a GRUU URI. - outbound: anonymous ? !userAgent.contact.tempGruu : !userAgent.contact.pubGruu - }); - // FIXME: TODO: We should not be parsing URIs here as if it fails we have to throw an exception - // which is not something we want our constructor to do. URIs should be passed in as params. - // URIs - if (anonymous && userAgent.configuration.uri) { - inviterOptions.params.fromDisplayName = "Anonymous"; - inviterOptions.params.fromUri = "sip:anonymous@anonymous.invalid"; - } - let fromURI = userAgent.userAgentCore.configuration.aor; - if (inviterOptions.params.fromUri) { - fromURI = - typeof inviterOptions.params.fromUri === "string" - ? Grammar.URIParse(inviterOptions.params.fromUri) - : inviterOptions.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + inviterOptions.params.fromUri); - } - let toURI = targetURI; - if (inviterOptions.params.toUri) { - toURI = - typeof inviterOptions.params.toUri === "string" - ? Grammar.URIParse(inviterOptions.params.toUri) - : inviterOptions.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + inviterOptions.params.toUri); - } - // Params - const messageOptions = Object.assign({}, inviterOptions.params); - messageOptions.fromTag = this.fromTag; - // Extra headers - const extraHeaders = (inviterOptions.extraHeaders || []).slice(); - if (anonymous && userAgent.configuration.uri) { - extraHeaders.push("P-Preferred-Identity: " + userAgent.configuration.uri.toString()); - extraHeaders.push("Privacy: id"); - } - extraHeaders.push("Contact: " + contact); - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - if (userAgent.configuration.sipExtension100rel === SIPExtension.Required) { - extraHeaders.push("Require: 100rel"); - } - if (userAgent.configuration.sipExtensionReplaces === SIPExtension.Required) { - extraHeaders.push("Require: replaces"); - } - inviterOptions.extraHeaders = extraHeaders; - // Body - const body = undefined; - // Make initial outgoing request message - this.outgoingRequestMessage = userAgent.userAgentCore.makeOutgoingRequestMessage(C.INVITE, targetURI, fromURI, toURI, messageOptions, extraHeaders, body); - // Session parent properties - this._contact = contact; - this._referralInviterOptions = inviterOptions; - this._renderbody = options.renderbody; - this._rendertype = options.rendertype; - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // Modifiers and options for re-INVITE transactions - if (options.sessionDescriptionHandlerModifiersReInvite) { - this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiersReInvite; - } - if (options.sessionDescriptionHandlerOptionsReInvite) { - this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptionsReInvite; - } - // Identifier - this._id = this.outgoingRequestMessage.callId + this.fromTag; - // Add to the user agent's session collection. - this.userAgent._sessions[this._id] = this; - } - /** - * Destructor. - */ - dispose() { - // Only run through this once. It can and does get called multiple times - // depending on the what the sessions state is when first called. - // For example, if called when "establishing" it will be called again - // at least once when the session transitions to "terminated". - // Regardless, running through this more than once is pointless. - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - // Dispose of early dialog media - this.disposeEarlyMedia(); - // If the final response for the initial INVITE not yet been received, cancel it - switch (this.state) { - case SessionState.Initial: - return this.cancel().then(() => super.dispose()); - case SessionState.Establishing: - return this.cancel().then(() => super.dispose()); - case SessionState.Established: - return super.dispose(); - case SessionState.Terminating: - return super.dispose(); - case SessionState.Terminated: - return super.dispose(); - default: - throw new Error("Unknown state."); - } - } - /** - * Initial outgoing INVITE request message body. - */ - get body() { - return this.outgoingRequestMessage.body; - } - /** - * The identity of the local user. - */ - get localIdentity() { - return this.outgoingRequestMessage.from; - } - /** - * The identity of the remote user. - */ - get remoteIdentity() { - return this.outgoingRequestMessage.to; - } - /** - * Initial outgoing INVITE request message. - */ - get request() { - return this.outgoingRequestMessage; - } - /** - * Cancels the INVITE request. - * - * @remarks - * Sends a CANCEL request. - * Resolves once the response sent, otherwise rejects. - * - * After sending a CANCEL request the expectation is that a 487 final response - * will be received for the INVITE. However a 200 final response to the INVITE - * may nonetheless arrive (it's a race between the CANCEL reaching the UAS before - * the UAS sends a 200) in which case an ACK & BYE will be sent. The net effect - * is that this method will terminate the session regardless of the race. - * @param options - Options bucket. - */ - cancel(options = {}) { - this.logger.log("Inviter.cancel"); - // validate state - if (this.state !== SessionState.Initial && this.state !== SessionState.Establishing) { - const error = new Error(`Invalid session state ${this.state}`); - this.logger.error(error.message); - return Promise.reject(error); - } - // flag canceled - this.isCanceled = true; - // transition state - this.stateTransition(SessionState.Terminating); - // helper function - function getCancelReason(code, reason) { - if ((code && code < 200) || code > 699) { - throw new TypeError("Invalid statusCode: " + code); - } - else if (code) { - const cause = code; - const text = getReasonPhrase(code) || reason; - return "SIP;cause=" + cause + ';text="' + text + '"'; - } - } - if (this.outgoingInviteRequest) { - // the CANCEL may not be respected by peer(s), so don't transition to terminated - let cancelReason; - if (options.statusCode && options.reasonPhrase) { - cancelReason = getCancelReason(options.statusCode, options.reasonPhrase); - } - this.outgoingInviteRequest.cancel(cancelReason, options); - } - else { - this.logger.warn("Canceled session before INVITE was sent"); - this.stateTransition(SessionState.Terminated); - } - return Promise.resolve(); - } - /** - * Sends the INVITE request. - * - * @remarks - * TLDR... - * 1) Only one offer/answer exchange permitted during initial INVITE. - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * 1) Only one offer/answer exchange permitted during initial INVITE. - * - * Our implementation replaces the following bullet point... - * - * o After having sent or received an answer to the first offer, the - * UAC MAY generate subsequent offers in requests based on rules - * specified for that method, but only if it has received answers - * to any previous offers, and has not sent any offers to which it - * hasn't gotten an answer. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...with... - * - * o After having sent or received an answer to the first offer, the - * UAC MUST NOT generate subsequent offers in requests based on rules - * specified for that method. - * - * ...which in combination with this bullet point... - * - * o Once the UAS has sent or received an answer to the initial - * offer, it MUST NOT generate subsequent offers in any responses - * to the initial INVITE. This means that a UAS based on this - * specification alone can never generate subsequent offers until - * completion of the initial transaction. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * ...ensures that EXACTLY ONE offer/answer exchange will occur - * during an initial out of dialog INVITE request made by our UAC. - * - * - * 2) No "early media" if the initial offer is in an INVITE (default behavior). - * - * While our implementation adheres to the following bullet point... - * - * o If the initial offer is in an INVITE, the answer MUST be in a - * reliable non-failure message from UAS back to UAC which is - * correlated to that INVITE. For this specification, that is - * only the final 2xx response to that INVITE. That same exact - * answer MAY also be placed in any provisional responses sent - * prior to the answer. The UAC MUST treat the first session - * description it receives as the answer, and MUST ignore any - * session descriptions in subsequent responses to the initial - * INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * - * We have made the following implementation decision with regard to early media... - * - * o If the initial offer is in the INVITE, the answer from the - * UAS back to the UAC will establish a media session only - * only after the final 2xx response to that INVITE is received. - * - * The reason for this decision is rooted in a restriction currently - * inherent in WebRTC. Specifically, while a SIP INVITE request with an - * initial offer may fork resulting in more than one provisional answer, - * there is currently no easy/good way to to "fork" an offer generated - * by a peer connection. In particular, a WebRTC offer currently may only - * be matched with one answer and we have no good way to know which - * "provisional answer" is going to be the "final answer". So we have - * decided to punt and not create any "early media" sessions in this case. - * - * The upshot is that if you want "early media", you must not put the - * initial offer in the INVITE. Instead, force the UAS to provide the - * initial offer by sending an INVITE without an offer. In the WebRTC - * case this allows us to create a unique peer connection with a unique - * answer for every provisional offer with "early media" on all of them. - * - * - * 3) If "early media" and the initial offer is in an INVITE, no INVITE forking. - * - * The default behavior may be altered and "early media" utilized if the - * initial offer is in the an INVITE by setting the `earlyMedia` options. - * However in that case the INVITE request MUST NOT fork. This allows for - * "early media" in environments where the forking behavior of the SIP - * servers being utilized is configured to disallow forking. - */ - invite(options = {}) { - this.logger.log("Inviter.invite"); - // validate state - if (this.state !== SessionState.Initial) { - // re-invite - return super.invite(options); - } - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiers = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptions = options.sessionDescriptionHandlerOptions; - } - // just send an INVITE with no sdp... - if (options.withoutSdp || this.inviteWithoutSdp) { - if (this._renderbody && this._rendertype) { - this.outgoingRequestMessage.body = { contentType: this._rendertype, body: this._renderbody }; - } - // transition state - this.stateTransition(SessionState.Establishing); - return Promise.resolve(this.sendInvite(options)); - } - // get an offer and send it in an INVITE - const offerOptions = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.getOffer(offerOptions) - .then((body) => { - this.outgoingRequestMessage.body = { body: body.content, contentType: body.contentType }; - // transition state - this.stateTransition(SessionState.Establishing); - return this.sendInvite(options); - }) - .catch((error) => { - this.logger.log(error.message); - this.stateTransition(SessionState.Terminated); - throw error; - }); - } - /** - * 13.2.1 Creating the Initial INVITE - * - * Since the initial INVITE represents a request outside of a dialog, - * its construction follows the procedures of Section 8.1.1. Additional - * processing is required for the specific case of INVITE. - * - * An Allow header field (Section 20.5) SHOULD be present in the INVITE. - * It indicates what methods can be invoked within a dialog, on the UA - * sending the INVITE, for the duration of the dialog. For example, a - * UA capable of receiving INFO requests within a dialog [34] SHOULD - * include an Allow header field listing the INFO method. - * - * A Supported header field (Section 20.37) SHOULD be present in the - * INVITE. It enumerates all the extensions understood by the UAC. - * - * An Accept (Section 20.1) header field MAY be present in the INVITE. - * It indicates which Content-Types are acceptable to the UA, in both - * the response received by it, and in any subsequent requests sent to - * it within dialogs established by the INVITE. The Accept header field - * is especially useful for indicating support of various session - * description formats. - * - * The UAC MAY add an Expires header field (Section 20.19) to limit the - * validity of the invitation. If the time indicated in the Expires - * header field is reached and no final answer for the INVITE has been - * received, the UAC core SHOULD generate a CANCEL request for the - * INVITE, as per Section 9. - * - * A UAC MAY also find it useful to add, among others, Subject (Section - * 20.36), Organization (Section 20.25) and User-Agent (Section 20.41) - * header fields. They all contain information related to the INVITE. - * - * The UAC MAY choose to add a message body to the INVITE. Section - * 8.1.1.10 deals with how to construct the header fields -- Content- - * Type among others -- needed to describe the message body. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - */ - sendInvite(options = {}) { - // There are special rules for message bodies that contain a session - // description - their corresponding Content-Disposition is "session". - // SIP uses an offer/answer model where one UA sends a session - // description, called the offer, which contains a proposed description - // of the session. The offer indicates the desired communications means - // (audio, video, games), parameters of those means (such as codec - // types) and addresses for receiving media from the answerer. The - // other UA responds with another session description, called the - // answer, which indicates which communications means are accepted, the - // parameters that apply to those means, and addresses for receiving - // media from the offerer. An offer/answer exchange is within the - // context of a dialog, so that if a SIP INVITE results in multiple - // dialogs, each is a separate offer/answer exchange. The offer/answer - // model defines restrictions on when offers and answers can be made - // (for example, you cannot make a new offer while one is in progress). - // This results in restrictions on where the offers and answers can - // appear in SIP messages. In this specification, offers and answers - // can only appear in INVITE requests and responses, and ACK. The usage - // of offers and answers is further restricted. For the initial INVITE - // transaction, the rules are: - // - // o The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. In this specification, that is the final 2xx - // response. - // - // o If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // - // o If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message (in this specification, ACK - // for a 2xx response). - // - // o After having sent or received an answer to the first offer, the - // UAC MAY generate subsequent offers in requests based on rules - // specified for that method, but only if it has received answers - // to any previous offers, and has not sent any offers to which it - // hasn't gotten an answer. - // - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // 5 The Offer/Answer Model and PRACK - // - // RFC 3261 describes guidelines for the sets of messages in which - // offers and answers [3] can appear. Based on those guidelines, this - // extension provides additional opportunities for offer/answer - // exchanges. - // If the INVITE contained an offer, the UAS MAY generate an answer in a - // reliable provisional response (assuming these are supported by the - // UAC). That results in the establishment of the session before - // completion of the call. Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // If the UAC receives a reliable provisional response with an offer - // (this would occur if the UAC sent an INVITE without an offer, in - // which case the first reliable provisional response will contain the - // offer), it MUST generate an answer in the PRACK. If the UAC receives - // a reliable provisional response with an answer, it MAY generate an - // additional offer in the PRACK. If the UAS receives a PRACK with an - // offer, it MUST place the answer in the 2xx to the PRACK. - // Once an answer has been sent or received, the UA SHOULD establish the - // session based on the parameters of the offer and answer, even if the - // original INVITE itself has not been responded to. - // If the UAS had placed a session description in any reliable - // provisional response that is unacknowledged when the INVITE is - // accepted, the UAS MUST delay sending the 2xx until the provisional - // response is acknowledged. Otherwise, the reliability of the 1xx - // cannot be guaranteed, and reliability is needed for proper operation - // of the offer/answer exchange. - // All user agents that support this extension MUST support all - // offer/answer exchanges that are possible based on the rules in - // Section 13.2 of RFC 3261, based on the existence of INVITE and PRACK - // as requests, and 2xx and reliable 1xx as non-failure reliable - // responses. - // - // https://tools.ietf.org/html/rfc3262#section-5 - //// - // The Offer/Answer Model Implementation - // - // The offer/answer model is straight forward, but one MUST READ the specifications... - // - // 13.2.1 Creating the Initial INVITE (paragraph 8 in particular) - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // - // 5 The Offer/Answer Model and PRACK - // https://tools.ietf.org/html/rfc3262#section-5 - // - // Session Initiation Protocol (SIP) Usage of the Offer/Answer Model - // https://tools.ietf.org/html/rfc6337 - //// - //// - // TODO: The Offer/Answer Model Implementation - // - // Currently if `earlyMedia` is enabled and the INVITE request forks, - // the session is terminated if the early dialog does not match the - // confirmed dialog. This restriction make sense in a WebRTC environment, - // but there are other environments where this restriction does not hold. - // - // So while we currently cannot make the offer in INVITE+forking+webrtc - // case work, we propose doing the following... - // - // OPTION 1 - // - add a `earlyMediaForking` option and - // - require SDH.setDescription() to be callable multiple times. - // - // OPTION 2 - // 1) modify SDH Factory to provide an initial offer without giving us the SDH, and then... - // 2) stick that offer in the initial INVITE, and when 183 with initial answer is received... - // 3) ask SDH Factory if it supports "earlyRemoteAnswer" - // a) if true, ask SDH Factory to createSDH(localOffer).then((sdh) => sdh.setDescription(remoteAnswer) - // b) if false, defer getting a SDH until 2xx response is received - // - // Our supplied WebRTC SDH will default to behavior 3b which works in forking environment (without) - // early media if initial offer is in the INVITE). We will, however, provide an "inviteWillNotFork" - // option which if set to "true" will have our supplied WebRTC SDH behave in the 3a manner. - // That will result in - // - early media working with initial offer in the INVITE, and... - // - if the INVITE forks, the session terminating with an ERROR that reads like - // "You set 'inviteWillNotFork' to true but the INVITE forked. You can't eat your cake, and have it too." - // - furthermore, we accept that users will report that error to us as "bug" regardless - // - // So, SDH Factory is going to end up with a new interface along the lines of... - // - // interface SessionDescriptionHandlerFactory { - // makeLocalOffer(): Promise; - // makeSessionDescriptionHandler( - // initialOffer: ContentTypeAndBody, offerType: "local" | "remote" - // ): Promise; - // supportsEarlyRemoteAnswer: boolean; - // supportsContentType(contentType: string): boolean; - // getDescription(description: ContentTypeAndBody): Promise - // setDescription(description: ContentTypeAndBody): Promise - // } - //// - // Send the INVITE request. - this.outgoingInviteRequest = this.userAgent.userAgentCore.invite(this.outgoingRequestMessage, { - onAccept: (inviteResponse) => { - // Our transaction layer is "non-standard" in that it will only - // pass us a 2xx response once per branch, so there is no need to - // worry about dealing with 2xx retransmissions. However, we can - // and do still get 2xx responses for multiple branches (when an - // INVITE is forked) which may create multiple confirmed dialogs. - // Herein we are acking and sending a bye to any confirmed dialogs - // which arrive beyond the first one. This is the desired behavior - // for most applications (but certainly not all). - // If we already received a confirmed dialog, ack & bye this additional confirmed session. - if (this.dialog) { - this.logger.log("Additional confirmed dialog, sending ACK and BYE"); - this.ackAndBye(inviteResponse); - // We do NOT transition state in this case (this is an "extra" dialog) - return; - } - // If the user requested cancellation, ack & bye this session. - if (this.isCanceled) { - this.logger.log("Canceled session accepted, sending ACK and BYE"); - this.ackAndBye(inviteResponse); - this.stateTransition(SessionState.Terminated); - return; - } - this.notifyReferer(inviteResponse); - this.onAccept(inviteResponse) - .then(() => { - this.disposeEarlyMedia(); - }) - .catch(() => { - this.disposeEarlyMedia(); - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(inviteResponse); - } - }); - }, - onProgress: (inviteResponse) => { - // If the user requested cancellation, ignore response. - if (this.isCanceled) { - return; - } - this.notifyReferer(inviteResponse); - this.onProgress(inviteResponse) - .catch(() => { - this.disposeEarlyMedia(); - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(inviteResponse); - } - }); - }, - onRedirect: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onRedirect(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(inviteResponse); - } - }, - onReject: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onReject(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(inviteResponse); - } - }, - onTrying: (inviteResponse) => { - this.notifyReferer(inviteResponse); - this.onTrying(inviteResponse); - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(inviteResponse); - } - } - }); - return this.outgoingInviteRequest; - } - disposeEarlyMedia() { - this.earlyMediaSessionDescriptionHandlers.forEach((sessionDescriptionHandler) => { - sessionDescriptionHandler.close(); - }); - this.earlyMediaSessionDescriptionHandlers.clear(); - } - notifyReferer(response) { - if (!this._referred) { - return; - } - if (!(this._referred instanceof Session)) { - throw new Error("Referred session not instance of session"); - } - if (!this._referred.dialog) { - return; - } - if (!response.message.statusCode) { - throw new Error("Status code undefined."); - } - if (!response.message.reasonPhrase) { - throw new Error("Reason phrase undefined."); - } - const statusCode = response.message.statusCode; - const reasonPhrase = response.message.reasonPhrase; - const body = `SIP/2.0 ${statusCode} ${reasonPhrase}`.trim(); - const outgoingNotifyRequest = this._referred.dialog.notify(undefined, { - extraHeaders: ["Event: refer", "Subscription-State: terminated"], - body: { - contentDisposition: "render", - contentType: "message/sipfrag", - content: body - } - }); - // The implicit subscription created by a REFER is the same as a - // subscription created with a SUBSCRIBE request. The agent issuing the - // REFER can terminate this subscription prematurely by unsubscribing - // using the mechanisms described in [2]. Terminating a subscription, - // either by explicitly unsubscribing or rejecting NOTIFY, is not an - // indication that the referenced request should be withdrawn or - // abandoned. - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - // FIXME: TODO: This should be done in a subscribe dialog to satisfy the above. - // If the notify is rejected, stop sending NOTIFY requests. - outgoingNotifyRequest.delegate = { - onReject: () => { - this._referred = undefined; - } - }; - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 2xx response. - */ - onAccept(inviteResponse) { - this.logger.log("Inviter.onAccept"); - // validate state - if (this.state !== SessionState.Establishing) { - this.logger.error(`Accept received while in state ${this.state}, dropping response`); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const response = inviteResponse.message; - const session = inviteResponse.session; - // Ported behavior. - if (response.hasHeader("P-Asserted-Identity")) { - this._assertedIdentity = Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // We have a confirmed dialog. - session.delegate = { - onAck: (ackRequest) => this.onAckRequest(ackRequest), - onBye: (byeRequest) => this.onByeRequest(byeRequest), - onInfo: (infoRequest) => this.onInfoRequest(infoRequest), - onInvite: (inviteRequest) => this.onInviteRequest(inviteRequest), - onMessage: (messageRequest) => this.onMessageRequest(messageRequest), - onNotify: (notifyRequest) => this.onNotifyRequest(notifyRequest), - onPrack: (prackRequest) => this.onPrackRequest(prackRequest), - onRefer: (referRequest) => this.onReferRequest(referRequest) - }; - this._dialog = session; - switch (session.signalingState) { - case SignalingState.Initial: - // INVITE without offer, so MUST have offer at this point, so invalid state. - this.logger.error("Received 2xx response to INVITE without a session description"); - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.stateTransition(SessionState.Terminated); - return Promise.reject(new Error("Bad Media Description")); - case SignalingState.HaveLocalOffer: - // INVITE with offer, so MUST have answer at this point, so invalid state. - this.logger.error("Received 2xx response to INVITE without a session description"); - this.ackAndBye(inviteResponse, 400, "Missing session description"); - this.stateTransition(SessionState.Terminated); - return Promise.reject(new Error("Bad Media Description")); - case SignalingState.HaveRemoteOffer: { - // INVITE without offer, received offer in 2xx, so MUST send answer in ACK. - if (!this._dialog.offer) { - throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setOfferAndGetAnswer(this._dialog.offer, options) - .then((body) => { - inviteResponse.ack({ body }); - this.stateTransition(SessionState.Established); - }) - .catch((error) => { - this.ackAndBye(inviteResponse, 488, "Invalid session description"); - this.stateTransition(SessionState.Terminated); - throw error; - }); - } - case SignalingState.Stable: { - // If INVITE without offer and we have already completed the initial exchange. - if (this.earlyMediaSessionDescriptionHandlers.size > 0) { - const sdh = this.earlyMediaSessionDescriptionHandlers.get(session.id); - if (!sdh) { - throw new Error("Session description handler undefined."); - } - this.setSessionDescriptionHandler(sdh); - this.earlyMediaSessionDescriptionHandlers.delete(session.id); - inviteResponse.ack(); - this.stateTransition(SessionState.Established); - return Promise.resolve(); - } - // If INVITE with offer and we used an "early" answer in a provisional response for media - if (this.earlyMediaDialog) { - // If early media dialog doesn't match confirmed dialog, we must unfortunately fail. - // This limitation stems from how WebRTC currently implements its offer/answer model. - // There are details elsewhere, but in short a WebRTC offer cannot be forked. - if (this.earlyMediaDialog !== session) { - if (this.earlyMedia) { - const message = "You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests " + - "do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly " + - "the end point which accepted the INVITE (confirmed dialog) does not match the end point with " + - "which early media has been setup (early dialog) and thus this session is unable to proceed. " + - "In accordance with the SIP specifications, the SIP servers your end point is connected to " + - "determine if an INVITE forks and the forking behavior of those servers cannot be controlled " + - "by this library. If you wish to use early media with this library you must configure those " + - "servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow " + - "this library to function with any INVITE requests which do fork."; - this.logger.error(message); - } - const error = new Error("Early media dialog does not equal confirmed dialog, terminating session"); - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.stateTransition(SessionState.Terminated); - return Promise.reject(error); - } - // Otherwise we are good to go. - inviteResponse.ack(); - this.stateTransition(SessionState.Established); - return Promise.resolve(); - } - // If INVITE with offer and we have been waiting till now to apply the answer. - const answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setAnswer(answer, options) - .then(() => { - // This session has completed an initial offer/answer exchange... - let ackOptions; - if (this._renderbody && this._rendertype) { - ackOptions = { - body: { contentDisposition: "render", contentType: this._rendertype, content: this._renderbody } - }; - } - inviteResponse.ack(ackOptions); - this.stateTransition(SessionState.Established); - }) - .catch((error) => { - this.logger.error(error.message); - this.ackAndBye(inviteResponse, 488, "Not Acceptable Here"); - this.stateTransition(SessionState.Terminated); - throw error; - }); - } - case SignalingState.Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - } - /** - * Handle provisional response to initial INVITE. - * @param inviteResponse - 1xx response. - */ - onProgress(inviteResponse) { - var _a; - this.logger.log("Inviter.onProgress"); - // validate state - if (this.state !== SessionState.Establishing) { - this.logger.error(`Progress received while in state ${this.state}, dropping response`); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - if (!this.outgoingInviteRequest) { - throw new Error("Outgoing INVITE request undefined."); - } - const response = inviteResponse.message; - const session = inviteResponse.session; - // Ported - Set assertedIdentity. - if (response.hasHeader("P-Asserted-Identity")) { - this._assertedIdentity = Grammar.nameAddrHeaderParse(response.getHeader("P-Asserted-Identity")); - } - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - const requireHeader = response.getHeader("require"); - const rseqHeader = response.getHeader("rseq"); - const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - const responseReliable = !!rseq; - const extraHeaders = []; - if (responseReliable) { - extraHeaders.push("RAck: " + response.getHeader("rseq") + " " + response.getHeader("cseq")); - } - switch (session.signalingState) { - case SignalingState.Initial: - // INVITE without offer and session still has no offer (and no answer). - if (responseReliable) { - // Similarly, if a reliable provisional - // response is the first reliable message sent back to the UAC, and the - // INVITE did not contain an offer, one MUST appear in that reliable - // provisional response. - // https://tools.ietf.org/html/rfc3262#section-5 - this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."); - // FIXME: Known popular UA's currently end up here... - inviteResponse.prack({ extraHeaders }); - } - return Promise.resolve(); - case SignalingState.HaveLocalOffer: - // INVITE with offer and session only has that initial local offer. - if (responseReliable) { - inviteResponse.prack({ extraHeaders }); - } - return Promise.resolve(); - case SignalingState.HaveRemoteOffer: - if (!responseReliable) { - // The initial offer MUST be in either an INVITE or, if not there, - // in the first reliable non-failure message from the UAS back to - // the UAC. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // According to Section 13.2.1 of [RFC3261], 'The first reliable - // non-failure message' must have an offer if there is no offer in the - // INVITE request. This means that the User Agent (UA) that receives - // the INVITE request without an offer must include an offer in the - // first reliable response with 100rel extension. If no reliable - // provisional response has been sent, the User Agent Server (UAS) must - // include an offer when sending 2xx response. - // https://tools.ietf.org/html/rfc6337#section-2.2 - this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."); - return Promise.resolve(); - } - { - // If the initial offer is in the first reliable non-failure - // message from the UAS back to UAC, the answer MUST be in the - // acknowledgement for that message - const sdh = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions || {}); - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { - this.delegate.onSessionDescriptionHandler(sdh, true); - } - this.earlyMediaSessionDescriptionHandlers.set(session.id, sdh); - return sdh - .setDescription(response.body, this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers) - .then(() => sdh.getDescription(this.sessionDescriptionHandlerOptions, this.sessionDescriptionHandlerModifiers)) - .then((description) => { - const body = { - contentDisposition: "session", - contentType: description.contentType, - content: description.body - }; - inviteResponse.prack({ extraHeaders, body }); - }) - .catch((error) => { - this.stateTransition(SessionState.Terminated); - throw error; - }); - } - case SignalingState.Stable: - // This session has completed an initial offer/answer exchange, so... - // - INVITE with SDP and this provisional response MAY be reliable - // - INVITE without SDP and this provisional response MAY be reliable - if (responseReliable) { - inviteResponse.prack({ extraHeaders }); - } - if (this.earlyMedia && !this.earlyMediaDialog) { - this.earlyMediaDialog = session; - const answer = session.answer; - if (!answer) { - throw new Error("Answer is undefined."); - } - const options = { - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers, - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions - }; - return this.setAnswer(answer, options).catch((error) => { - this.stateTransition(SessionState.Terminated); - throw error; - }); - } - return Promise.resolve(); - case SignalingState.Closed: - // Dialog has terminated. - return Promise.reject(new Error("Terminated.")); - default: - throw new Error("Unknown session signaling state."); - } - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 3xx response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect(inviteResponse) { - this.logger.log("Inviter.onRedirect"); - // validate state - if (this.state !== SessionState.Establishing && this.state !== SessionState.Terminating) { - this.logger.error(`Redirect received while in state ${this.state}, dropping response`); - return; - } - // transition state - this.stateTransition(SessionState.Terminated); - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 4xx, 5xx, or 6xx response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onReject(inviteResponse) { - this.logger.log("Inviter.onReject"); - // validate state - if (this.state !== SessionState.Establishing && this.state !== SessionState.Terminating) { - this.logger.error(`Reject received while in state ${this.state}, dropping response`); - return; - } - // transition state - this.stateTransition(SessionState.Terminated); - } - /** - * Handle final response to initial INVITE. - * @param inviteResponse - 100 response. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTrying(inviteResponse) { - this.logger.log("Inviter.onTrying"); - // validate state - if (this.state !== SessionState.Establishing) { - this.logger.error(`Trying received while in state ${this.state}, dropping response`); - return; - } - } -} diff --git a/lib/api/message.d.ts b/lib/api/message.d.ts deleted file mode 100644 index 1ceb4b121..000000000 --- a/lib/api/message.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingMessageRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * A received message (incoming MESSAGE). - * @public - */ -export declare class Message { - private incomingMessageRequest; - /** @internal */ - constructor(incomingMessageRequest: IncomingMessageRequest); - /** Incoming MESSAGE request message. */ - get request(): IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=message.d.ts.map \ No newline at end of file diff --git a/lib/api/message.d.ts.map b/lib/api/message.d.ts.map deleted file mode 100644 index 156007f5d..000000000 --- a/lib/api/message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../src/api/message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1F;;;GAGG;AACH,qBAAa,OAAO;IAEC,OAAO,CAAC,sBAAsB;IADjD,gBAAgB;gBACW,sBAAsB,EAAE,sBAAsB;IAEzE,wCAAwC;IACxC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/message.js b/lib/api/message.js deleted file mode 100644 index d65d1d0ed..000000000 --- a/lib/api/message.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A received message (incoming MESSAGE). - * @public - */ -export class Message { - /** @internal */ - constructor(incomingMessageRequest) { - this.incomingMessageRequest = incomingMessageRequest; - } - /** Incoming MESSAGE request message. */ - get request() { - return this.incomingMessageRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingMessageRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingMessageRequest.reject(options); - return Promise.resolve(); - } -} diff --git a/lib/api/messager-message-options.d.ts b/lib/api/messager-message-options.d.ts deleted file mode 100644 index 7a83a61b8..000000000 --- a/lib/api/messager-message-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Messager.message}. - * @public - */ -export interface MessagerMessageOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=messager-message-options.d.ts.map \ No newline at end of file diff --git a/lib/api/messager-message-options.d.ts.map b/lib/api/messager-message-options.d.ts.map deleted file mode 100644 index 5806244a8..000000000 --- a/lib/api/messager-message-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messager-message-options.d.ts","sourceRoot":"","sources":["../../src/api/messager-message-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/messager-message-options.js b/lib/api/messager-message-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/messager-options.d.ts b/lib/api/messager-options.d.ts deleted file mode 100644 index 2d2251208..000000000 --- a/lib/api/messager-options.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { URI } from "../core"; -/** - * Options for {@link Messager} constructor. - * @public - */ -export interface MessagerOptions { - /** Array of extra headers added to the MESSAGE. */ - extraHeaders?: Array; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: string | URI; - toDisplayName?: string; - toUri?: string | URI; - }; -} -//# sourceMappingURL=messager-options.d.ts.map \ No newline at end of file diff --git a/lib/api/messager-options.d.ts.map b/lib/api/messager-options.d.ts.map deleted file mode 100644 index 48d8e72b9..000000000 --- a/lib/api/messager-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messager-options.d.ts","sourceRoot":"","sources":["../../src/api/messager-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,mDAAmD;IACnD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;QACvB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;KACtB,CAAC;CACH"} \ No newline at end of file diff --git a/lib/api/messager-options.js b/lib/api/messager-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/messager.d.ts b/lib/api/messager.d.ts deleted file mode 100644 index 2cf076e2e..000000000 --- a/lib/api/messager.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { URI } from "../core"; -import { MessagerMessageOptions } from "./messager-message-options"; -import { MessagerOptions } from "./messager-options"; -import { UserAgent } from "./user-agent"; -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -export declare class Messager { - private logger; - private request; - private userAgent; - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, content: string, contentType?: string, options?: MessagerOptions); - /** - * Send the message. - */ - message(options?: MessagerMessageOptions): Promise; -} -//# sourceMappingURL=messager.d.ts.map \ No newline at end of file diff --git a/lib/api/messager.d.ts.map b/lib/api/messager.d.ts.map deleted file mode 100644 index 34d2136ca..000000000 --- a/lib/api/messager.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messager.d.ts","sourceRoot":"","sources":["../../src/api/messager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoD,GAAG,EAAE,MAAM,SAAS,CAAC;AAChF,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,QAAQ;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;;;;OAOG;gBAED,SAAS,EAAE,SAAS,EACpB,SAAS,EAAE,GAAG,EACd,OAAO,EAAE,MAAM,EACf,WAAW,SAAe,EAC1B,OAAO,GAAE,eAAoB;IAsD/B;;OAEG;IACI,OAAO,CAAC,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,CAAC;CAIpE"} \ No newline at end of file diff --git a/lib/api/messager.js b/lib/api/messager.js deleted file mode 100644 index 72f55690c..000000000 --- a/lib/api/messager.js +++ /dev/null @@ -1,59 +0,0 @@ -import { C, Grammar } from "../core"; -/** - * A messager sends a {@link Message} (outgoing MESSAGE). - * @public - */ -export class Messager { - /** - * Constructs a new instance of the `Messager` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param content - Content for the body of the message. - * @param contentType - Content type of the body of the message. - * @param options - Options bucket. See {@link MessagerOptions} for details. - */ - constructor(userAgent, targetURI, content, contentType = "text/plain", options = {}) { - // Logger - this.logger = userAgent.getLogger("sip.Messager"); - // Default options params - options.params = options.params || {}; - // URIs - let fromURI = userAgent.userAgentCore.configuration.aor; - if (options.params.fromUri) { - fromURI = - typeof options.params.fromUri === "string" ? Grammar.URIParse(options.params.fromUri) : options.params.fromUri; - } - if (!fromURI) { - throw new TypeError("Invalid from URI: " + options.params.fromUri); - } - let toURI = targetURI; - if (options.params.toUri) { - toURI = typeof options.params.toUri === "string" ? Grammar.URIParse(options.params.toUri) : options.params.toUri; - } - if (!toURI) { - throw new TypeError("Invalid to URI: " + options.params.toUri); - } - // Message params - const params = options.params ? Object.assign({}, options.params) : {}; - // Extra headers - const extraHeaders = (options.extraHeaders || []).slice(); - // Body - const contentDisposition = "render"; - const body = { - contentDisposition, - contentType, - content - }; - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE, targetURI, fromURI, toURI, params, extraHeaders, body); - // User agent - this.userAgent = userAgent; - } - /** - * Send the message. - */ - message(options = {}) { - this.userAgent.userAgentCore.request(this.request, options.requestDelegate); - return Promise.resolve(); - } -} diff --git a/lib/api/notification.d.ts b/lib/api/notification.d.ts deleted file mode 100644 index 3290d6f60..000000000 --- a/lib/api/notification.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IncomingNotifyRequest, IncomingRequestMessage, ResponseOptions } from "../core"; -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -export declare class Notification { - private incomingNotifyRequest; - /** @internal */ - constructor(incomingNotifyRequest: IncomingNotifyRequest); - /** Incoming NOTIFY request message. */ - get request(): IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; -} -//# sourceMappingURL=notification.d.ts.map \ No newline at end of file diff --git a/lib/api/notification.d.ts.map b/lib/api/notification.d.ts.map deleted file mode 100644 index 823e6118a..000000000 --- a/lib/api/notification.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notification.d.ts","sourceRoot":"","sources":["../../src/api/notification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEzF;;;GAGG;AACH,qBAAa,YAAY;IAEJ,OAAO,CAAC,qBAAqB;IADhD,gBAAgB;gBACW,qBAAqB,EAAE,qBAAqB;IAEvE,uCAAuC;IACvC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIxD"} \ No newline at end of file diff --git a/lib/api/notification.js b/lib/api/notification.js deleted file mode 100644 index a86924254..000000000 --- a/lib/api/notification.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A notification of an event (incoming NOTIFY). - * @public - */ -export class Notification { - /** @internal */ - constructor(incomingNotifyRequest) { - this.incomingNotifyRequest = incomingNotifyRequest; - } - /** Incoming NOTIFY request message. */ - get request() { - return this.incomingNotifyRequest.message; - } - /** Accept the request. */ - accept(options) { - this.incomingNotifyRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingNotifyRequest.reject(options); - return Promise.resolve(); - } -} diff --git a/lib/api/notifier.d.ts b/lib/api/notifier.d.ts deleted file mode 100644 index feb606737..000000000 --- a/lib/api/notifier.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * TODO: This is currently just a placeholder. - * Notifier is the peer of a Subscriber. - * That is, a Notifier sends NOTIFY requests. - * @internal - */ -export declare class Notifier { -} -//# sourceMappingURL=notifier.d.ts.map \ No newline at end of file diff --git a/lib/api/notifier.d.ts.map b/lib/api/notifier.d.ts.map deleted file mode 100644 index f65c5e841..000000000 --- a/lib/api/notifier.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notifier.d.ts","sourceRoot":"","sources":["../../src/api/notifier.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,QAAQ;CAAG"} \ No newline at end of file diff --git a/lib/api/notifier.js b/lib/api/notifier.js deleted file mode 100644 index e64883a8b..000000000 --- a/lib/api/notifier.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * TODO: This is currently just a placeholder. - * Notifier is the peer of a Subscriber. - * That is, a Notifier sends NOTIFY requests. - * @internal - */ -export class Notifier { -} diff --git a/lib/api/publisher-options.d.ts b/lib/api/publisher-options.d.ts deleted file mode 100644 index 137223835..000000000 --- a/lib/api/publisher-options.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { URI } from "../core"; -/** - * Options for {@link Publisher} constructor. - * @public - */ -export interface PublisherOptions { - /** @deprecated TODO: provide alternative. */ - body?: string; - /** @deprecated TODO: provide alternative. */ - contentType?: string; - /** - * Expire value for the published event. - * @defaultValue 3600 - */ - expires?: number; - /** - * Array of extra headers added to the PUBLISH request message. - */ - extraHeaders?: Array; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: URI; - toDisplayName?: string; - toUri?: URI; - }; - /** - * If set true, UA will gracefully unpublish for the event on UA close. - * @defaultValue true - */ - unpublishOnClose?: boolean; -} -//# sourceMappingURL=publisher-options.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-options.d.ts.map b/lib/api/publisher-options.d.ts.map deleted file mode 100644 index 01fdfda1a..000000000 --- a/lib/api/publisher-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6CAA6C;IAC7C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,GAAG,CAAC;QACd,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,GAAG,CAAC;KACb,CAAC;IACF;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B"} \ No newline at end of file diff --git a/lib/api/publisher-options.js b/lib/api/publisher-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/publisher-publish-options.d.ts b/lib/api/publisher-publish-options.d.ts deleted file mode 100644 index e849f0773..000000000 --- a/lib/api/publisher-publish-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Publisher.publish}. - * @public - */ -export interface PublisherPublishOptions { -} -//# sourceMappingURL=publisher-publish-options.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-publish-options.d.ts.map b/lib/api/publisher-publish-options.d.ts.map deleted file mode 100644 index d43326216..000000000 --- a/lib/api/publisher-publish-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-publish-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-publish-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;CAAG"} \ No newline at end of file diff --git a/lib/api/publisher-publish-options.js b/lib/api/publisher-publish-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/publisher-state.d.ts b/lib/api/publisher-state.d.ts deleted file mode 100644 index facc5009e..000000000 --- a/lib/api/publisher-state.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * {@link Publisher} state. - * @remarks - * The {@link Publisher} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Publisher | | v v - * Constructed -> Initial -> Published -> Unpublished -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -export declare enum PublisherState { - Initial = "Initial", - Published = "Published", - Unpublished = "Unpublished", - Terminated = "Terminated" -} -//# sourceMappingURL=publisher-state.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-state.d.ts.map b/lib/api/publisher-state.d.ts.map deleted file mode 100644 index dd3f6b0b6..000000000 --- a/lib/api/publisher-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-state.d.ts","sourceRoot":"","sources":["../../src/api/publisher-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,WAAW,gBAAgB;IAC3B,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/publisher-state.js b/lib/api/publisher-state.js deleted file mode 100644 index 28a86a28c..000000000 --- a/lib/api/publisher-state.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * {@link Publisher} state. - * @remarks - * The {@link Publisher} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Publisher | | v v - * Constructed -> Initial -> Published -> Unpublished -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -export var PublisherState; -(function (PublisherState) { - PublisherState["Initial"] = "Initial"; - PublisherState["Published"] = "Published"; - PublisherState["Unpublished"] = "Unpublished"; - PublisherState["Terminated"] = "Terminated"; -})(PublisherState || (PublisherState = {})); diff --git a/lib/api/publisher-unpublish-options.d.ts b/lib/api/publisher-unpublish-options.d.ts deleted file mode 100644 index 09d3c157a..000000000 --- a/lib/api/publisher-unpublish-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Publisher.unpublish}. - * @public - */ -export interface PublisherUnpublishOptions { -} -//# sourceMappingURL=publisher-unpublish-options.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher-unpublish-options.d.ts.map b/lib/api/publisher-unpublish-options.d.ts.map deleted file mode 100644 index 99a1f229c..000000000 --- a/lib/api/publisher-unpublish-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher-unpublish-options.d.ts","sourceRoot":"","sources":["../../src/api/publisher-unpublish-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,yBAAyB;CAAG"} \ No newline at end of file diff --git a/lib/api/publisher-unpublish-options.js b/lib/api/publisher-unpublish-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/publisher.d.ts b/lib/api/publisher.d.ts deleted file mode 100644 index e62f5ac78..000000000 --- a/lib/api/publisher.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { IncomingResponseMessage, OutgoingPublishRequest, URI } from "../core"; -import { Emitter } from "./emitter"; -import { PublisherOptions } from "./publisher-options"; -import { PublisherPublishOptions } from "./publisher-publish-options"; -import { PublisherState } from "./publisher-state"; -import { PublisherUnpublishOptions } from "./publisher-unpublish-options"; -import { UserAgent } from "./user-agent"; -/** - * A publisher publishes a publication (outgoing PUBLISH). - * @public - */ -export declare class Publisher { - private event; - private options; - private target; - private pubRequestBody; - private pubRequestExpires; - private pubRequestEtag; - private publishRefreshTimer; - private disposed; - private id; - private logger; - private request; - private userAgent; - /** The publication state. */ - private _state; - /** Emits when the registration state changes. */ - private _stateEventEmitter; - /** - * Constructs a new instance of the `Publisher` class. - * - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, eventType: string, options?: PublisherOptions); - /** - * Destructor. - */ - dispose(): Promise; - /** The publication state. */ - get state(): PublisherState; - /** Emits when the publisher state changes. */ - get stateChange(): Emitter; - /** - * Publish. - * @param content - Body to publish - */ - publish(content: string, options?: PublisherPublishOptions): Promise; - /** - * Unpublish. - */ - unpublish(options?: PublisherUnpublishOptions): Promise; - /** @internal */ - protected receiveResponse(response: IncomingResponseMessage): void; - /** @internal */ - protected send(): OutgoingPublishRequest; - private refreshRequest; - private sendPublishRequest; - /** - * Transition publication state. - */ - private stateTransition; -} -//# sourceMappingURL=publisher.d.ts.map \ No newline at end of file diff --git a/lib/api/publisher.d.ts.map b/lib/api/publisher.d.ts.map deleted file mode 100644 index 4e37de760..000000000 --- a/lib/api/publisher.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../../src/api/publisher.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,uBAAuB,EAEvB,sBAAsB,EAEtB,GAAG,EACJ,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAmB;IAClC,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,mBAAmB,CAAqB;IAEhD,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B,6BAA6B;IAC7B,OAAO,CAAC,MAAM,CAA0C;IACxD,iDAAiD;IACjD,OAAO,CAAC,kBAAkB,CAA8B;IAExD;;;;;;;OAOG;gBACgB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IA4D1G;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA2B/B,6BAA6B;IAC7B,IAAW,KAAK,IAAI,cAAc,CAEjC;IAED,8CAA8C;IAC9C,IAAW,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAEhD;IAED;;;OAGG;IAEI,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IAyBrF;;OAEG;IAEI,SAAS,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBxE,gBAAgB;IAChB,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA+FlE,gBAAgB;IAChB,SAAS,CAAC,IAAI,IAAI,sBAAsB;IAUxC,OAAO,CAAC,cAAc;IAqBtB,OAAO,CAAC,kBAAkB;IA0C1B;;OAEG;IACH,OAAO,CAAC,eAAe;CA2CxB"} \ No newline at end of file diff --git a/lib/api/publisher.js b/lib/api/publisher.js deleted file mode 100644 index 256ec2d7f..000000000 --- a/lib/api/publisher.js +++ /dev/null @@ -1,326 +0,0 @@ -import { C, fromBodyLegacy } from "../core"; -import { EmitterImpl } from "./emitter"; -import { PublisherState } from "./publisher-state"; -/** - * A publisher publishes a publication (outgoing PUBLISH). - * @public - */ -export class Publisher { - /** - * Constructs a new instance of the `Publisher` class. - * - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - Request URI identifying the target of the message. - * @param eventType - The event type identifying the published document. - * @param options - Options bucket. See {@link PublisherOptions} for details. - */ - constructor(userAgent, targetURI, eventType, options = {}) { - this.disposed = false; - /** The publication state. */ - this._state = PublisherState.Initial; - // state emitter - this._stateEventEmitter = new EmitterImpl(); - this.userAgent = userAgent; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.contentType = options.contentType || "text/plain"; - if (typeof options.expires !== "number" || options.expires % 1 !== 0) { - options.expires = 3600; - } - else { - options.expires = Number(options.expires); - } - if (typeof options.unpublishOnClose !== "boolean") { - options.unpublishOnClose = true; - } - this.target = targetURI; - this.event = eventType; - this.options = options; - this.pubRequestExpires = options.expires; - this.logger = userAgent.getLogger("sip.Publisher"); - const params = options.params || {}; - const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; - const toURI = params.toUri ? params.toUri : targetURI; - let body; - if (options.body && options.contentType) { - const contentDisposition = "render"; - const contentType = options.contentType; - const content = options.body; - body = { - contentDisposition, - contentType, - content - }; - } - const extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body); - // Identifier - this.id = this.target.toString() + ":" + this.event; - // Add to the user agent's publisher collection. - this.userAgent._publishers[this.id] = this; - } - /** - * Destructor. - */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's publisher collection - delete this.userAgent._publishers[this.id]; - // Send unpublish, if requested - if (this.options.unpublishOnClose && this.state === PublisherState.Published) { - return this.unpublish(); - } - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - this.pubRequestEtag = undefined; - return Promise.resolve(); - } - /** The publication state. */ - get state() { - return this._state; - } - /** Emits when the publisher state changes. */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * Publish. - * @param content - Body to publish - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - publish(content, options = {}) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // is Initial or Modify request - this.options.body = content; - this.pubRequestBody = this.options.body; - if (this.pubRequestExpires === 0) { - // This is Initial request after unpublish - if (this.options.expires === undefined) { - throw new Error("Expires undefined."); - } - this.pubRequestExpires = this.options.expires; - this.pubRequestEtag = undefined; - } - this.sendPublishRequest(); - return Promise.resolve(); - } - /** - * Unpublish. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - unpublish(options = {}) { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestExpires = 0; - if (this.pubRequestEtag !== undefined) { - this.sendPublishRequest(); - } - return Promise.resolve(); - } - /** @internal */ - receiveResponse(response) { - const statusCode = response.statusCode || 0; - switch (true) { - case /^1[0-9]{2}$/.test(statusCode.toString()): - break; - case /^2[0-9]{2}$/.test(statusCode.toString()): - // Set SIP-Etag - if (response.hasHeader("SIP-ETag")) { - this.pubRequestEtag = response.getHeader("SIP-ETag"); - } - else { - this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); - } - // Update Expire - if (response.hasHeader("Expires")) { - const expires = Number(response.getHeader("Expires")); - if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { - this.pubRequestExpires = expires; - } - else { - this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); - } - } - else { - this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); - } - if (this.pubRequestExpires !== 0) { - // Schedule refresh - this.publishRefreshTimer = setTimeout(() => this.refreshRequest(), this.pubRequestExpires * 900); - this.stateTransition(PublisherState.Published); - } - else { - this.stateTransition(PublisherState.Unpublished); - } - break; - case /^412$/.test(statusCode.toString()): - // 412 code means no matching ETag - possibly the PUBLISH expired - // Resubmit as new request, if the current request is not a "remove" - if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { - this.logger.warn("412 response to PUBLISH, recovering"); - this.pubRequestEtag = undefined; - if (this.options.body === undefined) { - throw new Error("Body undefined."); - } - this.publish(this.options.body); - } - else { - this.logger.warn("412 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.stateTransition(PublisherState.Unpublished); - this.stateTransition(PublisherState.Terminated); - } - break; - case /^423$/.test(statusCode.toString()): - // 423 code means we need to adjust the Expires interval up - if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { - const minExpires = Number(response.getHeader("Min-Expires")); - if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { - this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); - this.pubRequestExpires = minExpires; - if (this.options.body === undefined) { - throw new Error("Body undefined."); - } - this.publish(this.options.body); - } - else { - this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); - this.pubRequestExpires = 0; - this.stateTransition(PublisherState.Unpublished); - this.stateTransition(PublisherState.Terminated); - } - } - else { - this.logger.warn("423 response to PUBLISH, recovery failed"); - this.pubRequestExpires = 0; - this.stateTransition(PublisherState.Unpublished); - this.stateTransition(PublisherState.Terminated); - } - break; - default: - this.pubRequestExpires = 0; - this.stateTransition(PublisherState.Unpublished); - this.stateTransition(PublisherState.Terminated); - break; - } - // Do the cleanup - if (this.pubRequestExpires === 0) { - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - this.pubRequestBody = undefined; - this.pubRequestEtag = undefined; - } - } - /** @internal */ - send() { - return this.userAgent.userAgentCore.publish(this.request, { - onAccept: (response) => this.receiveResponse(response.message), - onProgress: (response) => this.receiveResponse(response.message), - onRedirect: (response) => this.receiveResponse(response.message), - onReject: (response) => this.receiveResponse(response.message), - onTrying: (response) => this.receiveResponse(response.message) - }); - } - refreshRequest() { - // Clean up before the run - if (this.publishRefreshTimer) { - clearTimeout(this.publishRefreshTimer); - this.publishRefreshTimer = undefined; - } - // This is Refresh request - this.pubRequestBody = undefined; - if (this.pubRequestEtag === undefined) { - throw new Error("Etag undefined"); - } - if (this.pubRequestExpires === 0) { - throw new Error("Expires zero"); - } - this.sendPublishRequest(); - } - sendPublishRequest() { - const reqOptions = Object.assign({}, this.options); - reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); - reqOptions.extraHeaders.push("Event: " + this.event); - reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); - if (this.pubRequestEtag !== undefined) { - reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); - } - const ruri = this.target; - const params = this.options.params || {}; - let bodyAndContentType; - if (this.pubRequestBody !== undefined) { - if (this.options.contentType === undefined) { - throw new Error("Content type undefined."); - } - bodyAndContentType = { - body: this.pubRequestBody, - contentType: this.options.contentType - }; - } - let body; - if (bodyAndContentType) { - body = fromBodyLegacy(bodyAndContentType); - } - this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body); - return this.send(); - } - /** - * Transition publication state. - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case PublisherState.Initial: - if (newState !== PublisherState.Published && - newState !== PublisherState.Unpublished && - newState !== PublisherState.Terminated) { - invalidTransition(); - } - break; - case PublisherState.Published: - if (newState !== PublisherState.Unpublished && newState !== PublisherState.Terminated) { - invalidTransition(); - } - break; - case PublisherState.Unpublished: - if (newState !== PublisherState.Published && newState !== PublisherState.Terminated) { - invalidTransition(); - } - break; - case PublisherState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Publication transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === PublisherState.Terminated) { - this.dispose(); - } - } -} diff --git a/lib/api/referral.d.ts b/lib/api/referral.d.ts deleted file mode 100644 index f107b7ccd..000000000 --- a/lib/api/referral.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { IncomingReferRequest, IncomingRequestMessage, NameAddrHeader, ResponseOptions } from "../core"; -import { Inviter } from "./inviter"; -import { InviterOptions } from "./inviter-options"; -import { Session } from "./session"; -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -export declare class Referral { - private incomingReferRequest; - private session; - private inviter; - /** @internal */ - constructor(incomingReferRequest: IncomingReferRequest, session: Session); - get referTo(): NameAddrHeader; - get referredBy(): string | undefined; - get replaces(): string | undefined; - /** Incoming REFER request message. */ - get request(): IncomingRequestMessage; - /** Accept the request. */ - accept(options?: ResponseOptions): Promise; - /** Reject the request. */ - reject(options?: ResponseOptions): Promise; - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - makeInviter(options?: InviterOptions): Inviter; -} -//# sourceMappingURL=referral.d.ts.map \ No newline at end of file diff --git a/lib/api/referral.d.ts.map b/lib/api/referral.d.ts.map deleted file mode 100644 index 14bdd1143..000000000 --- a/lib/api/referral.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"referral.d.ts","sourceRoot":"","sources":["../../src/api/referral.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AACxG,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC;;;GAGG;AACH,qBAAa,QAAQ;IAIA,OAAO,CAAC,oBAAoB;IAAwB,OAAO,CAAC,OAAO;IAHtF,OAAO,CAAC,OAAO,CAAsB;IAErC,gBAAgB;gBACW,oBAAoB,EAAE,oBAAoB,EAAU,OAAO,EAAE,OAAO;IAE/F,IAAW,OAAO,IAAI,cAAc,CAMnC;IAED,IAAW,UAAU,IAAI,MAAM,GAAG,SAAS,CAE1C;IAED,IAAW,QAAQ,IAAI,MAAM,GAAG,SAAS,CAExC;IAED,sCAAsC;IACtC,IAAW,OAAO,IAAI,sBAAsB,CAE3C;IAED,0BAA0B;IACnB,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,OAAO,CAAC,IAAI,CAAC;IAK5E,0BAA0B;IACnB,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD;;;;;;;;;;;;OAYG;IACI,WAAW,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO;CAuBtD"} \ No newline at end of file diff --git a/lib/api/referral.js b/lib/api/referral.js deleted file mode 100644 index 9f21b653e..000000000 --- a/lib/api/referral.js +++ /dev/null @@ -1,75 +0,0 @@ -import { NameAddrHeader } from "../core"; -/** - * A request to establish a {@link Session} elsewhere (incoming REFER). - * @public - */ -export class Referral { - /** @internal */ - constructor(incomingReferRequest, session) { - this.incomingReferRequest = incomingReferRequest; - this.session = session; - } - get referTo() { - const referTo = this.incomingReferRequest.message.parseHeader("refer-to"); - if (!(referTo instanceof NameAddrHeader)) { - throw new Error("Failed to parse Refer-To header."); - } - return referTo; - } - get referredBy() { - return this.incomingReferRequest.message.getHeader("referred-by"); - } - get replaces() { - return this.referTo.uri.getHeader("replaces"); - } - /** Incoming REFER request message. */ - get request() { - return this.incomingReferRequest.message; - } - /** Accept the request. */ - accept(options = { statusCode: 202 }) { - this.incomingReferRequest.accept(options); - return Promise.resolve(); - } - /** Reject the request. */ - reject(options) { - this.incomingReferRequest.reject(options); - return Promise.resolve(); - } - /** - * Creates an inviter which may be used to send an out of dialog INVITE request. - * - * @remarks - * This a helper method to create an Inviter which will execute the referral - * of the `Session` which was referred. The appropriate headers are set and - * the referred `Session` is linked to the new `Session`. Note that only a - * single instance of the `Inviter` will be created and returned (if called - * more than once a reference to the same `Inviter` will be returned every time). - * - * @param options - Options bucket. - * @param modifiers - Session description handler modifiers. - */ - makeInviter(options) { - if (this.inviter) { - return this.inviter; - } - const targetURI = this.referTo.uri.clone(); - targetURI.clearHeaders(); - options = options || {}; - const extraHeaders = (options.extraHeaders || []).slice(); - const replaces = this.replaces; - if (replaces) { - // decodeURIComponent is a holdover from 2c086eb4. Not sure that it is actually necessary - extraHeaders.push("Replaces: " + decodeURIComponent(replaces)); - } - const referredBy = this.referredBy; - if (referredBy) { - extraHeaders.push("Referred-By: " + referredBy); - } - options.extraHeaders = extraHeaders; - this.inviter = this.session.userAgent._makeInviter(targetURI, options); - this.inviter._referred = this.session; - this.session._referral = this.inviter; - return this.inviter; - } -} diff --git a/lib/api/registerer-options.d.ts b/lib/api/registerer-options.d.ts deleted file mode 100644 index 3657de030..000000000 --- a/lib/api/registerer-options.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { URI } from "../core"; -/** - * Options for {@link Registerer} constructor. - * @public - */ -export interface RegistererOptions { - /** Registration expiration time in seconds. */ - expires?: number; - /** Array of extra Contact header parameters. */ - extraContactHeaderParams?: Array; - /** Array of extra headers added to the REGISTER. */ - extraHeaders?: Array; - /** - * UUID to provide with "+sip.instance" Contact parameter. - * @defaultValue a randomly generated uuid - */ - instanceId?: string; - /** - * If true, constructor logs the registerer configuration. - * @defaultValue `true` - */ - logConfiguration?: boolean; - /** @deprecated TODO: provide alternative. */ - params?: { - fromDisplayName?: string; - fromTag?: string; - fromUri?: URI; - toDisplayName?: string; - toUri?: URI; - }; - /** - * Value to provide with "reg-id" Contact parameter. - * @defaultValue 1 - */ - regId?: number; - /** - * The URI of the registrar to send the REGISTER requests. - * @defaultValue domain portion of the user agent's uri - */ - registrar?: URI; -} -//# sourceMappingURL=registerer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-options.d.ts.map b/lib/api/registerer-options.d.ts.map deleted file mode 100644 index b77f84b43..000000000 --- a/lib/api/registerer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,gDAAgD;IAChD,wBAAwB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAEzC,oDAAoD;IACpD,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE7B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B,6CAA6C;IAC7C,MAAM,CAAC,EAAE;QACP,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,GAAG,CAAC;QACd,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,GAAG,CAAC;KACb,CAAC;IAEF;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,SAAS,CAAC,EAAE,GAAG,CAAC;CACjB"} \ No newline at end of file diff --git a/lib/api/registerer-options.js b/lib/api/registerer-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/registerer-register-options.d.ts b/lib/api/registerer-register-options.d.ts deleted file mode 100644 index 22140aa66..000000000 --- a/lib/api/registerer-register-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Registerer.register}. - * @public - */ -export interface RegistererRegisterOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=registerer-register-options.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-register-options.d.ts.map b/lib/api/registerer-register-options.d.ts.map deleted file mode 100644 index 77c1747b4..000000000 --- a/lib/api/registerer-register-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-register-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-register-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/registerer-register-options.js b/lib/api/registerer-register-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/registerer-state.d.ts b/lib/api/registerer-state.d.ts deleted file mode 100644 index de9c318ff..000000000 --- a/lib/api/registerer-state.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * {@link Registerer} state. - * @remarks - * The {@link Registerer} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Registerer | | v v - * Constructed -> Initial -> Registered -> Unregistered -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -export declare enum RegistererState { - Initial = "Initial", - Registered = "Registered", - Unregistered = "Unregistered", - Terminated = "Terminated" -} -//# sourceMappingURL=registerer-state.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-state.d.ts.map b/lib/api/registerer-state.d.ts.map deleted file mode 100644 index b14cf5168..000000000 --- a/lib/api/registerer-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-state.d.ts","sourceRoot":"","sources":["../../src/api/registerer-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,oBAAY,eAAe;IACzB,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,YAAY,iBAAiB;IAC7B,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/registerer-state.js b/lib/api/registerer-state.js deleted file mode 100644 index 3ae97e339..000000000 --- a/lib/api/registerer-state.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * {@link Registerer} state. - * @remarks - * The {@link Registerer} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * __________________________________________ - * | __________________________ | - * Registerer | | v v - * Constructed -> Initial -> Registered -> Unregistered -> Terminated - * | ^____________| ^ - * |______________________________| - * ``` - * @public - */ -export var RegistererState; -(function (RegistererState) { - RegistererState["Initial"] = "Initial"; - RegistererState["Registered"] = "Registered"; - RegistererState["Unregistered"] = "Unregistered"; - RegistererState["Terminated"] = "Terminated"; -})(RegistererState || (RegistererState = {})); diff --git a/lib/api/registerer-unregister-options.d.ts b/lib/api/registerer-unregister-options.d.ts deleted file mode 100644 index d2673f86d..000000000 --- a/lib/api/registerer-unregister-options.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Registerer.unregister}. - * @public - */ -export interface RegistererUnregisterOptions { - /** - * If true, unregister all contacts. - * @defaultValue false - */ - all?: boolean; - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=registerer-unregister-options.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer-unregister-options.d.ts.map b/lib/api/registerer-unregister-options.d.ts.map deleted file mode 100644 index 3f30ee432..000000000 --- a/lib/api/registerer-unregister-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer-unregister-options.d.ts","sourceRoot":"","sources":["../../src/api/registerer-unregister-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/registerer-unregister-options.js b/lib/api/registerer-unregister-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/registerer.d.ts b/lib/api/registerer.d.ts deleted file mode 100644 index 2df7146e7..000000000 --- a/lib/api/registerer.d.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { OutgoingRegisterRequest } from "../core"; -import { Emitter } from "./emitter"; -import { RegistererOptions } from "./registerer-options"; -import { RegistererRegisterOptions } from "./registerer-register-options"; -import { RegistererState } from "./registerer-state"; -import { RegistererUnregisterOptions } from "./registerer-unregister-options"; -import { UserAgent } from "./user-agent"; -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -export declare class Registerer { - private static readonly defaultExpires; - private disposed; - private id; - private expires; - private logger; - private options; - private request; - private userAgent; - private registrationExpiredTimer; - private registrationTimer; - /** The contacts returned from the most recent accepted REGISTER request. */ - private _contacts; - /** The number of seconds to wait before retrying to register. */ - private _retryAfter; - /** The registration state. */ - private _state; - /** Emits when the registration state changes. */ - private _stateEventEmitter; - /** True is waiting for final response to outstanding REGISTER request. */ - private _waiting; - /** Emits when waiting changes. */ - private _waitingEventEmitter; - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - constructor(userAgent: UserAgent, options?: RegistererOptions); - /** Default registerer options. */ - private static defaultOptions; - private static newUUID; - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - private static stripUndefinedProperties; - /** The registered contacts. */ - get contacts(): Array; - /** - * The number of seconds to wait before retrying to register. - * @defaultValue `undefined` - * @remarks - * When the server rejects a registration request, if it provides a suggested - * duration to wait before retrying, that value is available here when and if - * the state transitions to `Unsubscribed`. It is also available during the - * callback to `onReject` after a call to `register`. (Note that if the state - * if already `Unsubscribed`, a rejected request created by `register` will - * not cause the state to transition to `Unsubscribed`. One way to avoid this - * case is to dispose of `Registerer` when unregistered and create a new - * `Registerer` for any attempts to retry registering.) - * @example - * ```ts - * // Checking for retry after on state change - * registerer.stateChange.addListener((newState) => { - * switch (newState) { - * case RegistererState.Unregistered: - * const retryAfter = registerer.retryAfter; - * break; - * } - * }); - * - * // Checking for retry after on request rejection - * registerer.register({ - * requestDelegate: { - * onReject: () => { - * const retryAfter = registerer.retryAfter; - * } - * } - * }); - * ``` - */ - get retryAfter(): number | undefined; - /** The registration state. */ - get state(): RegistererState; - /** Emits when the registerer state changes. */ - get stateChange(): Emitter; - /** Destructor. */ - dispose(): Promise; - /** - * Sends the REGISTER request. - * @remarks - * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - register(options?: RegistererRegisterOptions): Promise; - /** - * Sends the REGISTER request with expires equal to zero. - * @remarks - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - unregister(options?: RegistererUnregisterOptions): Promise; - /** - * Clear registration timers. - */ - private clearTimers; - /** - * Generate Contact Header - */ - private generateContactHeader; - /** - * Helper function, called when registered. - */ - private registered; - /** - * Helper function, called when unregistered. - */ - private unregistered; - /** - * Helper function, called when terminated. - */ - private terminated; - /** - * Transition registration state. - */ - private stateTransition; - /** True if the registerer is currently waiting for final response to a REGISTER request. */ - private get waiting(); - /** Emits when the registerer waiting state changes. */ - private get waitingChange(); - /** - * Toggle waiting. - */ - private waitingToggle; - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - private waitingWarning; - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - private stateError; -} -//# sourceMappingURL=registerer.d.ts.map \ No newline at end of file diff --git a/lib/api/registerer.d.ts.map b/lib/api/registerer.d.ts.map deleted file mode 100644 index 312e5e61e..000000000 --- a/lib/api/registerer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registerer.d.ts","sourceRoot":"","sources":["../../src/api/registerer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,uBAAuB,EAA+C,MAAM,SAAS,CAAC;AACnH,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAEjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAO;IAE7C,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,SAAS,CAAY;IAE7B,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,iBAAiB,CAAqB;IAE9C,4EAA4E;IAC5E,OAAO,CAAC,SAAS,CAAqB;IAEtC,iEAAiE;IACjE,OAAO,CAAC,WAAW,CAAiC;IAEpD,8BAA8B;IAC9B,OAAO,CAAC,MAAM,CAA4C;IAC1D,iDAAiD;IACjD,OAAO,CAAC,kBAAkB,CAA+B;IAEzD,0EAA0E;IAC1E,OAAO,CAAC,QAAQ,CAAS;IACzB,kCAAkC;IAClC,OAAO,CAAC,oBAAoB,CAAuB;IAEnD;;;;OAIG;gBACgB,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,iBAAsB;IA+FxE,kCAAkC;IAClC,OAAO,CAAC,MAAM,CAAC,cAAc;IAc7B,OAAO,CAAC,MAAM,CAAC,OAAO;IAStB;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAWvC,+BAA+B;IAC/B,IAAW,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,CAEnC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,IAAW,UAAU,IAAI,MAAM,GAAG,SAAS,CAE1C;IAED,8BAA8B;IAC9B,IAAW,KAAK,IAAI,eAAe,CAElC;IAED,+CAA+C;IAC/C,IAAW,WAAW,IAAI,OAAO,CAAC,eAAe,CAAC,CAEjD;IAED,kBAAkB;IACX,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA6C/B;;;;;OAKG;IACI,QAAQ,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,uBAAuB,CAAC;IA8M1F;;;;OAIG;IACI,UAAU,CAAC,OAAO,GAAE,2BAAgC,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAgH9F;;OAEG;IACH,OAAO,CAAC,WAAW;IAYnB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAkB7B;;OAEG;IACH,OAAO,CAAC,UAAU;IAqBlB;;OAEG;IACH,OAAO,CAAC,YAAY;IAQpB;;OAEG;IACH,OAAO,CAAC,UAAU;IAQlB;;OAEG;IACH,OAAO,CAAC,eAAe;IA4CvB,4FAA4F;IAC5F,OAAO,KAAK,OAAO,GAElB;IAED,uDAAuD;IACvD,OAAO,KAAK,aAAa,GAExB;IAED;;OAEG;IACH,OAAO,CAAC,aAAa;IASrB,kFAAkF;IAClF,OAAO,CAAC,cAAc;IAUtB,kFAAkF;IAClF,OAAO,CAAC,UAAU;CAOnB"} \ No newline at end of file diff --git a/lib/api/registerer.js b/lib/api/registerer.js deleted file mode 100644 index 3c55715d3..000000000 --- a/lib/api/registerer.js +++ /dev/null @@ -1,661 +0,0 @@ -import { C, Grammar, URI } from "../core"; -import { EmitterImpl } from "./emitter"; -import { RequestPendingError } from "./exceptions"; -import { RegistererState } from "./registerer-state"; -/** - * A registerer registers a contact for an address of record (outgoing REGISTER). - * @public - */ -export class Registerer { - /** - * Constructs a new instance of the `Registerer` class. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param options - Options bucket. See {@link RegistererOptions} for details. - */ - constructor(userAgent, options = {}) { - this.disposed = false; - /** The contacts returned from the most recent accepted REGISTER request. */ - this._contacts = []; - /** The number of seconds to wait before retrying to register. */ - this._retryAfter = undefined; - /** The registration state. */ - this._state = RegistererState.Initial; - /** True is waiting for final response to outstanding REGISTER request. */ - this._waiting = false; - // state emitter - this._stateEventEmitter = new EmitterImpl(); - // waiting emitter - this._waitingEventEmitter = new EmitterImpl(); - // Set user agent - this.userAgent = userAgent; - // Default registrar is domain portion of user agent uri - const defaultUserAgentRegistrar = userAgent.configuration.uri.clone(); - defaultUserAgentRegistrar.user = undefined; - // Initialize configuration - this.options = Object.assign(Object.assign(Object.assign({}, Registerer.defaultOptions()), { registrar: defaultUserAgentRegistrar }), Registerer.stripUndefinedProperties(options)); - // Make sure we are not using references to array options - this.options.extraContactHeaderParams = (this.options.extraContactHeaderParams || []).slice(); - this.options.extraHeaders = (this.options.extraHeaders || []).slice(); - // Make sure we are not using references to registrar uri - if (!this.options.registrar) { - throw new Error("Registrar undefined."); - } - this.options.registrar = this.options.registrar.clone(); - // Set instanceId and regId conditional defaults and validate - if (this.options.regId && !this.options.instanceId) { - this.options.instanceId = Registerer.newUUID(); - } - else if (!this.options.regId && this.options.instanceId) { - this.options.regId = 1; - } - if (this.options.instanceId && Grammar.parse(this.options.instanceId, "uuid") === -1) { - throw new Error("Invalid instanceId."); - } - if (this.options.regId && this.options.regId < 0) { - throw new Error("Invalid regId."); - } - const registrar = this.options.registrar; - const fromURI = (this.options.params && this.options.params.fromUri) || userAgent.userAgentCore.configuration.aor; - const toURI = (this.options.params && this.options.params.toUri) || userAgent.configuration.uri; - const params = this.options.params || {}; - const extraHeaders = (options.extraHeaders || []).slice(); - // Build the request - this.request = userAgent.userAgentCore.makeOutgoingRequestMessage(C.REGISTER, registrar, fromURI, toURI, params, extraHeaders, undefined); - // Registration expires - this.expires = this.options.expires || Registerer.defaultExpires; - if (this.expires < 0) { - throw new Error("Invalid expires."); - } - // initialize logger - this.logger = userAgent.getLogger("sip.Registerer"); - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - Object.keys(this.options).forEach((key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value = this.options[key]; - switch (key) { - case "registrar": - this.logger.log("· " + key + ": " + value); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - }); - } - // Identifier - this.id = this.request.callId + this.request.from.parameters.tag; - // Add to the user agent's session collection. - this.userAgent._registerers[this.id] = this; - } - /** Default registerer options. */ - static defaultOptions() { - return { - expires: Registerer.defaultExpires, - extraContactHeaderParams: [], - extraHeaders: [], - logConfiguration: true, - instanceId: "", - params: {}, - regId: 0, - registrar: new URI("sip", "anonymous", "anonymous.invalid") - }; - } - // http://stackoverflow.com/users/109538/broofa - static newUUID() { - const UUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = Math.floor(Math.random() * 16); - const v = c === "x" ? r : (r % 4) + 8; - return v.toString(16); - }); - return UUID; - } - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - static stripUndefinedProperties(options) { - return Object.keys(options).reduce((object, key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (options[key] !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object[key] = options[key]; - } - return object; - }, {}); - } - /** The registered contacts. */ - get contacts() { - return this._contacts.slice(); - } - /** - * The number of seconds to wait before retrying to register. - * @defaultValue `undefined` - * @remarks - * When the server rejects a registration request, if it provides a suggested - * duration to wait before retrying, that value is available here when and if - * the state transitions to `Unsubscribed`. It is also available during the - * callback to `onReject` after a call to `register`. (Note that if the state - * if already `Unsubscribed`, a rejected request created by `register` will - * not cause the state to transition to `Unsubscribed`. One way to avoid this - * case is to dispose of `Registerer` when unregistered and create a new - * `Registerer` for any attempts to retry registering.) - * @example - * ```ts - * // Checking for retry after on state change - * registerer.stateChange.addListener((newState) => { - * switch (newState) { - * case RegistererState.Unregistered: - * const retryAfter = registerer.retryAfter; - * break; - * } - * }); - * - * // Checking for retry after on request rejection - * registerer.register({ - * requestDelegate: { - * onReject: () => { - * const retryAfter = registerer.retryAfter; - * } - * } - * }); - * ``` - */ - get retryAfter() { - return this._retryAfter; - } - /** The registration state. */ - get state() { - return this._state; - } - /** Emits when the registerer state changes. */ - get stateChange() { - return this._stateEventEmitter; - } - /** Destructor. */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.disposed = true; - this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's registerer collection - delete this.userAgent._registerers[this.id]; - // If registered, unregisters and resolves after final response received. - return new Promise((resolve) => { - const doClose = () => { - // If we are registered, unregister and resolve after our state changes - if (!this.waiting && this._state === RegistererState.Registered) { - this.stateChange.addListener(() => { - this.terminated(); - resolve(); - }, { once: true }); - this.unregister(); - return; - } - // Otherwise just resolve - this.terminated(); - resolve(); - }; - // If we are waiting for an outstanding request, wait for it to finish and then try closing. - // Otherwise just try closing. - if (this.waiting) { - this.waitingChange.addListener(() => { - doClose(); - }, { once: true }); - } - else { - doClose(); - } - }); - } - /** - * Sends the REGISTER request. - * @remarks - * If successful, sends re-REGISTER requests prior to registration expiration until `unsubscribe()` is called. - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - register(options = {}) { - if (this.state === RegistererState.Terminated) { - this.stateError(); - throw new Error("Registerer terminated. Unable to register."); - } - if (this.disposed) { - this.stateError(); - throw new Error("Registerer disposed. Unable to register."); - } - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - this.waitingWarning(); - const error = new RequestPendingError("REGISTER request already in progress, waiting for final response"); - return Promise.reject(error); - } - // Options - if (options.requestOptions) { - this.options = Object.assign(Object.assign({}, this.options), options.requestOptions); - } - // Extra headers - const extraHeaders = (this.options.extraHeaders || []).slice(); - extraHeaders.push("Contact: " + this.generateContactHeader(this.expires)); - // this is UA.C.ALLOWED_METHODS, removed to get around circular dependency - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - this.request.extraHeaders = extraHeaders; - this.waitingToggle(true); - const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: (response) => { - let expires; - // FIXME: This does NOT appear to be to spec and should be removed. - // I haven't found anywhere that an Expires header may be used in a response. - if (response.message.hasHeader("expires")) { - expires = Number(response.message.getHeader("expires")); - } - // 8. The registrar returns a 200 (OK) response. The response MUST - // contain Contact header field values enumerating all current - // bindings. Each Contact value MUST feature an "expires" - // parameter indicating its expiration interval chosen by the - // registrar. The response SHOULD include a Date header field. - // https://tools.ietf.org/html/rfc3261#section-10.3 - this._contacts = response.message.getHeaders("contact"); - let contacts = this._contacts.length; - if (!contacts) { - this.logger.error("No Contact header in response to REGISTER, dropping response."); - this.unregistered(); - return; - } - // The 200 (OK) response from the registrar contains a list of Contact - // fields enumerating all current bindings. The UA compares each - // contact address to see if it created the contact address, using - // comparison rules in Section 19.1.4. If so, it updates the expiration - // time interval according to the expires parameter or, if absent, the - // Expires field value. The UA then issues a REGISTER request for each - // of its bindings before the expiration interval has elapsed. - // https://tools.ietf.org/html/rfc3261#section-10.2.4 - let contact; - while (contacts--) { - contact = response.message.parseHeader("contact", contacts); - if (!contact) { - throw new Error("Contact undefined"); - } - if (contact.uri.user === this.userAgent.contact.uri.user) { - expires = Number(contact.getParam("expires")); - break; - } - contact = undefined; - } - // There must be a matching contact. - if (contact === undefined) { - this.logger.error("No Contact header pointing to us, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // The contact must have an expires. - if (expires === undefined) { - this.logger.error("Contact pointing to us is missing expires parameter, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // Save gruu values - if (contact.hasParam("temp-gruu")) { - const gruu = contact.getParam("temp-gruu"); - if (gruu) { - this.userAgent.contact.tempGruu = Grammar.URIParse(gruu.replace(/"/g, "")); - } - } - if (contact.hasParam("pub-gruu")) { - const gruu = contact.getParam("pub-gruu"); - if (gruu) { - this.userAgent.contact.pubGruu = Grammar.URIParse(gruu.replace(/"/g, "")); - } - } - this.registered(expires); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - this.waitingToggle(false); - }, - onProgress: (response) => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: (response) => { - this.logger.error("Redirect received. Not supported."); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - this.waitingToggle(false); - }, - onReject: (response) => { - if (response.message.statusCode === 423) { - // If a UA receives a 423 (Interval Too Brief) response, it MAY retry - // the registration after making the expiration interval of all contact - // addresses in the REGISTER request equal to or greater than the - // expiration interval within the Min-Expires header field of the 423 - // (Interval Too Brief) response. - // https://tools.ietf.org/html/rfc3261#section-10.2.8 - // - // The registrar MAY choose an expiration less than the requested - // expiration interval. If and only if the requested expiration - // interval is greater than zero AND smaller than one hour AND - // less than a registrar-configured minimum, the registrar MAY - // reject the registration with a response of 423 (Interval Too - // Brief). This response MUST contain a Min-Expires header field - // that states the minimum expiration interval the registrar is - // willing to honor. It then skips the remaining steps. - // https://tools.ietf.org/html/rfc3261#section-10.3 - if (!response.message.hasHeader("min-expires")) { - // This response MUST contain a Min-Expires header field - this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"); - this.unregistered(); - this.waitingToggle(false); - return; - } - // Increase our registration interval to the suggested minimum - this.expires = Number(response.message.getHeader("min-expires")); - // Attempt the registration again immediately - this.waitingToggle(false); - this.register(); - return; - } - this.logger.warn(`Failed to register, status code ${response.message.statusCode}`); - // The Retry-After header field can be used with a 500 (Server Internal - // Error) or 503 (Service Unavailable) response to indicate how long the - // service is expected to be unavailable to the requesting client... - // https://tools.ietf.org/html/rfc3261#section-20.33 - let retryAfterDuration = NaN; - if (response.message.statusCode === 500 || response.message.statusCode === 503) { - const header = response.message.getHeader("retry-after"); - if (header) { - retryAfterDuration = Number.parseInt(header, undefined); - } - } - // Set for the state change (if any) and the delegate callback (if any) - this._retryAfter = isNaN(retryAfterDuration) ? undefined : retryAfterDuration; - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - this._retryAfter = undefined; - this.waitingToggle(false); - }, - onTrying: (response) => { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return Promise.resolve(outgoingRegisterRequest); - } - /** - * Sends the REGISTER request with expires equal to zero. - * @remarks - * Rejects with `RequestPendingError` if a REGISTER request is already in progress. - */ - unregister(options = {}) { - if (this.state === RegistererState.Terminated) { - this.stateError(); - throw new Error("Registerer terminated. Unable to register."); - } - if (this.disposed) { - if (this.state !== RegistererState.Registered) { - // allows unregister while disposing and registered - this.stateError(); - throw new Error("Registerer disposed. Unable to register."); - } - } - // UAs MUST NOT send a new registration (that is, containing new Contact - // header field values, as opposed to a retransmission) until they have - // received a final response from the registrar for the previous one or - // the previous REGISTER request has timed out. - // https://tools.ietf.org/html/rfc3261#section-10.2 - if (this.waiting) { - this.waitingWarning(); - const error = new RequestPendingError("REGISTER request already in progress, waiting for final response"); - return Promise.reject(error); - } - if (this._state !== RegistererState.Registered && !options.all) { - this.logger.warn("Not currently registered, but sending an unregister anyway."); - } - // Extra headers - const extraHeaders = ((options.requestOptions && options.requestOptions.extraHeaders) || []).slice(); - this.request.extraHeaders = extraHeaders; - // Registrations are soft state and expire unless refreshed, but can - // also be explicitly removed. A client can attempt to influence the - // expiration interval selected by the registrar as described in Section - // 10.2.1. A UA requests the immediate removal of a binding by - // specifying an expiration interval of "0" for that contact address in - // a REGISTER request. UAs SHOULD support this mechanism so that - // bindings can be removed before their expiration interval has passed. - // - // The REGISTER-specific Contact header field value of "*" applies to - // all registrations, but it MUST NOT be used unless the Expires header - // field is present with a value of "0". - // https://tools.ietf.org/html/rfc3261#section-10.2.2 - if (options.all) { - extraHeaders.push("Contact: *"); - extraHeaders.push("Expires: 0"); - } - else { - extraHeaders.push("Contact: " + this.generateContactHeader(0)); - } - // Call-ID: All registrations from a UAC SHOULD use the same Call-ID - // header field value for registrations sent to a particular - // registrar. - // - // CSeq: The CSeq value guarantees proper ordering of REGISTER - // requests. A UA MUST increment the CSeq value by one for each - // REGISTER request with the same Call-ID. - // https://tools.ietf.org/html/rfc3261#section-10.2 - this.request.cseq++; - this.request.setHeader("cseq", this.request.cseq + " REGISTER"); - // Pre-emptive clear the registration timer to avoid a race condition where - // this timer fires while waiting for a final response to the unsubscribe. - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - this.waitingToggle(true); - const outgoingRegisterRequest = this.userAgent.userAgentCore.register(this.request, { - onAccept: (response) => { - this._contacts = response.message.getHeaders("contact"); // Update contacts - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - this.waitingToggle(false); - }, - onProgress: (response) => { - if (options.requestDelegate && options.requestDelegate.onProgress) { - options.requestDelegate.onProgress(response); - } - }, - onRedirect: (response) => { - this.logger.error("Unregister redirected. Not currently supported."); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onRedirect) { - options.requestDelegate.onRedirect(response); - } - this.waitingToggle(false); - }, - onReject: (response) => { - this.logger.error(`Unregister rejected with status code ${response.message.statusCode}`); - this.unregistered(); - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - this.waitingToggle(false); - }, - onTrying: (response) => { - if (options.requestDelegate && options.requestDelegate.onTrying) { - options.requestDelegate.onTrying(response); - } - } - }); - return Promise.resolve(outgoingRegisterRequest); - } - /** - * Clear registration timers. - */ - clearTimers() { - if (this.registrationTimer !== undefined) { - clearTimeout(this.registrationTimer); - this.registrationTimer = undefined; - } - if (this.registrationExpiredTimer !== undefined) { - clearTimeout(this.registrationExpiredTimer); - this.registrationExpiredTimer = undefined; - } - } - /** - * Generate Contact Header - */ - generateContactHeader(expires) { - let contact = this.userAgent.contact.toString(); - if (this.options.regId && this.options.instanceId) { - contact += ";reg-id=" + this.options.regId; - contact += ';+sip.instance=""'; - } - if (this.options.extraContactHeaderParams) { - this.options.extraContactHeaderParams.forEach((header) => { - contact += ";" + header; - }); - } - contact += ";expires=" + expires; - return contact; - } - /** - * Helper function, called when registered. - */ - registered(expires) { - this.clearTimers(); - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - this.registrationTimer = setTimeout(() => { - this.registrationTimer = undefined; - this.register(); - }, expires * 1000 - 3000); - // We are unregistered if the registration expires. - this.registrationExpiredTimer = setTimeout(() => { - this.logger.warn("Registration expired"); - this.unregistered(); - }, expires * 1000); - if (this._state !== RegistererState.Registered) { - this.stateTransition(RegistererState.Registered); - } - } - /** - * Helper function, called when unregistered. - */ - unregistered() { - this.clearTimers(); - if (this._state !== RegistererState.Unregistered) { - this.stateTransition(RegistererState.Unregistered); - } - } - /** - * Helper function, called when terminated. - */ - terminated() { - this.clearTimers(); - if (this._state !== RegistererState.Terminated) { - this.stateTransition(RegistererState.Terminated); - } - } - /** - * Transition registration state. - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case RegistererState.Initial: - if (newState !== RegistererState.Registered && - newState !== RegistererState.Unregistered && - newState !== RegistererState.Terminated) { - invalidTransition(); - } - break; - case RegistererState.Registered: - if (newState !== RegistererState.Unregistered && newState !== RegistererState.Terminated) { - invalidTransition(); - } - break; - case RegistererState.Unregistered: - if (newState !== RegistererState.Registered && newState !== RegistererState.Terminated) { - invalidTransition(); - } - break; - case RegistererState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Registration transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === RegistererState.Terminated) { - this.dispose(); - } - } - /** True if the registerer is currently waiting for final response to a REGISTER request. */ - get waiting() { - return this._waiting; - } - /** Emits when the registerer waiting state changes. */ - get waitingChange() { - return this._waitingEventEmitter; - } - /** - * Toggle waiting. - */ - waitingToggle(waiting) { - if (this._waiting === waiting) { - throw new Error(`Invalid waiting transition from ${this._waiting} to ${waiting}`); - } - this._waiting = waiting; - this.logger.log(`Waiting toggled to ${this._waiting}`); - this._waitingEventEmitter.emit(this._waiting); - } - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - waitingWarning() { - let message = "An attempt was made to send a REGISTER request while a prior one was still in progress."; - message += " RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response"; - message += " from the registrar for the previous one or the previous REGISTER request has timed out."; - message += " Note that if the transport disconnects, you still must wait for the prior request to time out before"; - message += - " sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer."; - this.logger.warn(message); - } - /** Hopefully helpful as the standard behavior has been found to be unexpected. */ - stateError() { - const reason = this.state === RegistererState.Terminated ? "is in 'Terminated' state" : "has been disposed"; - let message = `An attempt was made to send a REGISTER request when the Registerer ${reason}.`; - message += " The Registerer transitions to 'Terminated' when Registerer.dispose() is called."; - message += " Perhaps you called UserAgent.stop() which dipsoses of all Registerers?"; - this.logger.error(message); - } -} -Registerer.defaultExpires = 600; diff --git a/lib/api/session-bye-options.d.ts b/lib/api/session-bye-options.d.ts deleted file mode 100644 index dd51797cd..000000000 --- a/lib/api/session-bye-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Session.bye}. - * @public - */ -export interface SessionByeOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=session-bye-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-bye-options.d.ts.map b/lib/api/session-bye-options.d.ts.map deleted file mode 100644 index 065612db2..000000000 --- a/lib/api/session-bye-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-bye-options.d.ts","sourceRoot":"","sources":["../../src/api/session-bye-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/session-bye-options.js b/lib/api/session-bye-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-delegate.d.ts b/lib/api/session-delegate.d.ts deleted file mode 100644 index ceb0e42b3..000000000 --- a/lib/api/session-delegate.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { IncomingRequestMessage } from "../core"; -import { Bye } from "./bye"; -import { Info } from "./info"; -import { Message } from "./message"; -import { Notification } from "./notification"; -import { Referral } from "./referral"; -import { SessionDescriptionHandler } from "./session-description-handler"; -/** - * Delegate for {@link Session}. - * @public - */ -export interface SessionDelegate { - /** - * Called upon receiving an incoming in dialog BYE request. - * @param bye - The bye. - */ - onBye?(bye: Bye): void; - /** - * Called upon receiving an incoming in dialog INFO request. - * @param info - The info. - */ - onInfo?(info: Info): void; - /** - * Called upon receiving an incoming in dialog INVITE request. - * @param invite - The invite. - */ - onInvite?(request: IncomingRequestMessage, response: string, statusCode: number): void; - /** - * Called upon receiving an incoming in dialog MESSAGE request. - * @param message - The message. - */ - onMessage?(message: Message): void; - /** - * Called upon receiving an incoming in dialog NOTIFY request. - * - * @remarks - * If a refer is in progress notifications are delivered to the referrers delegate. - * - * @param notification - The notification. - */ - onNotify?(notification: Notification): void; - /** - * Called upon receiving an incoming in dialog REFER request. - * @param referral - The referral. - */ - onRefer?(referral: Referral): void; - /** - * Called upon creating a SessionDescriptionHandler. - * - * @remarks - * It's recommended that the SessionDescriptionHandler be accessed via the `Session.sessionDescriptionHandler` property. - * However there are use cases where one needs access immediately after it is constructed and before it is utilized. - * Thus this callback. - * - * In most scenarios a single SessionDescriptionHandler will be created per Session - * in which case this callback will be called at most once and `provisional` will be `false`. - * - * However if reliable provisional responses are being supported and an INVITE is sent without SDP, - * one or more session description handlers will be created if remote offers are received in reliable provisional responses. - * When remote offers are received in reliable provisional responses, the `provisional` parameter will be `true`. - * When the `provisional` paramter is `true`, this callback may (or may not) be called again. - * If the session is ultimately established using a SessionDescriptionHandler which was not created provisionally, - * this callback will be called again and the `provisional` parameter will be `false`. - * If the session is ultimately established using a SessionDescriptionHandler which was created provisionally, - * this callback will not be called again. - * Note that if the session is ultimately established using a SessionDescriptionHandler which was created provisionally, - * the provisional SessionDescriptionHandler being utilized will be available via the `Session.sessionDescriptionHandler` property. - * - * @param sessionDescriptionHandler - The handler. - * @param provisional - True if created provisionally. - */ - onSessionDescriptionHandler?(sessionDescriptionHandler: SessionDescriptionHandler, provisional: boolean): void; -} -//# sourceMappingURL=session-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/session-delegate.d.ts.map b/lib/api/session-delegate.d.ts.map deleted file mode 100644 index 6ffd2058e..000000000 --- a/lib/api/session-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-delegate.d.ts","sourceRoot":"","sources":["../../src/api/session-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,KAAK,CAAC,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC;IAEvB;;;OAGG;IACH,MAAM,CAAC,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAE1B;;;OAGG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvF;;;OAGG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IAEnC;;;;;;;OAOG;IACH,QAAQ,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,OAAO,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEnC;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,2BAA2B,CAAC,CAAC,yBAAyB,EAAE,yBAAyB,EAAE,WAAW,EAAE,OAAO,GAAG,IAAI,CAAC;CAChH"} \ No newline at end of file diff --git a/lib/api/session-delegate.js b/lib/api/session-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-description-handler-factory.d.ts b/lib/api/session-description-handler-factory.d.ts deleted file mode 100644 index 276d48824..000000000 --- a/lib/api/session-description-handler-factory.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Session } from "./session"; -import { SessionDescriptionHandler } from "./session-description-handler"; -/** - * Factory for {@link SessionDescriptionHandler}. - * @public - */ -export interface SessionDescriptionHandlerFactory { - /** - * SessionDescriptionHandler factory function. - * @remarks - * The `options` are provided as part of the UserAgent configuration - * and passed through on every call to SessionDescriptionHandlerFactory's constructor. - */ - (session: Session, options?: object): SessionDescriptionHandler; -} -//# sourceMappingURL=session-description-handler-factory.d.ts.map \ No newline at end of file diff --git a/lib/api/session-description-handler-factory.d.ts.map b/lib/api/session-description-handler-factory.d.ts.map deleted file mode 100644 index ac2624e8d..000000000 --- a/lib/api/session-description-handler-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-factory.d.ts","sourceRoot":"","sources":["../../src/api/session-description-handler-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E;;;GAGG;AACH,MAAM,WAAW,gCAAgC;IAC/C;;;;;OAKG;IACH,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,yBAAyB,CAAC;CACjE"} \ No newline at end of file diff --git a/lib/api/session-description-handler-factory.js b/lib/api/session-description-handler-factory.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-description-handler.d.ts b/lib/api/session-description-handler.d.ts deleted file mode 100644 index 7a44b4435..000000000 --- a/lib/api/session-description-handler.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Delegate for {@link Session} offer/answer exchange. - * @public - */ -export interface SessionDescriptionHandler { - /** - * Destructor. - */ - close(): void; - /** - * Gets the local description from the underlying media implementation. - * @param options - Options object to be used by getDescription. - * @param modifiers - Array with one time use description modifiers. - * @returns Promise that resolves with the local description to be used for the session. - * Rejects with `ClosedSessionDescriptionHandlerError` when this method - * is called after close or when close occurs before complete. - */ - getDescription(options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; - /** - * Returns true if the Session Description Handler can handle the Content-Type described by a SIP message. - * @param contentType - The content type that is in the SIP Message. - * @returns True if the content type is handled by this session description handler. False otherwise. - */ - hasDescription(contentType: string): boolean; - /** - * Rolls back the current local/remote offer to the prior stable state. - */ - rollbackDescription?(): Promise; - /** - * Sets the remote description to the underlying media implementation. - * @param sessionDescription - The description provided by a SIP message to be set on the media implementation. - * @param options - Options object to be used by setDescription. - * @param modifiers - Array with one time use description modifiers. - * @returns Promise that resolves once the description is set. - * Rejects with `ClosedSessionDescriptionHandlerError` when this method - * is called after close or when close occurs before complete. - */ - setDescription(sdp: string, options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones - A string containing DTMF digits. - * @param options - Options object to be used by sendDtmf. - * @returns True if DTMF send is successful, false otherwise. - */ - sendDtmf(tones: string, options?: unknown): boolean; -} -/** - * Modifier for {@link SessionDescriptionHandler} offer/answer. - * @public - */ -export interface SessionDescriptionHandlerModifier { - (sessionDescription: RTCSessionDescriptionInit): Promise; -} -/** - * Options for {@link SessionDescriptionHandler} methods. - * @remarks - * These options are provided to various UserAgent methods (invite() for example) - * and passed through on calls to getDescription() and setDescription(). - * @public - */ -export interface SessionDescriptionHandlerOptions { - constraints?: object; -} -/** - * Message body content and type. - * @public - */ -export interface BodyAndContentType { - /** Message body content. */ - body: string; - /** Message body content type. */ - contentType: string; -} -//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/api/session-description-handler.d.ts.map b/lib/api/session-description-handler.d.ts.map deleted file mode 100644 index 36facd9ec..000000000 --- a/lib/api/session-description-handler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../src/api/session-description-handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,KAAK,IAAI,IAAI,CAAC;IAEd;;;;;;;OAOG;IACH,cAAc,CACZ,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAE/B;;;;OAIG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC;IAE7C;;OAEG;IACH,mBAAmB,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtC;;;;;;;;OAQG;IACH,cAAc,CACZ,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC;CACrD;AAED;;;GAGG;AACH,MAAM,WAAW,iCAAiC;IAChD,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;CACrF;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gCAAgC;IAC/C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;CACrB"} \ No newline at end of file diff --git a/lib/api/session-description-handler.js b/lib/api/session-description-handler.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-info-options.d.ts b/lib/api/session-info-options.d.ts deleted file mode 100644 index 25b01e787..000000000 --- a/lib/api/session-info-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Session.info}. - * @public - */ -export interface SessionInfoOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=session-info-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-info-options.d.ts.map b/lib/api/session-info-options.d.ts.map deleted file mode 100644 index 76455fbdc..000000000 --- a/lib/api/session-info-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-info-options.d.ts","sourceRoot":"","sources":["../../src/api/session-info-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/session-info-options.js b/lib/api/session-info-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-invite-options.d.ts b/lib/api/session-invite-options.d.ts deleted file mode 100644 index bcd3cf7e8..000000000 --- a/lib/api/session-invite-options.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -import { SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -/** - * Options for {@link Session.invite}. - * @public - */ -export interface SessionInviteOptions { - /** - * See `core` API. - */ - requestDelegate?: OutgoingRequestDelegate; - /** - * See `core` API. - */ - requestOptions?: RequestOptions; - /** - * Modifiers to pass to SessionDescriptionHandler during re-INVITE transaction. - */ - sessionDescriptionHandlerModifiers?: Array; - /** - * Options to pass to SessionDescriptionHandler during re-INVITE transaction. - */ - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - /** - * If true, send INVITE without SDP. Default is false. - */ - withoutSdp?: boolean; -} -//# sourceMappingURL=session-invite-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-invite-options.d.ts.map b/lib/api/session-invite-options.d.ts.map deleted file mode 100644 index f33e68e18..000000000 --- a/lib/api/session-invite-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-invite-options.d.ts","sourceRoot":"","sources":["../../src/api/session-invite-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,iCAAiC,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;OAEG;IACH,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E;;OAEG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IACpE;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/api/session-invite-options.js b/lib/api/session-invite-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-message-options.d.ts b/lib/api/session-message-options.d.ts deleted file mode 100644 index 0d528d345..000000000 --- a/lib/api/session-message-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -/** - * Options for {@link Session.message}. - * @public - */ -export interface SessionMessageOptions { - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=session-message-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-message-options.d.ts.map b/lib/api/session-message-options.d.ts.map deleted file mode 100644 index ca21f8b56..000000000 --- a/lib/api/session-message-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-message-options.d.ts","sourceRoot":"","sources":["../../src/api/session-message-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/session-message-options.js b/lib/api/session-message-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-options.d.ts b/lib/api/session-options.d.ts deleted file mode 100644 index ea5e9b0fc..000000000 --- a/lib/api/session-options.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { SessionDelegate } from "./session-delegate"; -/** - * Options for {@link Session} constructor. - * @public - */ -export interface SessionOptions { - delegate?: SessionDelegate; -} -//# sourceMappingURL=session-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-options.d.ts.map b/lib/api/session-options.d.ts.map deleted file mode 100644 index fd9033393..000000000 --- a/lib/api/session-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-options.d.ts","sourceRoot":"","sources":["../../src/api/session-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,eAAe,CAAC;CAC5B"} \ No newline at end of file diff --git a/lib/api/session-options.js b/lib/api/session-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-refer-options.d.ts b/lib/api/session-refer-options.d.ts deleted file mode 100644 index dc9c15a00..000000000 --- a/lib/api/session-refer-options.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { OutgoingRequestDelegate, RequestOptions } from "../core"; -import { Notification } from "./notification"; -/** - * Options for {@link Session.refer}. - * @public - */ -export interface SessionReferOptions { - /** Called upon receiving an incoming NOTIFY associated with a REFER. */ - onNotify?: (notification: Notification) => void; - /** See `core` API. */ - requestDelegate?: OutgoingRequestDelegate; - /** See `core` API. */ - requestOptions?: RequestOptions; -} -//# sourceMappingURL=session-refer-options.d.ts.map \ No newline at end of file diff --git a/lib/api/session-refer-options.d.ts.map b/lib/api/session-refer-options.d.ts.map deleted file mode 100644 index 5e4627256..000000000 --- a/lib/api/session-refer-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-refer-options.d.ts","sourceRoot":"","sources":["../../src/api/session-refer-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,wEAAwE;IACxE,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,CAAC;IAChD,sBAAsB;IACtB,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,sBAAsB;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/session-refer-options.js b/lib/api/session-refer-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/session-state.d.ts b/lib/api/session-state.d.ts deleted file mode 100644 index 6706732a4..000000000 --- a/lib/api/session-state.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * {@link Session} state. - * - * @remarks - * The {@link Session} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ___________________________________________________________ - * | ____________________________________________ | - * | | ____________________________ | | - * Session | | | v v v - * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated - * | |___________________________^ ^ - * |_______________________________________________| - * ``` - * @public - */ -export declare enum SessionState { - /** - * If `Inviter`, INVITE not sent yet. - * If `Invitation`, received INVITE (but no final response sent yet). - */ - Initial = "Initial", - /** - * If `Inviter`, sent INVITE and waiting for a final response. - * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). - */ - Establishing = "Establishing", - /** - * If `Inviter`, sent INVITE and received 200 final response and sent ACK. - * If `Invitation`, received INVITE and sent 200 final response. - */ - Established = "Established", - /** - * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). - * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE - * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). - */ - Terminating = "Terminating", - /** - * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). - * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). - */ - Terminated = "Terminated" -} -//# sourceMappingURL=session-state.d.ts.map \ No newline at end of file diff --git a/lib/api/session-state.d.ts.map b/lib/api/session-state.d.ts.map deleted file mode 100644 index 8427a136d..000000000 --- a/lib/api/session-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-state.d.ts","sourceRoot":"","sources":["../../src/api/session-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,oBAAY,YAAY;IACtB;;;OAGG;IACH,OAAO,YAAY;IACnB;;;OAGG;IACH,YAAY,iBAAiB;IAC7B;;;OAGG;IACH,WAAW,gBAAgB;IAC3B;;;;OAIG;IACH,WAAW,gBAAgB;IAC3B;;;OAGG;IACH,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/session-state.js b/lib/api/session-state.js deleted file mode 100644 index 693137b2a..000000000 --- a/lib/api/session-state.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * {@link Session} state. - * - * @remarks - * The {@link Session} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ___________________________________________________________ - * | ____________________________________________ | - * | | ____________________________ | | - * Session | | | v v v - * Constructed -> Initial -> Establishing -> Established -> Terminating -> Terminated - * | |___________________________^ ^ - * |_______________________________________________| - * ``` - * @public - */ -export var SessionState; -(function (SessionState) { - /** - * If `Inviter`, INVITE not sent yet. - * If `Invitation`, received INVITE (but no final response sent yet). - */ - SessionState["Initial"] = "Initial"; - /** - * If `Inviter`, sent INVITE and waiting for a final response. - * If `Invitation`, received INVITE and attempting to send 200 final response (but has not sent it yet). - */ - SessionState["Establishing"] = "Establishing"; - /** - * If `Inviter`, sent INVITE and received 200 final response and sent ACK. - * If `Invitation`, received INVITE and sent 200 final response. - */ - SessionState["Established"] = "Established"; - /** - * If `Inviter`, sent INVITE, sent CANCEL and now waiting for 487 final response to ACK (or 200 to ACK & BYE). - * If `Invitation`, received INVITE, sent 200 final response and now waiting on ACK and upon receipt will attempt BYE - * (as the protocol specification requires, before sending a BYE we must receive the ACK - so we are waiting). - */ - SessionState["Terminating"] = "Terminating"; - /** - * If `Inviter`, sent INVITE and received non-200 final response (or sent/received BYE after receiving 200). - * If `Invitation`, received INVITE and sent non-200 final response (or sent/received BYE after sending 200). - */ - SessionState["Terminated"] = "Terminated"; -})(SessionState || (SessionState = {})); diff --git a/lib/api/session.d.ts b/lib/api/session.d.ts deleted file mode 100644 index 421151e74..000000000 --- a/lib/api/session.d.ts +++ /dev/null @@ -1,360 +0,0 @@ -import { AckableIncomingResponseWithSession, Body, IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest, Logger, NameAddrHeader, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingMessageRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions, Session as SessionDialog, URI } from "../core"; -import { Emitter } from "./emitter"; -import { Inviter } from "./inviter"; -import { InviterOptions } from "./inviter-options"; -import { Notification } from "./notification"; -import { SessionByeOptions } from "./session-bye-options"; -import { SessionDelegate } from "./session-delegate"; -import { SessionDescriptionHandler, SessionDescriptionHandlerModifier, SessionDescriptionHandlerOptions } from "./session-description-handler"; -import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; -import { SessionInfoOptions } from "./session-info-options"; -import { SessionInviteOptions } from "./session-invite-options"; -import { SessionMessageOptions } from "./session-message-options"; -import { SessionOptions } from "./session-options"; -import { SessionReferOptions } from "./session-refer-options"; -import { SessionState } from "./session-state"; -import { UserAgent } from "./user-agent"; -/** - * A session provides real time communication between one or more participants. - * - * @remarks - * The transport behaves in a deterministic manner according to the - * the state defined in {@link SessionState}. - * @public - */ -export declare abstract class Session { - /** - * Property reserved for use by instance owner. - * @defaultValue `undefined` - */ - data: unknown; - /** - * The session delegate. - * @defaultValue `undefined` - */ - delegate: SessionDelegate | undefined; - /** @internal */ - _contact: string | undefined; - /** @internal */ - _referral: Inviter | undefined; - /** @internal */ - _replacee: Session | undefined; - /** @internal */ - protected _assertedIdentity: NameAddrHeader | undefined; - /** @internal */ - protected _dialog: SessionDialog | undefined; - /** @internal */ - protected _referralInviterOptions: InviterOptions | undefined; - /** @internal */ - protected _renderbody: string | undefined; - /** @internal */ - protected _rendertype: string | undefined; - /** If defined, NOTIFYs associated with a REFER subscription are delivered here. */ - private onNotify; - /** True if there is an outgoing re-INVITE request outstanding. */ - private pendingReinvite; - /** True if there is an incoming re-INVITE ACK request outstanding. */ - private pendingReinviteAck; - /** Dialogs session description handler. */ - private _sessionDescriptionHandler; - /** SDH modifiers for the initial INVITE transaction. */ - private _sessionDescriptionHandlerModifiers; - /** SDH options for the initial INVITE transaction. */ - private _sessionDescriptionHandlerOptions; - /** SDH modifiers for re-INVITE transactions. */ - private _sessionDescriptionHandlerModifiersReInvite; - /** SDH options for re-NVITE transactions.*/ - private _sessionDescriptionHandlerOptionsReInvite; - /** Session state. */ - private _state; - /** Session state emitter. */ - private _stateEventEmitter; - /** User agent. */ - private _userAgent; - /** - * The identity of the local user. - */ - abstract readonly localIdentity: NameAddrHeader; - /** - * The identity of the remote user. - */ - abstract readonly remoteIdentity: NameAddrHeader; - /** - * Logger. - */ - protected abstract logger: Logger; - /** @internal */ - protected abstract _id: string; - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - protected constructor(userAgent: UserAgent, options?: SessionOptions); - /** - * Destructor. - */ - dispose(): Promise; - /** - * The asserted identity of the remote user. - */ - get assertedIdentity(): NameAddrHeader | undefined; - /** - * The confirmed session dialog. - */ - get dialog(): SessionDialog | undefined; - /** - * A unique identifier for this session. - */ - get id(): string; - /** - * The session being replace by this one. - */ - get replacee(): Session | undefined; - /** - * Session description handler. - * @remarks - * If `this` is an instance of `Invitation`, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". - * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * Otherwise `undefined`. - */ - get sessionDescriptionHandler(): SessionDescriptionHandler | undefined; - /** - * Session description handler factory. - */ - get sessionDescriptionHandlerFactory(): SessionDescriptionHandlerFactory; - /** - * SDH modifiers for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerModifiers(): Array; - set sessionDescriptionHandlerModifiers(modifiers: Array); - /** - * SDH options for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerOptions(): SessionDescriptionHandlerOptions; - set sessionDescriptionHandlerOptions(options: SessionDescriptionHandlerOptions); - /** - * SDH modifiers for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerModifiersReInvite(): Array; - set sessionDescriptionHandlerModifiersReInvite(modifiers: Array); - /** - * SDH options for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerOptionsReInvite(): SessionDescriptionHandlerOptions; - set sessionDescriptionHandlerOptionsReInvite(options: SessionDescriptionHandlerOptions); - /** - * Session state. - */ - get state(): SessionState; - /** - * Session state change emitter. - */ - get stateChange(): Emitter; - /** - * The user agent. - */ - get userAgent(): UserAgent; - /** - * End the {@link Session}. Sends a BYE. - * @param options - Options bucket. See {@link SessionByeOptions} for details. - */ - bye(options?: SessionByeOptions): Promise; - /** - * Share {@link Info} with peer. Sends an INFO. - * @param options - Options bucket. See {@link SessionInfoOptions} for details. - */ - info(options?: SessionInfoOptions): Promise; - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. See {@link SessionInviteOptions} for details. - */ - invite(options?: SessionInviteOptions): Promise; - /** - * Deliver a {@link Message}. Sends a MESSAGE. - * @param options - Options bucket. See {@link SessionMessageOptions} for details. - */ - message(options?: SessionMessageOptions): Promise; - /** - * Proffer a {@link Referral}. Send a REFER. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - Options bucket. See {@link SessionReferOptions} for details. - */ - refer(referTo: URI | Session, options?: SessionReferOptions): Promise; - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * Send MESSAGE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _message(delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * Send REFER. - * @param onNotify - Notification callback. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _refer(onNotify?: (notification: Notification) => void, delegate?: OutgoingRequestDelegate, options?: RequestOptions): Promise; - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and send a BYE. - * Note that the BYE is sent in the dialog associated with the response - * which is not necessarily `this.dialog`. And, accordingly, the - * session state is not transitioned to terminated and session is not closed. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - protected ackAndBye(response: AckableIncomingResponseWithSession, statusCode?: number, reasonPhrase?: string): void; - /** - * Handle in dialog ACK request. - * @internal - */ - protected onAckRequest(request: IncomingAckRequest): Promise; - /** - * Handle in dialog BYE request. - * @internal - */ - protected onByeRequest(request: IncomingByeRequest): void; - /** - * Handle in dialog INFO request. - * @internal - */ - protected onInfoRequest(request: IncomingInfoRequest): void; - /** - * Handle in dialog INVITE request. - * @internal - */ - protected onInviteRequest(request: IncomingInviteRequest): void; - /** - * Handle in dialog MESSAGE request. - * @internal - */ - protected onMessageRequest(request: IncomingMessageRequest): void; - /** - * Handle in dialog NOTIFY request. - * @internal - */ - protected onNotifyRequest(request: IncomingNotifyRequest): void; - /** - * Handle in dialog PRACK request. - * @internal - */ - protected onPrackRequest(request: IncomingPrackRequest): void; - /** - * Handle in dialog REFER request. - * @internal - */ - protected onReferRequest(request: IncomingReferRequest): void; - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - protected generateResponseOfferAnswer(request: IncomingInviteRequest, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - protected generateResponseOfferAnswerInDialog(options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Get local offer. - * @internal - */ - protected getOffer(options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Rollback local/remote offer. - * @internal - */ - protected rollbackOffer(): Promise; - /** - * Set remote answer. - * @internal - */ - protected setAnswer(answer: Body, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * Set remote offer and get local answer. - * @internal - */ - protected setOfferAndGetAnswer(offer: Body, options: { - sessionDescriptionHandlerOptions?: SessionDescriptionHandlerOptions; - sessionDescriptionHandlerModifiers?: Array; - }): Promise; - /** - * SDH for confirmed dialog. - * @internal - */ - protected setSessionDescriptionHandler(sdh: SessionDescriptionHandler): void; - /** - * SDH for confirmed dialog. - * @internal - */ - protected setupSessionDescriptionHandler(): SessionDescriptionHandler; - /** - * Transition session state. - * @internal - */ - protected stateTransition(newState: SessionState): void; - private copyRequestOptions; - private getReasonHeaderValue; - private referExtraHeaders; - private referToString; -} -//# sourceMappingURL=session.d.ts.map \ No newline at end of file diff --git a/lib/api/session.d.ts.map b/lib/api/session.d.ts.map deleted file mode 100644 index 968531dcb..000000000 --- a/lib/api/session.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/api/session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,EAClC,IAAI,EAIJ,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,MAAM,EACN,cAAc,EACd,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EAErB,sBAAsB,EACtB,oBAAoB,EACpB,uBAAuB,EACvB,cAAc,EACd,OAAO,IAAI,aAAa,EAGxB,GAAG,EACJ,MAAM,SAAS,CAAC;AAIjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAGjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EACL,yBAAyB,EACzB,iCAAiC,EACjC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;GAOG;AACH,8BAAsB,OAAO;IAC3B;;;OAGG;IACI,IAAI,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACI,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IAK7C,gBAAgB;IACT,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,gBAAgB;IACT,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IACtC,gBAAgB;IACT,SAAS,EAAE,OAAO,GAAG,SAAS,CAAC;IAKtC,gBAAgB;IAChB,SAAS,CAAC,iBAAiB,EAAE,cAAc,GAAG,SAAS,CAAC;IACxD,gBAAgB;IAChB,SAAS,CAAC,OAAO,EAAE,aAAa,GAAG,SAAS,CAAC;IAC7C,gBAAgB;IAChB,SAAS,CAAC,uBAAuB,EAAE,cAAc,GAAG,SAAS,CAAC;IAC9D,gBAAgB;IAChB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,gBAAgB;IAChB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAE1C,mFAAmF;IACnF,OAAO,CAAC,QAAQ,CAAqD;IACrE,kEAAkE;IAClE,OAAO,CAAC,eAAe,CAAS;IAChC,sEAAsE;IACtE,OAAO,CAAC,kBAAkB,CAAS;IACnC,2CAA2C;IAC3C,OAAO,CAAC,0BAA0B,CAAwC;IAC1E,wDAAwD;IACxD,OAAO,CAAC,mCAAmC,CAAuD;IAClG,sDAAsD;IACtD,OAAO,CAAC,iCAAiC,CAA+C;IACxF,gDAAgD;IAChD,OAAO,CAAC,2CAA2C,CAAuD;IAC1G,4CAA4C;IAC5C,OAAO,CAAC,yCAAyC,CAA+C;IAChG,qBAAqB;IACrB,OAAO,CAAC,MAAM,CAAsC;IACpD,6BAA6B;IAC7B,OAAO,CAAC,kBAAkB,CAA4B;IACtD,kBAAkB;IAClB,OAAO,CAAC,UAAU,CAAY;IAE9B;;OAEG;IACH,kBAAyB,aAAa,EAAE,cAAc,CAAC;IAEvD;;OAEG;IACH,kBAAyB,cAAc,EAAE,cAAc,CAAC;IAExD;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAElC,gBAAgB;IAChB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAE/B;;;;OAIG;IACH,SAAS,aAAa,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,cAAmB;IAMxE;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAkD/B;;OAEG;IACH,IAAW,gBAAgB,IAAI,cAAc,GAAG,SAAS,CAExD;IAED;;OAEG;IACH,IAAW,MAAM,IAAI,aAAa,GAAG,SAAS,CAE7C;IAED;;OAEG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED;;OAEG;IACH,IAAW,QAAQ,IAAI,OAAO,GAAG,SAAS,CAEzC;IAED;;;;;;;;;;OAUG;IACH,IAAW,yBAAyB,IAAI,yBAAyB,GAAG,SAAS,CAE5E;IAED;;OAEG;IACH,IAAW,gCAAgC,IAAI,gCAAgC,CAE9E;IAED;;;;;;;OAOG;IACH,IAAW,kCAAkC,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAExF;IAED,IAAW,kCAAkC,CAAC,SAAS,EAAE,KAAK,CAAC,iCAAiC,CAAC,EAEhG;IAED;;;;;;;OAOG;IACH,IAAW,gCAAgC,IAAI,gCAAgC,CAE9E;IAED,IAAW,gCAAgC,CAAC,OAAO,EAAE,gCAAgC,EAEpF;IAED;;;;;;;OAOG;IACH,IAAW,0CAA0C,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAEhG;IAED,IAAW,0CAA0C,CAAC,SAAS,EAAE,KAAK,CAAC,iCAAiC,CAAC,EAExG;IAED;;;;;;;OAOG;IACH,IAAW,wCAAwC,IAAI,gCAAgC,CAEtF;IAED,IAAW,wCAAwC,CAAC,OAAO,EAAE,gCAAgC,EAE5F;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,YAAY,CAE/B;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,YAAY,CAAC,CAE9C;IAED;;OAEG;IACH,IAAW,SAAS,IAAI,SAAS,CAEhC;IAED;;;OAGG;IACI,GAAG,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAoDxE;;;OAGG;IACI,IAAI,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAa3E;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAyLjF;;;OAGG;IACI,OAAO,CAAC,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAapF;;;;OAIG;IACI,KAAK,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAgBtG;;;;;OAKG;IACI,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAmDtG;;;;;OAKG;IACI,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAQxG;;;;;OAKG;IACI,QAAQ,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAQ9G;;;;;;OAMG;IACI,MAAM,CACX,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,EAC/C,QAAQ,CAAC,EAAE,uBAAuB,EAClC,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,kBAAkB,CAAC;IAU9B;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,SAAS,CAAC,QAAQ,EAAE,kCAAkC,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI;IAUnH;;;OAGG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAmFlE;;;OAGG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAezD;;;OAGG;IACH,SAAS,CAAC,aAAa,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI;IAuB3D;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAiF/D;;;OAGG;IACH,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAejE;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAwB/D;;;OAGG;IAEH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI;IAU7D;;;OAGG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI;IAgC7D;;;;;;OAMG;IACH,SAAS,CAAC,2BAA2B,CACnC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GACA,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAY5B;;;;;OAKG;IACH,SAAS,CAAC,mCAAmC,CAAC,OAAO,EAAE;QACrD,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAuC7B;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE;QAC1B,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GAAG,OAAO,CAAC,IAAI,CAAC;IAyBjB;;;OAGG;IACH,SAAS,CAAC,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBxC;;;OAGG;IACH,SAAS,CAAC,SAAS,CACjB,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GACA,OAAO,CAAC,IAAI,CAAC;IAgChB;;;OAGG;IACH,SAAS,CAAC,oBAAoB,CAC5B,KAAK,EAAE,IAAI,EACX,OAAO,EAAE;QACP,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;QACpE,kCAAkC,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAC/E,GACA,OAAO,CAAC,IAAI,CAAC;IAoChB;;;OAGG;IACH,SAAS,CAAC,4BAA4B,CAAC,GAAG,EAAE,yBAAyB,GAAG,IAAI;IAO5E;;;OAGG;IACH,SAAS,CAAC,8BAA8B,IAAI,yBAAyB;IAcrE;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI;IAsDvD,OAAO,CAAC,kBAAkB;IAe1B,OAAO,CAAC,oBAAoB;IAS5B,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,aAAa;CAoBtB"} \ No newline at end of file diff --git a/lib/api/session.js b/lib/api/session.js deleted file mode 100644 index 8a908f467..000000000 --- a/lib/api/session.js +++ /dev/null @@ -1,1229 +0,0 @@ -import { fromBodyLegacy, getBody, Grammar, SessionState as SessionDialogState, SignalingState, URI } from "../core"; -import { getReasonPhrase } from "../core/messages/utils"; -import { AllowedMethods } from "../core/user-agent-core/allowed-methods"; -import { Bye } from "./bye"; -import { EmitterImpl } from "./emitter"; -import { ContentTypeUnsupportedError, RequestPendingError } from "./exceptions"; -import { Info } from "./info"; -import { Message } from "./message"; -import { Notification } from "./notification"; -import { Referral } from "./referral"; -import { SessionState } from "./session-state"; -/** - * A session provides real time communication between one or more participants. - * - * @remarks - * The transport behaves in a deterministic manner according to the - * the state defined in {@link SessionState}. - * @public - */ -export class Session { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - constructor(userAgent, options = {}) { - /** True if there is an outgoing re-INVITE request outstanding. */ - this.pendingReinvite = false; - /** True if there is an incoming re-INVITE ACK request outstanding. */ - this.pendingReinviteAck = false; - /** Session state. */ - this._state = SessionState.Initial; - this.delegate = options.delegate; - this._stateEventEmitter = new EmitterImpl(); - this._userAgent = userAgent; - } - /** - * Destructor. - */ - dispose() { - this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`); - // Remove from the user agent's session collection - delete this.userAgent._sessions[this.id]; - // Dispose of dialog media - if (this._sessionDescriptionHandler) { - this._sessionDescriptionHandler.close(); - // TODO: The SDH needs to remain defined as it will be called after it is closed in cases - // where an answer/offer arrives while the session is being torn down. There are a variety - // of circumstances where this can happen - sending a BYE during a re-INVITE for example. - // The code is currently written such that it lazily makes a new SDH when it needs one - // and one is not yet defined. Thus if we undefined it here, it will currently make a - // new one which is out of sync and then never gets cleaned up. - // - // The downside of leaving it defined are that calls this closed SDH will continue to be - // made (think setDescription) and those should/will fail. These failures are handled, but - // it would be nice to have it all coded up in a way where having an undefined SDH where - // one is expected throws an error. - // - // this._sessionDescriptionHandler = undefined; - } - switch (this.state) { - case SessionState.Initial: - break; // the Inviter/Invitation sub class dispose method handles this case - case SessionState.Establishing: - break; // the Inviter/Invitation sub class dispose method handles this case - case SessionState.Established: - return new Promise((resolve) => { - this._bye({ - // wait for the response to the BYE before resolving - onAccept: () => resolve(), - onRedirect: () => resolve(), - onReject: () => resolve() - }); - }); - case SessionState.Terminating: - break; // nothing to be done - case SessionState.Terminated: - break; // nothing to be done - default: - throw new Error("Unknown state."); - } - return Promise.resolve(); - } - /** - * The asserted identity of the remote user. - */ - get assertedIdentity() { - return this._assertedIdentity; - } - /** - * The confirmed session dialog. - */ - get dialog() { - return this._dialog; - } - /** - * A unique identifier for this session. - */ - get id() { - return this._id; - } - /** - * The session being replace by this one. - */ - get replacee() { - return this._replacee; - } - /** - * Session description handler. - * @remarks - * If `this` is an instance of `Invitation`, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". - * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, - * `sessionDescriptionHandler` will be defined when the session state changes to "established". - * Otherwise `undefined`. - */ - get sessionDescriptionHandler() { - return this._sessionDescriptionHandler; - } - /** - * Session description handler factory. - */ - get sessionDescriptionHandlerFactory() { - return this.userAgent.configuration.sessionDescriptionHandlerFactory; - } - /** - * SDH modifiers for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerModifiers() { - return this._sessionDescriptionHandlerModifiers || []; - } - set sessionDescriptionHandlerModifiers(modifiers) { - this._sessionDescriptionHandlerModifiers = modifiers.slice(); - } - /** - * SDH options for the initial INVITE transaction. - * @remarks - * Used in all cases when handling the initial INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Inviter.invite() or Invitation.accept(). - */ - get sessionDescriptionHandlerOptions() { - return this._sessionDescriptionHandlerOptions || {}; - } - set sessionDescriptionHandlerOptions(options) { - this._sessionDescriptionHandlerOptions = Object.assign({}, options); - } - /** - * SDH modifiers for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerModifiersReInvite() { - return this._sessionDescriptionHandlerModifiersReInvite || []; - } - set sessionDescriptionHandlerModifiersReInvite(modifiers) { - this._sessionDescriptionHandlerModifiersReInvite = modifiers.slice(); - } - /** - * SDH options for re-INVITE transactions. - * @remarks - * Used in all cases when handling a re-INVITE transaction as either UAC or UAS. - * May be set directly at anytime. - * May optionally be set via constructor option. - * May optionally be set via options passed to Session.invite(). - */ - get sessionDescriptionHandlerOptionsReInvite() { - return this._sessionDescriptionHandlerOptionsReInvite || {}; - } - set sessionDescriptionHandlerOptionsReInvite(options) { - this._sessionDescriptionHandlerOptionsReInvite = Object.assign({}, options); - } - /** - * Session state. - */ - get state() { - return this._state; - } - /** - * Session state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * The user agent. - */ - get userAgent() { - return this._userAgent; - } - /** - * End the {@link Session}. Sends a BYE. - * @param options - Options bucket. See {@link SessionByeOptions} for details. - */ - bye(options = {}) { - let message = "Session.bye() may only be called if established session."; - switch (this.state) { - case SessionState.Initial: - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " However Inviter.invite() has not yet been called."; - message += " Perhaps you should have called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " However Invitation.accept() has not yet been called."; - message += " Perhaps you should have called Invitation.reject()?"; - } - break; - case SessionState.Establishing: - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " However a dialog does not yet exist."; - message += " Perhaps you should have called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " However Invitation.accept() has not yet been called (or not yet resolved)."; - message += " Perhaps you should have called Invitation.reject()?"; - } - break; - case SessionState.Established: { - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._bye(requestDelegate, requestOptions); - } - case SessionState.Terminating: - message += " However this session is already terminating."; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof this.cancel === "function") { - message += " Perhaps you have already called Inviter.cancel()?"; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - else if (typeof this.reject === "function") { - message += " Perhaps you have already called Session.bye()?"; - } - break; - case SessionState.Terminated: - message += " However this session is already terminated."; - break; - default: - throw new Error("Unknown state"); - } - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - /** - * Share {@link Info} with peer. Sends an INFO. - * @param options - Options bucket. See {@link SessionInfoOptions} for details. - */ - info(options = {}) { - // guard session state - if (this.state !== SessionState.Established) { - const message = "Session.info() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._info(requestDelegate, requestOptions); - } - /** - * Renegotiate the session. Sends a re-INVITE. - * @param options - Options bucket. See {@link SessionInviteOptions} for details. - */ - invite(options = {}) { - this.logger.log("Session.invite"); - if (this.state !== SessionState.Established) { - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - if (this.pendingReinvite) { - return Promise.reject(new RequestPendingError("Reinvite in progress. Please wait until complete, then try again.")); - } - this.pendingReinvite = true; - // Modifiers and options for initial INVITE transaction - if (options.sessionDescriptionHandlerModifiers) { - this.sessionDescriptionHandlerModifiersReInvite = options.sessionDescriptionHandlerModifiers; - } - if (options.sessionDescriptionHandlerOptions) { - this.sessionDescriptionHandlerOptionsReInvite = options.sessionDescriptionHandlerOptions; - } - const delegate = { - onAccept: (response) => { - // A re-INVITE transaction has an offer/answer [RFC3264] exchange - // associated with it. The UAC (User Agent Client) generating a given - // re-INVITE can act as the offerer or as the answerer. A UAC willing - // to act as the offerer includes an offer in the re-INVITE. The UAS - // (User Agent Server) then provides an answer in a response to the - // re-INVITE. A UAC willing to act as answerer does not include an - // offer in the re-INVITE. The UAS then provides an offer in a response - // to the re-INVITE becoming, thus, the offerer. - // https://tools.ietf.org/html/rfc6141#section-1 - const body = getBody(response.message); - if (!body) { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Received 2xx response to re-INVITE without a session description"); - this.ackAndBye(response, 400, "Missing session description"); - this.stateTransition(SessionState.Terminated); - this.pendingReinvite = false; - return; - } - if (options.withoutSdp) { - // INVITE without SDP - set remote offer and send an answer in the ACK - const answerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.setOfferAndGetAnswer(body, answerOptions) - .then((answerBody) => { - response.ack({ body: answerBody }); - }) - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); - this.logger.error(error.message); - if (this.state === SessionState.Terminated) { - // A BYE should not be sent if already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - response.ack(); - } - else { - this.ackAndBye(response, 488, "Bad Media Description"); - this.stateTransition(SessionState.Terminated); - } - }) - .then(() => { - this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - else { - // INVITE with SDP - set remote answer and send an ACK - const answerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.setAnswer(body, answerOptions) - .then(() => { - response.ack(); - }) - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); - this.logger.error(error.message); - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // The ACK needs to be sent regardless as it was not handled by the transaction. - if (this.state !== SessionState.Terminated) { - this.ackAndBye(response, 488, "Bad Media Description"); - this.stateTransition(SessionState.Terminated); - } - else { - response.ack(); - } - }) - .then(() => { - this.pendingReinvite = false; - if (options.requestDelegate && options.requestDelegate.onAccept) { - options.requestDelegate.onAccept(response); - } - }); - } - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onProgress: (response) => { - return; - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect: (response) => { - return; - }, - onReject: (response) => { - this.logger.warn("Received a non-2xx response to re-INVITE"); - this.pendingReinvite = false; - if (options.withoutSdp) { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - } - else { - this.rollbackOffer() - .catch((error) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); - this.logger.error(error.message); - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // Note that the ACK was already sent by the transaction, so just need to send BYE. - if (this.state !== SessionState.Terminated) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - const extraHeaders = []; - extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); - this.dialog.bye(undefined, { extraHeaders }); - this.stateTransition(SessionState.Terminated); - } - }) - .then(() => { - if (options.requestDelegate && options.requestDelegate.onReject) { - options.requestDelegate.onReject(response); - } - }); - } - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTrying: (response) => { - return; - } - }; - const requestOptions = options.requestOptions || {}; - requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); - requestOptions.extraHeaders.push("Allow: " + AllowedMethods.toString()); - requestOptions.extraHeaders.push("Contact: " + this._contact); - // Just send an INVITE with no sdp... - if (options.withoutSdp) { - if (!this.dialog) { - this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - return Promise.resolve(this.dialog.invite(delegate, requestOptions)); - } - // Get an offer and send it in an INVITE - const offerOptions = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - return this.getOffer(offerOptions) - .then((offerBody) => { - if (!this.dialog) { - this.pendingReinvite = false; - throw new Error("Dialog undefined."); - } - requestOptions.body = offerBody; - return this.dialog.invite(delegate, requestOptions); - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.error("Failed to send re-INVITE"); - this.pendingReinvite = false; - throw error; - }); - } - /** - * Deliver a {@link Message}. Sends a MESSAGE. - * @param options - Options bucket. See {@link SessionMessageOptions} for details. - */ - message(options = {}) { - // guard session state - if (this.state !== SessionState.Established) { - const message = "Session.message() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - return this._message(requestDelegate, requestOptions); - } - /** - * Proffer a {@link Referral}. Send a REFER. - * @param referTo - The referral target. If a `Session`, a REFER w/Replaces is sent. - * @param options - Options bucket. See {@link SessionReferOptions} for details. - */ - refer(referTo, options = {}) { - // guard session state - if (this.state !== SessionState.Established) { - const message = "Session.refer() may only be called if established session."; - this.logger.error(message); - return Promise.reject(new Error(`Invalid session state ${this.state}`)); - } - const requestDelegate = options.requestDelegate; - const requestOptions = this.copyRequestOptions(options.requestOptions); - requestOptions.extraHeaders = requestOptions.extraHeaders - ? requestOptions.extraHeaders.concat(this.referExtraHeaders(this.referToString(referTo))) - : this.referExtraHeaders(this.referToString(referTo)); - return this._refer(options.onNotify, requestDelegate, requestOptions); - } - /** - * Send BYE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _bye(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - const dialog = this.dialog; - // The caller's UA MAY send a BYE for either confirmed or early dialogs, - // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT - // send a BYE on early dialogs. However, the callee's UA MUST NOT send a - // BYE on a confirmed dialog until it has received an ACK for its 2xx - // response or until the server transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - switch (dialog.sessionState) { - case SessionDialogState.Initial: - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - case SessionDialogState.Early: // Implementation choice - not sending BYE for early dialogs. - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - case SessionDialogState.AckWait: { - // This state only occurs if we are the callee. - this.stateTransition(SessionState.Terminating); // We're terminating - return new Promise((resolve) => { - dialog.delegate = { - // When ACK shows up, say BYE. - onAck: () => { - const request = dialog.bye(delegate, options); - this.stateTransition(SessionState.Terminated); - resolve(request); - return Promise.resolve(); - }, - // Or the server transaction times out before the ACK arrives. - onAckTimeout: () => { - const request = dialog.bye(delegate, options); - this.stateTransition(SessionState.Terminated); - resolve(request); - } - }; - }); - } - case SessionDialogState.Confirmed: { - const request = dialog.bye(delegate, options); - this.stateTransition(SessionState.Terminated); - return Promise.resolve(request); - } - case SessionDialogState.Terminated: - throw new Error(`Invalid dialog state ${dialog.sessionState}`); - default: - throw new Error("Unrecognized state."); - } - } - /** - * Send INFO. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _info(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.info(delegate, options)); - } - /** - * Send MESSAGE. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _message(delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - return Promise.resolve(this.dialog.message(delegate, options)); - } - /** - * Send REFER. - * @param onNotify - Notification callback. - * @param delegate - Request delegate. - * @param options - Request options bucket. - * @internal - */ - _refer(onNotify, delegate, options) { - // Using core session dialog - if (!this.dialog) { - return Promise.reject(new Error("Session dialog undefined.")); - } - // If set, deliver any in-dialog NOTIFY requests here... - this.onNotify = onNotify; - return Promise.resolve(this.dialog.refer(delegate, options)); - } - /** - * Send ACK and then BYE. There are unrecoverable errors which can occur - * while handling dialog forming and in-dialog INVITE responses and when - * they occur we ACK the response and send a BYE. - * Note that the BYE is sent in the dialog associated with the response - * which is not necessarily `this.dialog`. And, accordingly, the - * session state is not transitioned to terminated and session is not closed. - * @param inviteResponse - The response causing the error. - * @param statusCode - Status code for he reason phrase. - * @param reasonPhrase - Reason phrase for the BYE. - * @internal - */ - ackAndBye(response, statusCode, reasonPhrase) { - response.ack(); - const extraHeaders = []; - if (statusCode) { - extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); - } - // Using the dialog session associate with the response (which might not be this.dialog) - response.session.bye(undefined, { extraHeaders }); - } - /** - * Handle in dialog ACK request. - * @internal - */ - onAckRequest(request) { - this.logger.log("Session.onAckRequest"); - if (this.state !== SessionState.Established && this.state !== SessionState.Terminating) { - this.logger.error(`ACK received while in state ${this.state}, dropping request`); - return Promise.resolve(); - } - const dialog = this.dialog; - if (!dialog) { - throw new Error("Dialog undefined."); - } - // if received answer in ACK. - const answerOptions = { - sessionDescriptionHandlerOptions: this.pendingReinviteAck - ? this.sessionDescriptionHandlerOptionsReInvite - : this.sessionDescriptionHandlerOptions, - sessionDescriptionHandlerModifiers: this.pendingReinviteAck - ? this._sessionDescriptionHandlerModifiersReInvite - : this._sessionDescriptionHandlerModifiers - }; - // reset pending ACK flag - this.pendingReinviteAck = false; - switch (dialog.signalingState) { - case SignalingState.Initial: { - // State should never be reached as first reliable response must have answer/offer. - // So we must have never has sent an offer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(SessionState.Terminated); - return Promise.resolve(); - } - case SignalingState.Stable: { - // State we should be in. - // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. - const body = getBody(request.message); - // If the ACK doesn't have an answer, nothing to be done. - if (!body) { - return Promise.resolve(); - } - if (body.contentDisposition === "render") { - this._renderbody = body.content; - this._rendertype = body.contentType; - return Promise.resolve(); - } - if (body.contentDisposition !== "session") { - return Promise.resolve(); - } - return this.setAnswer(body, answerOptions).catch((error) => { - this.logger.error(error.message); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(SessionState.Terminated); - }); - } - case SignalingState.HaveLocalOffer: { - // State should never be reached as local offer would be answered by this ACK. - // So we must have received an ACK without an answer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(SessionState.Terminated); - return Promise.resolve(); - } - case SignalingState.HaveRemoteOffer: { - // State should never be reached as remote offer would be answered in first reliable response. - // So we must have never has sent an answer. - this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); - const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; - dialog.bye(undefined, { extraHeaders }); - this.stateTransition(SessionState.Terminated); - return Promise.resolve(); - } - case SignalingState.Closed: - throw new Error(`Invalid signaling state ${dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${dialog.signalingState}.`); - } - } - /** - * Handle in dialog BYE request. - * @internal - */ - onByeRequest(request) { - this.logger.log("Session.onByeRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`BYE received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onBye) { - const bye = new Bye(request); - this.delegate.onBye(bye); - } - else { - request.accept(); - } - this.stateTransition(SessionState.Terminated); - } - /** - * Handle in dialog INFO request. - * @internal - */ - onInfoRequest(request) { - this.logger.log("Session.onInfoRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`INFO received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onInfo) { - const info = new Info(request); - this.delegate.onInfo(info); - } - else { - // FIXME: TODO: We should reject request... - // - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - // https://tools.ietf.org/html/rfc6086#section-4.2.2 - request.accept(); - } - } - /** - * Handle in dialog INVITE request. - * @internal - */ - onInviteRequest(request) { - this.logger.log("Session.onInviteRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`INVITE received while in state ${this.state}, dropping request`); - return; - } - // set pending ACK flag - this.pendingReinviteAck = true; - // TODO: would be nice to have core track and set the Contact header, - // but currently the session which is setting it is holding onto it. - const extraHeaders = ["Contact: " + this._contact]; - // Handle P-Asserted-Identity - if (request.message.hasHeader("P-Asserted-Identity")) { - const header = request.message.getHeader("P-Asserted-Identity"); - if (!header) { - throw new Error("Header undefined."); - } - this._assertedIdentity = Grammar.nameAddrHeaderParse(header); - } - const options = { - sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptionsReInvite, - sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiersReInvite - }; - this.generateResponseOfferAnswerInDialog(options) - .then((body) => { - const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 200); - } - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.error("Failed to handle to re-INVITE request"); - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - this.logger.error(this.dialog.signalingState); - // If we don't have a local/remote offer... - if (this.dialog.signalingState === SignalingState.Stable) { - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - return; - } - // Otherwise rollback - this.rollbackOffer() - .then(() => { - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }) - .catch((errorRollback) => { - // No way to recover, so terminate session and mark as failed. - this.logger.error(errorRollback.message); - this.logger.error("Failed to rollback offer on re-INVITE request"); - const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here - // A BYE should only be sent if session is not already terminated. - // For example, a BYE may be sent/received while re-INVITE is outstanding. - // Note that the ACK was already sent by the transaction, so just need to send BYE. - if (this.state !== SessionState.Terminated) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - const extraHeadersBye = []; - extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); - this.dialog.bye(undefined, { extraHeaders }); - this.stateTransition(SessionState.Terminated); - } - if (this.delegate && this.delegate.onInvite) { - this.delegate.onInvite(request.message, outgoingResponse.message, 488); - } - }); - }); - } - /** - * Handle in dialog MESSAGE request. - * @internal - */ - onMessageRequest(request) { - this.logger.log("Session.onMessageRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`); - return; - } - if (this.delegate && this.delegate.onMessage) { - const message = new Message(request); - this.delegate.onMessage(message); - } - else { - request.accept(); - } - } - /** - * Handle in dialog NOTIFY request. - * @internal - */ - onNotifyRequest(request) { - this.logger.log("Session.onNotifyRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); - return; - } - // If this a NOTIFY associated with the progress of a REFER, - // look to delegate handling to the associated callback. - if (this.onNotify) { - const notification = new Notification(request); - this.onNotify(notification); - return; - } - // Otherwise accept the NOTIFY. - if (this.delegate && this.delegate.onNotify) { - const notification = new Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - } - /** - * Handle in dialog PRACK request. - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onPrackRequest(request) { - this.logger.log("Session.onPrackRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`PRACK received while in state ${this.state}, dropping request`); - return; - } - throw new Error("Unimplemented."); - } - /** - * Handle in dialog REFER request. - * @internal - */ - onReferRequest(request) { - this.logger.log("Session.onReferRequest"); - if (this.state !== SessionState.Established) { - this.logger.error(`REFER received while in state ${this.state}, dropping request`); - return; - } - // REFER is a SIP request and is constructed as defined in [1]. A REFER - // request MUST contain exactly one Refer-To header field value. - // https://tools.ietf.org/html/rfc3515#section-2.4.1 - if (!request.message.hasHeader("refer-to")) { - this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); - request.reject(); - return; - } - const referral = new Referral(request, this); - if (this.delegate && this.delegate.onRefer) { - this.delegate.onRefer(referral); - } - else { - this.logger.log("No delegate available to handle REFER, automatically accepting and following."); - referral - .accept() - .then(() => referral.makeInviter(this._referralInviterOptions).invite()) - .catch((error) => { - // FIXME: logging and eating error... - this.logger.error(error.message); - }); - } - } - /** - * Generate an offer or answer for a response to an INVITE request. - * If a remote offer was provided in the request, set the remote - * description and get a local answer. If a remote offer was not - * provided, generates a local offer. - * @internal - */ - generateResponseOfferAnswer(request, options) { - if (this.dialog) { - return this.generateResponseOfferAnswerInDialog(options); - } - const body = getBody(request.message); - if (!body || body.contentDisposition !== "session") { - return this.getOffer(options); - } - else { - return this.setOfferAndGetAnswer(body, options); - } - } - /** - * Generate an offer or answer for a response to an INVITE request - * when a dialog (early or otherwise) has already been established. - * This method may NOT be called if a dialog has yet to be established. - * @internal - */ - generateResponseOfferAnswerInDialog(options) { - if (!this.dialog) { - throw new Error("Dialog undefined."); - } - switch (this.dialog.signalingState) { - case SignalingState.Initial: - return this.getOffer(options); - case SignalingState.HaveLocalOffer: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - return Promise.resolve(undefined); - case SignalingState.HaveRemoteOffer: - if (!this.dialog.offer) { - throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`); - } - return this.setOfferAndGetAnswer(this.dialog.offer, options); - case SignalingState.Stable: - // o Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.state !== SessionState.Established) { - return Promise.resolve(undefined); - } - // In dialog INVITE without offer, get an offer for the response. - return this.getOffer(options); - case SignalingState.Closed: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - default: - throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); - } - } - /** - * Get local offer. - * @internal - */ - getOffer(options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - return sdh - .getDescription(sdhOptions, sdhModifiers) - .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) - .catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.getOffer: SDH getDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.getOffer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.getOffer: SDH getDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Rollback local/remote offer. - * @internal - */ - rollbackOffer() { - const sdh = this.setupSessionDescriptionHandler(); - if (sdh.rollbackDescription === undefined) { - return Promise.resolve(); - } - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - return sdh.rollbackDescription().catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.rollbackOffer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Set remote answer. - * @internal - */ - setAnswer(answer, options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - if (!sdh.hasDescription(answer.contentType)) { - return Promise.reject(new ContentTypeUnsupportedError()); - } - } - catch (error) { - this.logger.error("Session.setAnswer: SDH hasDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - try { - return sdh.setDescription(answer.content, sdhOptions, sdhModifiers).catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.setAnswer: SDH setDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.setAnswer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.setAnswer: SDH setDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * Set remote offer and get local answer. - * @internal - */ - setOfferAndGetAnswer(offer, options) { - const sdh = this.setupSessionDescriptionHandler(); - const sdhOptions = options.sessionDescriptionHandlerOptions; - const sdhModifiers = options.sessionDescriptionHandlerModifiers; - // This is intentionally written very defensively. Don't trust SDH to behave. - try { - if (!sdh.hasDescription(offer.contentType)) { - return Promise.reject(new ContentTypeUnsupportedError()); - } - } - catch (error) { - this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - try { - return sdh - .setDescription(offer.content, sdhOptions, sdhModifiers) - .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) - .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) - .catch((error) => { - // don't trust SDH to reject with Error - this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); - const e = error instanceof Error ? error : new Error("Session.setOfferAndGetAnswer unknown error."); - this.logger.error(e.message); - throw e; - }); - } - catch (error) { - // don't trust SDH to throw an Error - this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); - const e = error instanceof Error ? error : new Error(error); - this.logger.error(e.message); - return Promise.reject(e); - } - } - /** - * SDH for confirmed dialog. - * @internal - */ - setSessionDescriptionHandler(sdh) { - if (this._sessionDescriptionHandler) { - throw new Error("Session description handler defined."); - } - this._sessionDescriptionHandler = sdh; - } - /** - * SDH for confirmed dialog. - * @internal - */ - setupSessionDescriptionHandler() { - var _a; - if (this._sessionDescriptionHandler) { - return this._sessionDescriptionHandler; - } - this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onSessionDescriptionHandler) { - this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler, false); - } - return this._sessionDescriptionHandler; - } - /** - * Transition session state. - * @internal - */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case SessionState.Initial: - if (newState !== SessionState.Establishing && - newState !== SessionState.Established && - newState !== SessionState.Terminating && - newState !== SessionState.Terminated) { - invalidTransition(); - } - break; - case SessionState.Establishing: - if (newState !== SessionState.Established && - newState !== SessionState.Terminating && - newState !== SessionState.Terminated) { - invalidTransition(); - } - break; - case SessionState.Established: - if (newState !== SessionState.Terminating && newState !== SessionState.Terminated) { - invalidTransition(); - } - break; - case SessionState.Terminating: - if (newState !== SessionState.Terminated) { - invalidTransition(); - } - break; - case SessionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Transition - this._state = newState; - this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === SessionState.Terminated) { - this.dispose(); - } - } - copyRequestOptions(requestOptions = {}) { - const extraHeaders = requestOptions.extraHeaders ? requestOptions.extraHeaders.slice() : undefined; - const body = requestOptions.body - ? { - contentDisposition: requestOptions.body.contentDisposition || "render", - contentType: requestOptions.body.contentType || "text/plain", - content: requestOptions.body.content || "" - } - : undefined; - return { - extraHeaders, - body - }; - } - getReasonHeaderValue(code, reason) { - const cause = code; - let text = getReasonPhrase(code); - if (!text && reason) { - text = reason; - } - return "SIP;cause=" + cause + ';text="' + text + '"'; - } - referExtraHeaders(referTo) { - const extraHeaders = []; - extraHeaders.push("Referred-By: <" + this.userAgent.configuration.uri + ">"); - extraHeaders.push("Contact: " + this._contact); - extraHeaders.push("Allow: " + ["ACK", "CANCEL", "INVITE", "MESSAGE", "BYE", "OPTIONS", "INFO", "NOTIFY", "REFER"].toString()); - extraHeaders.push("Refer-To: " + referTo); - return extraHeaders; - } - referToString(target) { - let referTo; - if (target instanceof URI) { - // REFER without Replaces (Blind Transfer) - referTo = target.toString(); - } - else { - // REFER with Replaces (Attended Transfer) - if (!target.dialog) { - throw new Error("Dialog undefined."); - } - const displayName = target.remoteIdentity.friendlyName; - const remoteTarget = target.dialog.remoteTarget.toString(); - const callId = target.dialog.callId; - const remoteTag = target.dialog.remoteTag; - const localTag = target.dialog.localTag; - const replaces = encodeURIComponent(`${callId};to-tag=${remoteTag};from-tag=${localTag}`); - referTo = `"${displayName}" <${remoteTarget}?Replaces=${replaces}>`; - } - return referTo; - } -} diff --git a/lib/api/subscriber-options.d.ts b/lib/api/subscriber-options.d.ts deleted file mode 100644 index 61cfed12b..000000000 --- a/lib/api/subscriber-options.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { SubscriptionOptions } from "./subscription-options"; -/** - * Options for {@link Subscriber} constructor. - * @public - */ -export interface SubscriberOptions extends SubscriptionOptions { - expires?: number; - extraHeaders?: Array; - body?: string; - contentType?: string; -} -//# sourceMappingURL=subscriber-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscriber-options.d.ts.map b/lib/api/subscriber-options.d.ts.map deleted file mode 100644 index 0bebbff69..000000000 --- a/lib/api/subscriber-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscriber-options.d.ts","sourceRoot":"","sources":["../../src/api/subscriber-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE7D;;;GAGG;AACH,MAAM,WAAW,iBAAkB,SAAQ,mBAAmB;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"} \ No newline at end of file diff --git a/lib/api/subscriber-options.js b/lib/api/subscriber-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/subscriber-subscribe-options.d.ts b/lib/api/subscriber-subscribe-options.d.ts deleted file mode 100644 index 53ffaa836..000000000 --- a/lib/api/subscriber-subscribe-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Subscriber.subscribe}. - * @public - */ -export interface SubscriberSubscribeOptions { -} -//# sourceMappingURL=subscriber-subscribe-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscriber-subscribe-options.d.ts.map b/lib/api/subscriber-subscribe-options.d.ts.map deleted file mode 100644 index 4e315065c..000000000 --- a/lib/api/subscriber-subscribe-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscriber-subscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscriber-subscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,0BAA0B;CAAG"} \ No newline at end of file diff --git a/lib/api/subscriber-subscribe-options.js b/lib/api/subscriber-subscribe-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/subscriber.d.ts b/lib/api/subscriber.d.ts deleted file mode 100644 index 4481a27c0..000000000 --- a/lib/api/subscriber.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { IncomingNotifyRequest, IncomingResponse, OutgoingSubscribeRequest, URI } from "../core"; -import { SubscriberOptions } from "./subscriber-options"; -import { SubscriberSubscribeOptions } from "./subscriber-subscribe-options"; -import { Subscription } from "./subscription"; -import { SubscriptionUnsubscribeOptions } from "./subscription-unsubscribe-options"; -import { UserAgent } from "./user-agent"; -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.addListener((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -export declare class Subscriber extends Subscription { - private id; - private body; - private event; - private expires; - private extraHeaders; - private logger; - private outgoingRequestMessage; - private retryAfterTimer; - private subscriberRequest; - private targetURI; - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - constructor(userAgent: UserAgent, targetURI: URI, eventType: string, options?: SubscriberOptions); - /** - * Destructor. - * @internal - */ - dispose(): Promise; - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - subscribe(options?: SubscriberSubscribeOptions): Promise; - /** - * {@inheritDoc Subscription.unsubscribe} - */ - unsubscribe(options?: SubscriptionUnsubscribeOptions): Promise; - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - _refresh(): Promise; - /** @internal */ - protected onAccepted(response: IncomingResponse): void; - /** @internal */ - protected onNotify(request: IncomingNotifyRequest): void; - /** @internal */ - protected onRefresh(request: OutgoingSubscribeRequest): void; - private initSubscriberRequest; -} -//# sourceMappingURL=subscriber.d.ts.map \ No newline at end of file diff --git a/lib/api/subscriber.d.ts.map b/lib/api/subscriber.d.ts.map deleted file mode 100644 index 24f09359d..000000000 --- a/lib/api/subscriber.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscriber.d.ts","sourceRoot":"","sources":["../../src/api/subscriber.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,qBAAqB,EAErB,gBAAgB,EAGhB,wBAAwB,EAIxB,GAAG,EAEJ,MAAM,SAAS,CAAC;AAIjB,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,qBAAa,UAAW,SAAQ,YAAY;IAE1C,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,IAAI,CAA6C;IACzD,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,sBAAsB,CAAyB;IACvD,OAAO,CAAC,eAAe,CAAqB;IAC5C,OAAO,CAAC,iBAAiB,CAAoB;IAC7C,OAAO,CAAC,SAAS,CAAM;IAEvB;;;;;;OAMG;gBACgB,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB;IAwC3G;;;OAGG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA6C/B;;;;;;OAMG;IAEI,SAAS,CAAC,OAAO,GAAE,0BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;IAqDzE;;OAEG;IAEI,WAAW,CAAC,OAAO,GAAE,8BAAmC,GAAG,OAAO,CAAC,IAAI,CAAC;IA+B/E;;;;OAIG;IACI,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAOhC,gBAAgB;IAEhB,SAAS,CAAC,UAAU,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI;IAMtD,gBAAgB;IAChB,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAuExD,gBAAgB;IAChB,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI;IAM5D,OAAO,CAAC,qBAAqB;CAkB9B"} \ No newline at end of file diff --git a/lib/api/subscriber.js b/lib/api/subscriber.js deleted file mode 100644 index 63b8099f1..000000000 --- a/lib/api/subscriber.js +++ /dev/null @@ -1,427 +0,0 @@ -import { C, fromBodyLegacy, SubscriptionState as SubscriptionDialogState } from "../core"; -import { AllowedMethods } from "../core/user-agent-core/allowed-methods"; -import { Notification } from "./notification"; -import { Subscription } from "./subscription"; -import { SubscriptionState } from "./subscription-state"; -/** - * A subscriber establishes a {@link Subscription} (outgoing SUBSCRIBE). - * - * @remarks - * This is (more or less) an implementation of a "subscriber" as - * defined in RFC 6665 "SIP-Specific Event Notifications". - * https://tools.ietf.org/html/rfc6665 - * - * @example - * ```ts - * // Create a new subscriber. - * const targetURI = new URI("sip", "alice", "example.com"); - * const eventType = "example-name"; // https://www.iana.org/assignments/sip-events/sip-events.xhtml - * const subscriber = new Subscriber(userAgent, targetURI, eventType); - * - * // Add delegate to handle event notifications. - * subscriber.delegate = { - * onNotify: (notification: Notification) => { - * // handle notification here - * } - * }; - * - * // Monitor subscription state changes. - * subscriber.stateChange.addListener((newState: SubscriptionState) => { - * if (newState === SubscriptionState.Terminated) { - * // handle state change here - * } - * }); - * - * // Attempt to establish the subscription - * subscriber.subscribe(); - * - * // Sometime later when done with subscription - * subscriber.unsubscribe(); - * ``` - * - * @public - */ -export class Subscriber extends Subscription { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @param targetURI - The request URI identifying the subscribed event. - * @param eventType - The event type identifying the subscribed event. - * @param options - Options bucket. See {@link SubscriberOptions} for details. - */ - constructor(userAgent, targetURI, eventType, options = {}) { - super(userAgent, options); - this.body = undefined; - this.logger = userAgent.getLogger("sip.Subscriber"); - if (options.body) { - this.body = { - body: options.body, - contentType: options.contentType ? options.contentType : "application/sdp" - }; - } - this.targetURI = targetURI; - // Subscription event - this.event = eventType; - // Subscription expires - if (options.expires === undefined) { - this.expires = 3600; - } - else if (typeof options.expires !== "number") { - // pre-typescript type guard - this.logger.warn(`Option "expires" must be a number. Using default of 3600.`); - this.expires = 3600; - } - else { - this.expires = options.expires; - } - // Subscription extra headers - this.extraHeaders = (options.extraHeaders || []).slice(); - // Subscription context. - this.subscriberRequest = this.initSubscriberRequest(); - this.outgoingRequestMessage = this.subscriberRequest.message; - // Add to UserAgent's collection - this.id = this.outgoingRequestMessage.callId + this.outgoingRequestMessage.from.parameters.tag + this.event; - this._userAgent._subscriptions[this.id] = this; - } - /** - * Destructor. - * @internal - */ - dispose() { - if (this.disposed) { - return Promise.resolve(); - } - this.logger.log(`Subscription ${this.id} in state ${this.state} is being disposed`); - // Remove from the user agent's subscription collection - delete this._userAgent._subscriptions[this.id]; - // Clear timers - if (this.retryAfterTimer) { - clearTimeout(this.retryAfterTimer); - this.retryAfterTimer = undefined; - } - // Dispose subscriber request - this.subscriberRequest.dispose(); - // Make sure to dispose of our parent, then unsubscribe the - // subscription dialog (if need be) and resolve when it has terminated. - return super.dispose().then(() => { - // If we have never subscribed there is nothing to wait on. - // If we are already transitioned to terminated there is no need to unsubscribe again. - if (this.state !== SubscriptionState.Subscribed) { - return; - } - if (!this._dialog) { - throw new Error("Dialog undefined."); - } - if (this._dialog.subscriptionState === SubscriptionDialogState.Pending || - this._dialog.subscriptionState === SubscriptionDialogState.Active) { - const dialog = this._dialog; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - return new Promise((resolve, reject) => { - dialog.delegate = { - onTerminated: () => resolve() - }; - dialog.unsubscribe(); - }); - } - }); - } - /** - * Subscribe to event notifications. - * - * @remarks - * Send an initial SUBSCRIBE request if no subscription as been established. - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - subscribe(options = {}) { - switch (this.subscriberRequest.state) { - case SubscriptionDialogState.Initial: - // we can end up here when retrying so only state transition if in SubscriptionState.Initial state - if (this.state === SubscriptionState.Initial) { - this.stateTransition(SubscriptionState.NotifyWait); - } - this.subscriberRequest.subscribe().then((result) => { - if (result.success) { - if (result.success.subscription) { - this._dialog = result.success.subscription; - this._dialog.delegate = { - onNotify: (request) => this.onNotify(request), - onRefresh: (request) => this.onRefresh(request), - onTerminated: () => { - // If a call to unsubscribe will state transition to SubscriptionState.Terminated, - // but we can end up here after that if the NOTIFY never arrives and timer N fires. - if (this.state !== SubscriptionState.Terminated) { - this.stateTransition(SubscriptionState.Terminated); - } - } - }; - } - this.onNotify(result.success.request); - } - else if (result.failure) { - this.unsubscribe(); - } - }); - break; - case SubscriptionDialogState.NotifyWait: - break; - case SubscriptionDialogState.Pending: - break; - case SubscriptionDialogState.Active: - if (this._dialog) { - const request = this._dialog.refresh(); - request.delegate = { - onAccept: (response) => this.onAccepted(response), - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onRedirect: (response) => this.unsubscribe(), - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onReject: (response) => this.unsubscribe() - }; - } - break; - case SubscriptionDialogState.Terminated: - break; - default: - break; - } - return Promise.resolve(); - } - /** - * {@inheritDoc Subscription.unsubscribe} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - unsubscribe(options = {}) { - if (this.disposed) { - return Promise.resolve(); - } - switch (this.subscriberRequest.state) { - case SubscriptionDialogState.Initial: - break; - case SubscriptionDialogState.NotifyWait: - break; - case SubscriptionDialogState.Pending: - if (this._dialog) { - this._dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case SubscriptionDialogState.Active: - if (this._dialog) { - this._dialog.unsubscribe(); - // responses intentionally ignored - } - break; - case SubscriptionDialogState.Terminated: - break; - default: - throw new Error("Unknown state."); - } - this.stateTransition(SubscriptionState.Terminated); - return Promise.resolve(); - } - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - * @deprecated Use `subscribe` instead. - * @internal - */ - _refresh() { - if (this.subscriberRequest.state === SubscriptionDialogState.Active) { - return this.subscribe(); - } - return Promise.resolve(); - } - /** @internal */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onAccepted(response) { - // NOTE: If you think you should do something with this response, - // please make sure you understand what it is you are doing and why. - // Per the RFC, the first NOTIFY is all that actually matters. - } - /** @internal */ - onNotify(request) { - // If we've set state to done, no further processing should take place - // and we are only interested in cleaning up after the appropriate NOTIFY. - if (this.disposed) { - request.accept(); - return; - } - // State transition if needed. - if (this.state !== SubscriptionState.Subscribed) { - this.stateTransition(SubscriptionState.Subscribed); - } - // Delegate notification. - if (this.delegate && this.delegate.onNotify) { - const notification = new Notification(request); - this.delegate.onNotify(notification); - } - else { - request.accept(); - } - // If the "Subscription-State" value is SubscriptionState.Terminated, the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for SubscriptionState.Terminated -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of SubscriptionState.Terminated, and subscribers MUST ignore any such - // parameter, if present. If a reason code is present, the client - // should behave as described below. If no reason code or an unknown - // reason code is present, the client MAY attempt to re-subscribe at any - // time (unless a "retry-after" parameter is present, in which case the - // client SHOULD NOT attempt re-subscription until after the number of - // seconds specified by the "retry-after" parameter). The reason codes - // defined by this document are: - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = request.message.parseHeader("Subscription-State"); - if (subscriptionState && subscriptionState.state) { - switch (subscriptionState.state) { - case "terminated": - if (subscriptionState.reason) { - this.logger.log(`Terminated subscription with reason ${subscriptionState.reason}`); - switch (subscriptionState.reason) { - case "deactivated": - case "timeout": - this.initSubscriberRequest(); - this.subscribe(); - return; - case "probation": - case "giveup": - this.initSubscriberRequest(); - if (subscriptionState.params && subscriptionState.params["retry-after"]) { - this.retryAfterTimer = setTimeout(() => { - this.subscribe(); - }, subscriptionState.params["retry-after"]); - } - else { - this.subscribe(); - } - return; - case "rejected": - case "noresource": - case "invariant": - break; - } - } - this.unsubscribe(); - break; - default: - break; - } - } - } - /** @internal */ - onRefresh(request) { - request.delegate = { - onAccept: (response) => this.onAccepted(response) - }; - } - initSubscriberRequest() { - const options = { - extraHeaders: this.extraHeaders, - body: this.body ? fromBodyLegacy(this.body) : undefined - }; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.subscriberRequest = new SubscriberRequest(this._userAgent.userAgentCore, this.targetURI, this.event, this.expires, options); - this.subscriberRequest.delegate = { - onAccept: (response) => this.onAccepted(response) - }; - return this.subscriberRequest; - } -} -class SubscriberRequest { - constructor(core, target, event, expires, options, delegate) { - this.core = core; - this.target = target; - this.event = event; - this.expires = expires; - this.subscribed = false; - this.logger = core.loggerFactory.getLogger("sip.Subscriber"); - this.delegate = delegate; - const allowHeader = "Allow: " + AllowedMethods.toString(); - const extraHeaders = ((options && options.extraHeaders) || []).slice(); - extraHeaders.push(allowHeader); - extraHeaders.push("Event: " + this.event); - extraHeaders.push("Expires: " + this.expires); - extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - const body = options && options.body; - this.message = core.makeOutgoingRequestMessage(C.SUBSCRIBE, this.target, this.core.configuration.aor, this.target, {}, extraHeaders, body); - } - /** Destructor. */ - dispose() { - if (this.request) { - this.request.waitNotifyStop(); - this.request.dispose(); - this.request = undefined; - } - } - /** Subscription state. */ - get state() { - if (this.subscription) { - return this.subscription.subscriptionState; - } - else if (this.subscribed) { - return SubscriptionDialogState.NotifyWait; - } - else { - return SubscriptionDialogState.Initial; - } - } - /** - * Establish subscription. - * @param options Options bucket. - */ - subscribe() { - if (this.subscribed) { - return Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")); - } - this.subscribed = true; - return new Promise((resolve) => { - if (!this.message) { - throw new Error("Message undefined."); - } - this.request = this.core.subscribe(this.message, { - // This SUBSCRIBE request will be confirmed with a final response. - // 200-class responses indicate that the subscription has been accepted - // and that a NOTIFY request will be sent immediately. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onAccept: (response) => { - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept(response); - } - }, - // Due to the potential for out-of-order messages, packet loss, and - // forking, the subscriber MUST be prepared to receive NOTIFY requests - // before the SUBSCRIBE transaction has completed. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotify: (requestWithSubscription) => { - this.subscription = requestWithSubscription.subscription; - if (this.subscription) { - this.subscription.autoRefresh = true; - } - resolve({ success: requestWithSubscription }); - }, - // If this Timer N expires prior to the receipt of a NOTIFY request, - // the subscriber considers the subscription failed, and cleans up - // any state associated with the subscription attempt. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - onNotifyTimeout: () => { - resolve({ failure: {} }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onRedirect: (response) => { - resolve({ failure: { response } }); - }, - // This SUBSCRIBE request will be confirmed with a final response. - // Non-200-class final responses indicate that no subscription or new - // dialog usage has been created, and no subsequent NOTIFY request will - // be sent. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - onReject: (response) => { - resolve({ failure: { response } }); - } - }); - }); - } -} diff --git a/lib/api/subscription-delegate.d.ts b/lib/api/subscription-delegate.d.ts deleted file mode 100644 index 2059c8b59..000000000 --- a/lib/api/subscription-delegate.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Notification } from "./notification"; -/** - * Delegate for {@link Subscription}. - * @public - */ -export interface SubscriptionDelegate { - /** - * Called upon receiving an incoming NOTIFY request. - * @param notification - A notification. See {@link Notification} for details. - */ - onNotify(notification: Notification): void; -} -//# sourceMappingURL=subscription-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-delegate.d.ts.map b/lib/api/subscription-delegate.d.ts.map deleted file mode 100644 index 7f5133b59..000000000 --- a/lib/api/subscription-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-delegate.d.ts","sourceRoot":"","sources":["../../src/api/subscription-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;CAC5C"} \ No newline at end of file diff --git a/lib/api/subscription-delegate.js b/lib/api/subscription-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/subscription-options.d.ts b/lib/api/subscription-options.d.ts deleted file mode 100644 index 70e65308d..000000000 --- a/lib/api/subscription-options.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { SubscriptionDelegate } from "./subscription-delegate"; -/** - * Options for {@link Subscription } constructor. - * @public - */ -export interface SubscriptionOptions { - delegate?: SubscriptionDelegate; -} -//# sourceMappingURL=subscription-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-options.d.ts.map b/lib/api/subscription-options.d.ts.map deleted file mode 100644 index abd24343b..000000000 --- a/lib/api/subscription-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CACjC"} \ No newline at end of file diff --git a/lib/api/subscription-options.js b/lib/api/subscription-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/subscription-state.d.ts b/lib/api/subscription-state.d.ts deleted file mode 100644 index df46a7d8b..000000000 --- a/lib/api/subscription-state.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * {@link Subscription} state. - * @remarks - * The {@link Subscription} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * _______________________________________ - * Subscription | v - * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated - * |____________________________^ - * ``` - * @public - */ -export declare enum SubscriptionState { - Initial = "Initial", - NotifyWait = "NotifyWait", - Subscribed = "Subscribed", - Terminated = "Terminated" -} -//# sourceMappingURL=subscription-state.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-state.d.ts.map b/lib/api/subscription-state.d.ts.map deleted file mode 100644 index 629f5dc35..000000000 --- a/lib/api/subscription-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-state.d.ts","sourceRoot":"","sources":["../../src/api/subscription-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,oBAAY,iBAAiB;IAC3B,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/api/subscription-state.js b/lib/api/subscription-state.js deleted file mode 100644 index ad2c149ca..000000000 --- a/lib/api/subscription-state.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * {@link Subscription} state. - * @remarks - * The {@link Subscription} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * _______________________________________ - * Subscription | v - * Constructed -> Initial -> NotifyWait -> Subscribed -> Terminated - * |____________________________^ - * ``` - * @public - */ -export var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Subscribed"] = "Subscribed"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState || (SubscriptionState = {})); diff --git a/lib/api/subscription-subscribe-options.d.ts b/lib/api/subscription-subscribe-options.d.ts deleted file mode 100644 index 38fc11d53..000000000 --- a/lib/api/subscription-subscribe-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Subscription.subscribe}. - * @public - */ -export interface SubscriptionSubscribeOptions { -} -//# sourceMappingURL=subscription-subscribe-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-subscribe-options.d.ts.map b/lib/api/subscription-subscribe-options.d.ts.map deleted file mode 100644 index bb7847866..000000000 --- a/lib/api/subscription-subscribe-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-subscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-subscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,4BAA4B;CAAG"} \ No newline at end of file diff --git a/lib/api/subscription-subscribe-options.js b/lib/api/subscription-subscribe-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/subscription-unsubscribe-options.d.ts b/lib/api/subscription-unsubscribe-options.d.ts deleted file mode 100644 index 0130c59f3..000000000 --- a/lib/api/subscription-unsubscribe-options.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Options for {@link Subscription.unsubscribe}. - * @public - */ -export interface SubscriptionUnsubscribeOptions { -} -//# sourceMappingURL=subscription-unsubscribe-options.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription-unsubscribe-options.d.ts.map b/lib/api/subscription-unsubscribe-options.d.ts.map deleted file mode 100644 index 6714e6c50..000000000 --- a/lib/api/subscription-unsubscribe-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-unsubscribe-options.d.ts","sourceRoot":"","sources":["../../src/api/subscription-unsubscribe-options.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,MAAM,WAAW,8BAA8B;CAAG"} \ No newline at end of file diff --git a/lib/api/subscription-unsubscribe-options.js b/lib/api/subscription-unsubscribe-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/subscription.d.ts b/lib/api/subscription.d.ts deleted file mode 100644 index d3e4b8885..000000000 --- a/lib/api/subscription.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { Subscription as SubscriptionDialog } from "../core"; -import { Emitter } from "./emitter"; -import { SubscriptionDelegate } from "./subscription-delegate"; -import { SubscriptionOptions } from "./subscription-options"; -import { SubscriptionState } from "./subscription-state"; -import { SubscriptionSubscribeOptions } from "./subscription-subscribe-options"; -import { SubscriptionUnsubscribeOptions } from "./subscription-unsubscribe-options"; -import { UserAgent } from "./user-agent"; -/** - * A subscription provides {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -export declare abstract class Subscription { - /** - * Property reserved for use by instance owner. - * @defaultValue `undefined` - */ - data: unknown; - /** - * Subscription delegate. See {@link SubscriptionDelegate} for details. - * @defaultValue `undefined` - */ - delegate: SubscriptionDelegate | undefined; - /** - * If the subscription state is SubscriptionState.Subscribed, the associated subscription dialog. Otherwise undefined. - * @internal - */ - protected _dialog: SubscriptionDialog | undefined; - /** - * Our user agent. - * @internal - */ - protected _userAgent: UserAgent; - private _disposed; - private _logger; - private _state; - private _stateEventEmitter; - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - protected constructor(userAgent: UserAgent, options?: SubscriptionOptions); - /** - * Destructor. - */ - dispose(): Promise; - /** - * The subscribed subscription dialog. - */ - get dialog(): SubscriptionDialog | undefined; - /** - * True if disposed. - * @internal - */ - get disposed(): boolean; - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - get state(): SubscriptionState; - /** - * Emits when the subscription `state` property changes. - */ - get stateChange(): Emitter; - /** @internal */ - protected stateTransition(newState: SubscriptionState): void; - /** - * Sends a re-SUBSCRIBE request if the subscription is "active". - */ - abstract subscribe(options?: SubscriptionSubscribeOptions): Promise; - /** - * Unsubscribe from event notifications. - * - * @remarks - * If the subscription state is SubscriptionState.Subscribed, sends an in dialog SUBSCRIBE request - * with expires time of zero (an un-subscribe) and terminates the subscription. - * Otherwise a noop. - */ - abstract unsubscribe(options?: SubscriptionUnsubscribeOptions): Promise; -} -//# sourceMappingURL=subscription.d.ts.map \ No newline at end of file diff --git a/lib/api/subscription.d.ts.map b/lib/api/subscription.d.ts.map deleted file mode 100644 index 33c9f8b22..000000000 --- a/lib/api/subscription.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../src/api/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,YAAY,IAAI,kBAAkB,EAAE,MAAM,SAAS,CAAC;AACrE,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,4BAA4B,EAAE,MAAM,kCAAkC,CAAC;AAChF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;GAOG;AACH,8BAAsB,YAAY;IAChC;;;OAGG;IACI,IAAI,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACI,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,OAAO,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,UAAU,EAAE,SAAS,CAAC;IAEhC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAgD;IAC9D,OAAO,CAAC,kBAAkB,CAAiC;IAE3D;;;;OAIG;IACH,SAAS,aAAa,SAAS,EAAE,SAAS,EAAE,OAAO,GAAE,mBAAwB;IAO7E;;OAEG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAS/B;;OAEG;IACH,IAAW,MAAM,IAAI,kBAAkB,GAAG,SAAS,CAElD;IAED;;;OAGG;IACH,IAAW,QAAQ,IAAI,OAAO,CAE7B;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,iBAAiB,CAEpC;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAEnD;IAED,gBAAgB;IAChB,SAAS,CAAC,eAAe,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI;IA6C5D;;OAEG;aACa,SAAS,CAAC,OAAO,CAAC,EAAE,4BAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;IAEhF;;;;;;;OAOG;aACa,WAAW,CAAC,OAAO,CAAC,EAAE,8BAA8B,GAAG,OAAO,CAAC,IAAI,CAAC;CACrF"} \ No newline at end of file diff --git a/lib/api/subscription.js b/lib/api/subscription.js deleted file mode 100644 index 35fada66d..000000000 --- a/lib/api/subscription.js +++ /dev/null @@ -1,102 +0,0 @@ -import { EmitterImpl } from "./emitter"; -import { SubscriptionState } from "./subscription-state"; -/** - * A subscription provides {@link Notification} of events. - * - * @remarks - * See {@link Subscriber} for details on establishing a subscription. - * - * @public - */ -export class Subscription { - /** - * Constructor. - * @param userAgent - User agent. See {@link UserAgent} for details. - * @internal - */ - constructor(userAgent, options = {}) { - this._disposed = false; - this._state = SubscriptionState.Initial; - this._logger = userAgent.getLogger("sip.Subscription"); - this._stateEventEmitter = new EmitterImpl(); - this._userAgent = userAgent; - this.delegate = options.delegate; - } - /** - * Destructor. - */ - dispose() { - if (this._disposed) { - return Promise.resolve(); - } - this._disposed = true; - this._stateEventEmitter.removeAllListeners(); - return Promise.resolve(); - } - /** - * The subscribed subscription dialog. - */ - get dialog() { - return this._dialog; - } - /** - * True if disposed. - * @internal - */ - get disposed() { - return this._disposed; - } - /** - * Subscription state. See {@link SubscriptionState} for details. - */ - get state() { - return this._state; - } - /** - * Emits when the subscription `state` property changes. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** @internal */ - stateTransition(newState) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate transition - switch (this._state) { - case SubscriptionState.Initial: - if (newState !== SubscriptionState.NotifyWait && newState !== SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case SubscriptionState.NotifyWait: - if (newState !== SubscriptionState.Subscribed && newState !== SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case SubscriptionState.Subscribed: - if (newState !== SubscriptionState.Terminated) { - invalidTransition(); - } - break; - case SubscriptionState.Terminated: - invalidTransition(); - break; - default: - throw new Error("Unrecognized state."); - } - // Guard against duplicate transition - if (this._state === newState) { - return; - } - // Transition - this._state = newState; - this._logger.log(`Subscription ${this._dialog ? this._dialog.id : undefined} transitioned to ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Dispose - if (newState === SubscriptionState.Terminated) { - this.dispose(); - } - } -} diff --git a/lib/api/transport-state.d.ts b/lib/api/transport-state.d.ts deleted file mode 100644 index d3319fcd6..000000000 --- a/lib/api/transport-state.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * {@link Transport} state. - * - * @remarks - * The {@link Transport} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ______________________________ - * | ____________ | - * Transport v v | | - * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting - * ^ ^ |_____________________^ | | - * | |_____________________________| | - * |_____________________________________________| - * ``` - * @public - */ -export declare enum TransportState { - /** - * The `connect()` method was called. - */ - Connecting = "Connecting", - /** - * The `connect()` method resolved. - */ - Connected = "Connected", - /** - * The `disconnect()` method was called. - */ - Disconnecting = "Disconnecting", - /** - * The `connect()` method was rejected, or - * the `disconnect()` method completed, or - * network connectivity was lost. - */ - Disconnected = "Disconnected" -} -//# sourceMappingURL=transport-state.d.ts.map \ No newline at end of file diff --git a/lib/api/transport-state.d.ts.map b/lib/api/transport-state.d.ts.map deleted file mode 100644 index c8f3524d0..000000000 --- a/lib/api/transport-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport-state.d.ts","sourceRoot":"","sources":["../../src/api/transport-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,oBAAY,cAAc;IACxB;;OAEG;IACH,UAAU,eAAe;IACzB;;OAEG;IACH,SAAS,cAAc;IACvB;;OAEG;IACH,aAAa,kBAAkB;IAC/B;;;;OAIG;IACH,YAAY,iBAAiB;CAC9B"} \ No newline at end of file diff --git a/lib/api/transport-state.js b/lib/api/transport-state.js deleted file mode 100644 index b38c563f5..000000000 --- a/lib/api/transport-state.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * {@link Transport} state. - * - * @remarks - * The {@link Transport} behaves in a deterministic manner according to the following - * Finite State Machine (FSM). - * ```txt - * ______________________________ - * | ____________ | - * Transport v v | | - * Constructed -> Disconnected -> Connecting -> Connected -> Disconnecting - * ^ ^ |_____________________^ | | - * | |_____________________________| | - * |_____________________________________________| - * ``` - * @public - */ -export var TransportState; -(function (TransportState) { - /** - * The `connect()` method was called. - */ - TransportState["Connecting"] = "Connecting"; - /** - * The `connect()` method resolved. - */ - TransportState["Connected"] = "Connected"; - /** - * The `disconnect()` method was called. - */ - TransportState["Disconnecting"] = "Disconnecting"; - /** - * The `connect()` method was rejected, or - * the `disconnect()` method completed, or - * network connectivity was lost. - */ - TransportState["Disconnected"] = "Disconnected"; -})(TransportState || (TransportState = {})); diff --git a/lib/api/transport.d.ts b/lib/api/transport.d.ts deleted file mode 100644 index 3f40d84d3..000000000 --- a/lib/api/transport.d.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { Transport as CoreTransport } from "../core"; -import { Emitter } from "./emitter"; -import { TransportState } from "./transport-state"; -/** - * Transport layer interface expected by the `UserAgent`. - * - * @remarks - * The transport behaves in a deterministic manner according to the - * the state defined in {@link TransportState}. - * - * The "Connecting" state is ONLY entered in response to the user calling `connect()`. - * The "Disconnecting" state is ONLY entered in response to the user calling `disconnect()`. - * The `onConnect` callback is ALWAYS called upon transitioning to the "Connected" state. - * The `onDisconnect` callback is ALWAYS called upon transitioning from the "Connected" state. - * - * Adherence to the state machine by the transport implementation is critical as the - * UserAgent depends on this behavior. Furthermore it is critical that the transport - * transition to the "Disconnected" state in all instances where network connectivity - * is lost as the UserAgent, API, and application layer more generally depend on knowing - * network was lost. For example, from a practical standpoint registrations and subscriptions are invalidated - * when network is lost - particularly in the case of connection oriented transport - * protocols such as a secure WebSocket transport. - * - * Proper handling the application level protocol recovery must be left to the application layer, - * thus the transport MUST NOT attempt to "auto-recover" from or otherwise hide loss of network. - * Note that callbacks and emitters such as `onConnect` and `onDisconnect` MUST NOT call methods - * `connect()` and `direct()` synchronously (state change handlers must not loop back). They may - * however do so asynchronously using a Promise resolution, `setTimeout`, or some other method. - * For example... - * ```ts - * transport.onDisconnect = () => { - * Promise.resolve().then(() => transport.connect()); - * } - * ``` - * @public - */ -export interface Transport extends CoreTransport { - /** - * Transport state. - * - * @remarks - * The initial Transport state MUST be "disconnected" (after calling constructor). - */ - readonly state: TransportState; - /** - * Transport state change emitter. - */ - readonly stateChange: Emitter; - /** - * Callback on state transition to "Connected". - * - * @remarks - * When the `UserAgent` is constructed, this property is set. - * ```txt - * - The `state` MUST be "Connected" when called. - * ``` - */ - onConnect: (() => void) | undefined; - /** - * Callback on state transition from "Connected". - * - * @remarks - * When the `UserAgent` is constructed, this property is set. - * ```txt - * - The `state` MUST NOT "Connected" when called. - * - If prior `state` is "Connecting" or "Connected", `error` MUST be defined. - * - If prior `state` is "Disconnecting", `error` MUST NOT be undefined. - * ``` - * If the transition from "Connected" occurs because the transport - * user requested it by calling `disconnect`, then `error` will be undefined. - * Otherwise `error` will be defined to provide an indication that the - * transport initiated the transition from "Connected" - for example, - * perhaps network connectivity was lost. - */ - onDisconnect: ((error?: Error) => void) | undefined; - /** - * Callback on receipt of a message. - * - * @remarks - * When the `UserAgent` is constructed, this property is set. - * The `state` MUST be "Connected" when this is called. - */ - onMessage: ((message: string) => void) | undefined; - /** - * Connect to network. - * - * @remarks - * ```txt - * - If `state` is "Connecting", `state` MUST NOT transition before returning. - * - If `state` is "Connected", `state` MUST NOT transition before returning. - * - If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning. - * - If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning. - * - The `state` MUST transition to "Connected" before resolving (assuming `state` is not already "Connected"). - * - The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting and MUST reject with an Error. - * ``` - * Resolves when the transport connects. Rejects if transport fails to connect. - * Rejects with {@link StateTransitionError} if a loop is detected. - * In particular, callbacks and emitters MUST NOT call this method synchronously. - */ - connect(): Promise; - /** - * Disconnect from network. - * - * @remarks - * ```txt - * - If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. - * - If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. - * - If `state` is "Disconnecting", `state` MUST NOT transition before returning. - * - If `state` is "Disconnected", `state` MUST NOT transition before returning. - * - The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). - * - The `state` MUST transition to "Connecting" or "Connected" before rejecting and MUST reject with an Error. - * ``` - * Resolves when the transport disconnects. Rejects if transport fails to disconnect. - * Rejects with {@link StateTransitionError} if a loop is detected. - * In particular, callbacks and emitters MUST NOT call this method synchronously. - */ - disconnect(): Promise; - /** - * Dispose. - * - * @remarks - * When the `UserAgent` is disposed or stopped, this method is called. - * The `UserAgent` MUST NOT continue to utilize the instance after calling this method. - */ - dispose(): Promise; - /** - * Returns true if the `state` equals "Connected". - * - * @remarks - * This is equivalent to `state === TransportState.Connected`. - * It is convenient. A common paradigm is, for example... - * - * @example - * ```ts - * // Monitor transport connectivity - * userAgent.transport.stateChange.addListener(() => { - * if (userAgent.transport.isConnected()) { - * // handle transport connect - * } else { - * // handle transport disconnect - * } - * }); - * ``` - */ - isConnected(): boolean; - /** - * Send a message. - * - * @remarks - * ```txt - * - If `state` is "Connecting", rejects with an Error. - * - If `state` is "Connected", resolves when the message is sent otherwise rejects with an Error. - * - If `state` is "Disconnecting", rejects with an Error. - * - If `state` is "Disconnected", rejects with an Error. - * ``` - * @param message - Message to send. - */ - send(message: string): Promise; -} -//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/lib/api/transport.d.ts.map b/lib/api/transport.d.ts.map deleted file mode 100644 index 2c68274b5..000000000 --- a/lib/api/transport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/api/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,IAAI,aAAa,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,WAAW,SAAU,SAAQ,aAAa;IAC9C;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;IAE9C;;;;;;;;OAQG;IACH,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IAEpC;;;;;;;;;;;;;;;OAeG;IACH,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAEpD;;;;;;OAMG;IACH,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAEnD;;;;;;;;;;;;;;;OAeG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzB;;;;;;;;;;;;;;;OAeG;IACH,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAE5B;;;;;;OAMG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzB;;;;;;;;;;;;;;;;;;OAkBG;IACH,WAAW,IAAI,OAAO,CAAC;IAEvB;;;;;;;;;;;OAWG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC"} \ No newline at end of file diff --git a/lib/api/transport.js b/lib/api/transport.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/user-agent-delegate.d.ts b/lib/api/user-agent-delegate.d.ts deleted file mode 100644 index 1213b62fc..000000000 --- a/lib/api/user-agent-delegate.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { IncomingReferRequest, IncomingRegisterRequest, IncomingSubscribeRequest } from "../core"; -import { Invitation } from "./invitation"; -import { Message } from "./message"; -import { Notification } from "./notification"; -import { Referral } from "./referral"; -import { Subscription } from "./subscription"; -/** - * Delegate for {@link UserAgent}. - * @public - */ -export interface UserAgentDelegate { - /** - * Called upon transport transitioning to connected state. - */ - onConnect?(): void; - /** - * Called upon transport transitioning from connected state. - * @param error - An error if disconnect triggered by transport. Otherwise undefined. - */ - onDisconnect?(error?: Error): void; - /** - * Called upon receipt of an invitation. - * @remarks - * Handler for incoming out of dialog INVITE requests. - * @param invitation - The invitation. - */ - onInvite?(invitation: Invitation): void; - /** - * Called upon receipt of a message. - * @remarks - * Handler for incoming out of dialog MESSAGE requests. - * @param message - The message. - */ - onMessage?(message: Message): void; - /** - * Called upon receipt of a notification. - * @remarks - * Handler for incoming out of dialog NOTIFY requests. - * @param notification - The notification. - */ - onNotify?(notification: Notification): void; - /** - * @alpha - * Called upon receipt of a referral. - * @remarks - * Handler for incoming out of dialog REFER requests. - * @param referral - The referral. - */ - onRefer?(referral: Referral): void; - /** - * @alpha - * Called upon receipt of a registration. - * @remarks - * Handler for incoming out of dialog REGISTER requests. - * @param registration - The registration. - */ - onRegister?(registration: unknown): void; - /** - * @alpha - * Called upon receipt of a subscription. - * @remarks - * Handler for incoming out of dialog SUBSCRIBE requests. - * @param subscription - The subscription. - */ - onSubscribe?(subscription: Subscription): void; - /** - * @internal - * Called upon receipt of an out of dialog REFER. Used by test suite. - * @param request - The request. - */ - onReferRequest?(request: IncomingReferRequest): void; - /** - * @internal - * Called upon receipt of a REGISTER request. Used by test suite. - * @param request - The request. - */ - onRegisterRequest?(request: IncomingRegisterRequest): void; - /** - * @internal - * Called upon receipt of an out of dialog SUBSCRIBE request. Used by test suite. - * @param request - The request. - */ - onSubscribeRequest?(request: IncomingSubscribeRequest): void; -} -//# sourceMappingURL=user-agent-delegate.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent-delegate.d.ts.map b/lib/api/user-agent-delegate.d.ts.map deleted file mode 100644 index c4a0c15bb..000000000 --- a/lib/api/user-agent-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-delegate.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAClG,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,SAAS,CAAC,IAAI,IAAI,CAAC;IAEnB;;;OAGG;IACH,YAAY,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IAEnC;;;;;OAKG;IACH,QAAQ,CAAC,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IAExC;;;;;OAKG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IAEnC;;;;;OAKG;IACH,QAAQ,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE5C;;;;;;OAMG;IACH,OAAO,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEnC;;;;;;OAMG;IACH,UAAU,CAAC,CAAC,YAAY,EAAE,OAAO,GAA4B,IAAI,CAAC;IAElE;;;;;;OAMG;IACH,WAAW,CAAC,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAAC;IAE/C;;;;OAIG;IACH,cAAc,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAErD;;;;OAIG;IACH,iBAAiB,CAAC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAE3D;;;;OAIG;IACH,kBAAkB,CAAC,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI,CAAC;CAC9D"} \ No newline at end of file diff --git a/lib/api/user-agent-delegate.js b/lib/api/user-agent-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/api/user-agent-options.d.ts b/lib/api/user-agent-options.d.ts deleted file mode 100644 index 36c86e538..000000000 --- a/lib/api/user-agent-options.d.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { Logger, URI } from "../core"; -import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; -import { Transport } from "./transport"; -import { UserAgentDelegate } from "./user-agent-delegate"; -/** - * Log level. - * @public - */ -export declare type LogLevel = "debug" | "log" | "warn" | "error"; -/** - * Log connector function. - * @public - */ -export declare type LogConnector = (level: LogLevel, category: string, label: string | undefined, content: string) => void; -/** - * SIP extension support level. - * @public - */ -export declare enum SIPExtension { - Required = "Required", - Supported = "Supported", - Unsupported = "Unsupported" -} -/** - * Options for {@link UserAgent} constructor. - * @public - */ -export interface UserAgentOptions { - /** - * If `true`, the user agent will accept out of dialog NOTIFY. - * @remarks - * RFC 6665 obsoletes the use of out of dialog NOTIFY from RFC 3265. - * @defaultValue `false` - */ - allowLegacyNotifications?: boolean; - /** - * Authorization ha1. - * @defaultValue `""` - */ - authorizationHa1?: string; - /** - * Authorization password. - * @defaultValue `""` - */ - authorizationPassword?: string; - /** - * Authorization username. - * @defaultValue `""` - */ - authorizationUsername?: string; - /** - * @deprecated - * If `true`, the user agent calls the `start()` method in the constructor. - * @defaultValue `false` - * @remarks - * The call to start() resolves when the user agent connects, so if this - * option is set to `true` an alternative method of connection detection - * must be used. - */ - autoStart?: boolean; - /** - * If `true`, the user agent calls the `stop()` method on unload (if running in browser window). - * @defaultValue `true` - */ - autoStop?: boolean; - /** - * Delegate for {@link UserAgent}. - * @defaultValue `{}` - */ - delegate?: UserAgentDelegate; - /** - * The display name associated with the user agent. - * @remarks - * Descriptive name to be shown to the called party when calling or sending IM messages - * (the display name portion of the From header). - * It must NOT be enclosed between double quotes even if the given name contains multi-byte symbols - * (SIPjs will always enclose the `displayName` value between double quotes). - * @defaultValue `""` - */ - displayName?: string; - /** - * Force adding rport to Via header. - * @defaultValue `false` - */ - forceRport?: boolean; - /** - * Hack - * @deprecated TBD - */ - hackIpInContact?: boolean | string; - /** - * Hack - * @deprecated TBD - */ - hackAllowUnregisteredOptionTags?: boolean; - /** - * Hack - * @deprecated TBD - */ - hackViaTcp?: boolean; - /** - * Hack - * @deprecated TBD - */ - hackWssInTransport?: boolean; - /** - * Indicates whether log messages should be written to the browser console. - * @defaultValue `true` - */ - logBuiltinEnabled?: boolean; - /** - * If true, constructor logs the user agent configuration. - * @defaultValue `true` - */ - logConfiguration?: boolean; - /** - * A function which will be called every time a log is generated. - * @defaultValue A noop - */ - logConnector?: LogConnector; - /** - * Indicates the verbosity level of the log messages. - * @defaultValue `"log"` - */ - logLevel?: LogLevel; - /** - * Number of seconds after which an incoming call is rejected if not answered. - * @defaultValue 60 - */ - noAnswerTimeout?: number; - /** - * Adds a Route header(s) to outgoing requests. - * @defaultValue `[]` - */ - preloadedRouteSet?: Array; - /** - * @deprecated - * Maximum number of times to attempt to reconnect when the transport connection drops. - * @defaultValue 0 - */ - reconnectionAttempts?: number; - /** - * @deprecated - * Seconds to wait between reconnection attempts when the transport connection drops. - * @defaultValue 4 - */ - reconnectionDelay?: number; - /** - * A factory for generating `SessionDescriptionHandler` instances. - * @remarks - * The factory will be passed a `Session` object for the current session - * and the `sessionDescriptionHandlerFactoryOptions` object. - * @defaultValue `Web.SessionDescriptionHandler.defaultFactory` - */ - sessionDescriptionHandlerFactory?: SessionDescriptionHandlerFactory; - /** - * Options to passed to `sessionDescriptionHandlerFactory`. - * @remarks - * See `Web.SessionDescriptionHandlerOptions` for details. - * @defaultValue `{}` - */ - sessionDescriptionHandlerFactoryOptions?: object; - /** - * Reliable provisional responses. - * https://tools.ietf.org/html/rfc3262 - * @defaultValue `SIPExtension.Unsupported` - */ - sipExtension100rel?: SIPExtension; - /** - * Replaces header. - * https://tools.ietf.org/html/rfc3891 - * @defaultValue `SIPExtension.Unsupported` - */ - sipExtensionReplaces?: SIPExtension; - /** - * Extra option tags to claim support for. - * @remarks - * Setting an extra option tag does not enable support for the associated extension - * it simply adds the tag to the list of supported options. - * See {@link UserAgentRegisteredOptionTags} for valid option tags. - * @defaultValue `[]` - */ - sipExtensionExtraSupported?: Array; - /** - * An id uniquely identify this user agent instance. - * @defaultValue - * A random id generated by default. - */ - sipjsId?: string; - /** - * A constructor function for the user agent's `Transport`. - * @remarks - * For more information about creating your own transport see `Transport`. - * @defaultValue `WebSocketTransport` - */ - transportConstructor?: new (logger: Logger, options: any) => Transport; - /** - * An options bucket object passed to `transportConstructor` when instantiated. - * @remarks - * See WebSocket Transport Configuration Parameters for the full list of options for the default transport. - * @defaultValue `{}` - */ - transportOptions?: unknown; - /** - * SIP Addresses-of-Record URI associated with the user agent. - * @remarks - * This is a SIP address given to you by your provider. - * If the user agent registers, it is the address-of-record which the user agent registers a contact for. - * An address-of-record represents an identity of the user, generally a long-term identity, - * and it does not have a dependency on any device; users can move between devices or even - * be associated with multiple devices at one time while retaining the same address-of-record. - * A simple URI, generally of the form `sip:egdar@example.com`, is used for an address-of-record. - * @defaultValue - * By default, URI is set to `sip:anonymous.X@anonymous.invalid`, where X is a random token generated for each UA. - */ - uri?: URI; - /** - * User agent string used in the UserAgent header. - * @defaultValue - * A reasonable value is utilized. - */ - userAgentString?: string; - /** - * Hostname to use in Via header. - * @defaultValue - * A random hostname in the .invalid domain. - */ - viaHost?: string; -} -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -export declare const UserAgentRegisteredOptionTags: { - [option: string]: boolean; -}; -//# sourceMappingURL=user-agent-options.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent-options.d.ts.map b/lib/api/user-agent-options.d.ts.map deleted file mode 100644 index 4bf39151d..000000000 --- a/lib/api/user-agent-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-options.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;;GAGG;AACH,oBAAY,QAAQ,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;AAE1D;;;GAGG;AACH,oBAAY,YAAY,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAEnH;;;GAGG;AACH,oBAAY,YAAY;IACtB,QAAQ,aAAa;IACrB,SAAS,cAAc;IACvB,WAAW,gBAAgB;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IAEnC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAE7B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAEnC;;;OAGG;IACH,+BAA+B,CAAC,EAAE,OAAO,CAAC;IAE1C;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAE5B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;OAGG;IACH,YAAY,CAAC,EAAE,YAAY,CAAC;IAE5B;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAEpB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAElC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;;OAMG;IACH,gCAAgC,CAAC,EAAE,gCAAgC,CAAC;IAEpE;;;;;OAKG;IACH,uCAAuC,CAAC,EAAE,MAAM,CAAC;IAEjD;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,YAAY,CAAC;IAElC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,YAAY,CAAC;IAEpC;;;;;;;OAOG;IACH,0BAA0B,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE3C;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IAEH,oBAAoB,CAAC,EAAE,KAAK,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,SAAS,CAAC;IAEvE;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;;;;;;;;OAWG;IACH,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,EAAE;IAAE,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAA;CAkCtE,CAAC"} \ No newline at end of file diff --git a/lib/api/user-agent-options.js b/lib/api/user-agent-options.js deleted file mode 100644 index 8e38df1ab..000000000 --- a/lib/api/user-agent-options.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * SIP extension support level. - * @public - */ -export var SIPExtension; -(function (SIPExtension) { - SIPExtension["Required"] = "Required"; - SIPExtension["Supported"] = "Supported"; - SIPExtension["Unsupported"] = "Unsupported"; -})(SIPExtension || (SIPExtension = {})); -/** - * SIP Option Tags - * @remarks - * http://www.iana.org/assignments/sip-parameters/sip-parameters.xhtml#sip-parameters-4 - * @public - */ -export const UserAgentRegisteredOptionTags = { - "100rel": true, - "199": true, - answermode: true, - "early-session": true, - eventlist: true, - explicitsub: true, - "from-change": true, - "geolocation-http": true, - "geolocation-sip": true, - gin: true, - gruu: true, - histinfo: true, - ice: true, - join: true, - "multiple-refer": true, - norefersub: true, - nosub: true, - outbound: true, - path: true, - policy: true, - precondition: true, - pref: true, - privacy: true, - "recipient-list-invite": true, - "recipient-list-message": true, - "recipient-list-subscribe": true, - replaces: true, - "resource-priority": true, - "sdp-anat": true, - "sec-agree": true, - tdialog: true, - timer: true, - uui: true // RFC 7433 -}; diff --git a/lib/api/user-agent-state.d.ts b/lib/api/user-agent-state.d.ts deleted file mode 100644 index c0a48616a..000000000 --- a/lib/api/user-agent-state.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "Started" --> "Stopped" - * 2. "Stopped" --> "Started" - * ``` - * @public - */ -export declare enum UserAgentState { - Started = "Started", - Stopped = "Stopped" -} -//# sourceMappingURL=user-agent-state.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent-state.d.ts.map b/lib/api/user-agent-state.d.ts.map deleted file mode 100644 index b3ec610be..000000000 --- a/lib/api/user-agent-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-state.d.ts","sourceRoot":"","sources":["../../src/api/user-agent-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB"} \ No newline at end of file diff --git a/lib/api/user-agent-state.js b/lib/api/user-agent-state.js deleted file mode 100644 index 09065910e..000000000 --- a/lib/api/user-agent-state.js +++ /dev/null @@ -1,15 +0,0 @@ -/** - * {@link UserAgent} state. - * @remarks - * Valid state transitions: - * ``` - * 1. "Started" --> "Stopped" - * 2. "Stopped" --> "Started" - * ``` - * @public - */ -export var UserAgentState; -(function (UserAgentState) { - UserAgentState["Started"] = "Started"; - UserAgentState["Stopped"] = "Stopped"; -})(UserAgentState || (UserAgentState = {})); diff --git a/lib/api/user-agent.d.ts b/lib/api/user-agent.d.ts deleted file mode 100644 index 9e82d5f12..000000000 --- a/lib/api/user-agent.d.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { Contact, Logger, LoggerFactory, URI, UserAgentCore } from "../core"; -import { Emitter } from "./emitter"; -import { Inviter } from "./inviter"; -import { InviterOptions } from "./inviter-options"; -import { Publisher } from "./publisher"; -import { Registerer } from "./registerer"; -import { Session } from "./session"; -import { Subscription } from "./subscription"; -import { Transport } from "./transport"; -import { UserAgentDelegate } from "./user-agent-delegate"; -import { UserAgentOptions } from "./user-agent-options"; -import { UserAgentState } from "./user-agent-state"; -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -export declare class UserAgent { - /** - * Property reserved for use by instance owner. - * @defaultValue `undefined` - */ - data: unknown; - /** - * Delegate. - */ - delegate: UserAgentDelegate | undefined; - /** @internal */ - _publishers: { - [id: string]: Publisher; - }; - /** @internal */ - _registerers: { - [id: string]: Registerer; - }; - /** @internal */ - _sessions: { - [id: string]: Session; - }; - /** @internal */ - _subscriptions: { - [id: string]: Subscription; - }; - private _contact; - private _state; - private _stateEventEmitter; - private _transport; - private _userAgentCore; - /** Logger. */ - private logger; - /** LoggerFactory. */ - private loggerFactory; - /** Options. */ - private options; - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - constructor(options?: Partial); - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - static makeURI(uri: string): URI | undefined; - /** Default user agent options. */ - private static defaultOptions; - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - private static stripUndefinedProperties; - /** - * User agent configuration. - */ - get configuration(): Required; - /** - * User agent contact. - */ - get contact(): Contact; - /** - * User agent state. - */ - get state(): UserAgentState; - /** - * User agent state change emitter. - */ - get stateChange(): Emitter; - /** - * User agent transport. - */ - get transport(): Transport; - /** - * User agent core. - */ - get userAgentCore(): UserAgentCore; - /** - * The logger. - */ - getLogger(category: string, label?: string): Logger; - /** - * The logger factory. - */ - getLoggerFactory(): LoggerFactory; - /** - * True if transport is connected. - */ - isConnected(): boolean; - /** - * Reconnect the transport. - */ - reconnect(): Promise; - /** - * Start the user agent. - * - * @remarks - * Resolves if transport connects, otherwise rejects. - * - * @example - * ```ts - * userAgent.start() - * .then(() => { - * // userAgent.isConnected() === true - * }) - * .catch((error: Error) => { - * // userAgent.isConnected() === false - * }); - * ``` - */ - start(): Promise; - /** - * Stop the user agent. - * - * @remarks - * Resolves when the user agent has completed a graceful shutdown. - * ```txt - * 1) Sessions terminate. - * 2) Registerers unregister. - * 3) Subscribers unsubscribe. - * 4) Publishers unpublish. - * 5) Transport disconnects. - * 6) User Agent Core resets. - * ``` - * NOTE: While this is a "graceful shutdown", it can also be very slow one if you - * are waiting for the returned Promise to resolve. The disposal of the clients and - * dialogs is done serially - waiting on one to finish before moving on to the next. - * This can be slow if there are lot of subscriptions to unsubscribe for example. - * - * THE SLOW PACE IS INTENTIONAL! - * While one could spin them all down in parallel, this could slam the remote server. - * It is bad practice to denial of service attack (DoS attack) servers!!! - * Moreover, production servers will automatically blacklist clients which send too - * many requests in too short a period of time - dropping any additional requests. - * - * If a different approach to disposing is needed, one can implement whatever is - * needed and execute that prior to calling `stop()`. Alternatively one may simply - * not wait for the Promise returned by `stop()` to complete. - */ - stop(): Promise; - /** - * Used to avoid circular references. - * @internal - */ - _makeInviter(targetURI: URI, options?: InviterOptions): Inviter; - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - private attemptReconnection; - /** - * Initialize contact. - */ - private initContact; - /** - * Initialize user agent core. - */ - private initCore; - private initTransportCallbacks; - private onTransportConnect; - private onTransportDisconnect; - private onTransportMessage; - /** - * Transition state. - */ - private transitionState; - /** Unload listener. */ - private unloadListener; -} -//# sourceMappingURL=user-agent.d.ts.map \ No newline at end of file diff --git a/lib/api/user-agent.d.ts.map b/lib/api/user-agent.d.ts.map deleted file mode 100644 index fdb3af439..000000000 --- a/lib/api/user-agent.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent.d.ts","sourceRoot":"","sources":["../../src/api/user-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAYP,MAAM,EACN,aAAa,EAGb,GAAG,EACH,aAAa,EAGd,MAAM,SAAS,CAAC;AAKjB,OAAO,EAAE,OAAO,EAAe,MAAM,WAAW,CAAC;AAEjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGnD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAgB,gBAAgB,EAAiC,MAAM,sBAAsB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAKpD;;;;;;;;;;GAUG;AACH,qBAAa,SAAS;IACpB;;;OAGG;IACI,IAAI,EAAE,OAAO,CAAC;IAErB;;OAEG;IACI,QAAQ,EAAE,iBAAiB,GAAG,SAAS,CAAC;IAE/C,gBAAgB;IACT,WAAW,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,CAAM;IACrD,gBAAgB;IACT,YAAY,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,UAAU,CAAA;KAAE,CAAM;IACvD,gBAAgB;IACT,SAAS,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAM;IACjD,gBAAgB;IACT,cAAc,EAAE;QAAE,CAAC,EAAE,EAAE,MAAM,GAAG,YAAY,CAAA;KAAE,CAAM;IAE3D,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,MAAM,CAA0C;IACxD,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,UAAU,CAAY;IAC9B,OAAO,CAAC,cAAc,CAAgB;IAEtC,cAAc;IACd,OAAO,CAAC,MAAM,CAAS;IACvB,qBAAqB;IACrB,OAAO,CAAC,aAAa,CAAgB;IACrC,eAAe;IACf,OAAO,CAAC,OAAO,CAA6B;IAE5C;;;OAGG;gBACgB,OAAO,GAAE,OAAO,CAAC,gBAAgB,CAAM;IA+I1D;;;;;;;;OAQG;WACW,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAInD,kCAAkC;IAClC,OAAO,CAAC,MAAM,CAAC,cAAc;IAuC7B;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAWvC;;OAEG;IACH,IAAW,aAAa,IAAI,QAAQ,CAAC,gBAAgB,CAAC,CAErD;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,OAAO,CAE5B;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,cAAc,CAEjC;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAEhD;IAED;;OAEG;IACH,IAAW,SAAS,IAAI,SAAS,CAEhC;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,aAAa,CAExC;IAED;;OAEG;IACI,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAI1D;;OAEG;IACI,gBAAgB,IAAI,aAAa;IAIxC;;OAEG;IACI,WAAW,IAAI,OAAO;IAI7B;;OAEG;IACI,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAQjC;;;;;;;;;;;;;;;;OAgBG;IACI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA2B7B;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAqGlC;;;OAGG;IACI,YAAY,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO;IAItE;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,OAAO,CAAC,WAAW;IA0BnB;;OAEG;IACH,OAAO,CAAC,QAAQ;IA2NhB,OAAO,CAAC,sBAAsB;IAM9B,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,qBAAqB;IAa7B,OAAO,CAAC,kBAAkB;IAwG1B;;OAEG;IAEH,OAAO,CAAC,eAAe;IA2BvB,uBAAuB;IACvB,OAAO,CAAC,cAAc,CAEpB;CACH"} \ No newline at end of file diff --git a/lib/api/user-agent.js b/lib/api/user-agent.js deleted file mode 100644 index 8b78aa1d3..000000000 --- a/lib/api/user-agent.js +++ /dev/null @@ -1,859 +0,0 @@ -import { DigestAuthentication, Grammar, IncomingRequestMessage, IncomingResponseMessage, Levels, LoggerFactory, Parser, URI, UserAgentCore } from "../core"; -import { createRandomToken, utf8Length } from "../core/messages/utils"; -import { defaultSessionDescriptionHandlerFactory } from "../platform/web/session-description-handler"; -import { Transport as WebTransport } from "../platform/web/transport"; -import { LIBRARY_VERSION } from "../version"; -import { EmitterImpl } from "./emitter"; -import { Invitation } from "./invitation"; -import { Inviter } from "./inviter"; -import { Message } from "./message"; -import { Notification } from "./notification"; -import { SIPExtension, UserAgentRegisteredOptionTags } from "./user-agent-options"; -import { UserAgentState } from "./user-agent-state"; -/** - * A user agent sends and receives requests using a `Transport`. - * - * @remarks - * A user agent (UA) is associated with a user via the user's SIP address of record (AOR) - * and acts on behalf of that user to send and receive SIP requests. The user agent can - * register to receive incoming requests, as well as create and send outbound messages. - * The user agent also maintains the Transport over which its signaling travels. - * - * @public - */ -export class UserAgent { - /** - * Constructs a new instance of the `UserAgent` class. - * @param options - Options bucket. See {@link UserAgentOptions} for details. - */ - constructor(options = {}) { - /** @internal */ - this._publishers = {}; - /** @internal */ - this._registerers = {}; - /** @internal */ - this._sessions = {}; - /** @internal */ - this._subscriptions = {}; - this._state = UserAgentState.Stopped; - /** Unload listener. */ - this.unloadListener = () => { - this.stop(); - }; - // state emitter - this._stateEventEmitter = new EmitterImpl(); - // initialize delegate - this.delegate = options.delegate; - // initialize configuration - this.options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, UserAgent.defaultOptions()), { sipjsId: createRandomToken(5) }), { uri: new URI("sip", "anonymous." + createRandomToken(6), "anonymous.invalid") }), { viaHost: createRandomToken(12) + ".invalid" }), UserAgent.stripUndefinedProperties(options)); - // viaHost is hack - if (this.options.hackIpInContact) { - if (typeof this.options.hackIpInContact === "boolean" && this.options.hackIpInContact) { - const from = 1; - const to = 254; - const octet = Math.floor(Math.random() * (to - from + 1) + from); - // random Test-Net IP (http://tools.ietf.org/html/rfc5735) - this.options.viaHost = "192.0.2." + octet; - } - else if (this.options.hackIpInContact) { - this.options.viaHost = this.options.hackIpInContact; - } - } - // initialize logger & logger factory - this.loggerFactory = new LoggerFactory(); - this.logger = this.loggerFactory.getLogger("sip.UserAgent"); - this.loggerFactory.builtinEnabled = this.options.logBuiltinEnabled; - this.loggerFactory.connector = this.options.logConnector; - switch (this.options.logLevel) { - case "error": - this.loggerFactory.level = Levels.error; - break; - case "warn": - this.loggerFactory.level = Levels.warn; - break; - case "log": - this.loggerFactory.level = Levels.log; - break; - case "debug": - this.loggerFactory.level = Levels.debug; - break; - default: - break; - } - if (this.options.logConfiguration) { - this.logger.log("Configuration:"); - Object.keys(this.options).forEach((key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value = this.options[key]; - switch (key) { - case "uri": - case "sessionDescriptionHandlerFactory": - this.logger.log("· " + key + ": " + value); - break; - case "authorizationPassword": - this.logger.log("· " + key + ": " + "NOT SHOWN"); - break; - case "transportConstructor": - this.logger.log("· " + key + ": " + value.name); - break; - default: - this.logger.log("· " + key + ": " + JSON.stringify(value)); - } - }); - } - // guard deprecated transport options (remove this in version 16.x) - if (this.options.transportOptions) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const optionsDeprecated = this.options.transportOptions; - const maxReconnectionAttemptsDeprecated = optionsDeprecated.maxReconnectionAttempts; - const reconnectionTimeoutDeprecated = optionsDeprecated.reconnectionTimeout; - if (maxReconnectionAttemptsDeprecated !== undefined) { - const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (reconnectionTimeoutDeprecated !== undefined) { - const deprecatedMessage = `The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // hack - if (options.reconnectionDelay === undefined && reconnectionTimeoutDeprecated !== undefined) { - this.options.reconnectionDelay = reconnectionTimeoutDeprecated; - } - if (options.reconnectionAttempts === undefined && maxReconnectionAttemptsDeprecated !== undefined) { - this.options.reconnectionAttempts = maxReconnectionAttemptsDeprecated; - } - } - // guard deprecated user agent options (remove this in version 16.x) - if (options.reconnectionDelay !== undefined) { - const deprecatedMessage = `The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (options.reconnectionAttempts !== undefined) { - const deprecatedMessage = `The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // Initialize Transport - this._transport = new this.options.transportConstructor(this.getLogger("sip.Transport"), this.options.transportOptions); - this.initTransportCallbacks(); - // Initialize Contact - this._contact = this.initContact(); - // Initialize UserAgentCore - this._userAgentCore = this.initCore(); - if (this.options.autoStart) { - this.start(); - } - } - /** - * Create a URI instance from a string. - * @param uri - The string to parse. - * - * @example - * ```ts - * const uri = UserAgent.makeURI("sip:edgar@example.com"); - * ``` - */ - static makeURI(uri) { - return Grammar.URIParse(uri); - } - /** Default user agent options. */ - static defaultOptions() { - return { - allowLegacyNotifications: false, - authorizationHa1: "", - authorizationPassword: "", - authorizationUsername: "", - autoStart: false, - autoStop: true, - delegate: {}, - displayName: "", - forceRport: false, - hackAllowUnregisteredOptionTags: false, - hackIpInContact: false, - hackViaTcp: false, - hackWssInTransport: false, - logBuiltinEnabled: true, - logConfiguration: true, - logConnector: () => { - /* noop */ - }, - logLevel: "log", - noAnswerTimeout: 60, - preloadedRouteSet: [], - reconnectionAttempts: 0, - reconnectionDelay: 4, - sessionDescriptionHandlerFactory: defaultSessionDescriptionHandlerFactory(), - sessionDescriptionHandlerFactoryOptions: {}, - sipExtension100rel: SIPExtension.Unsupported, - sipExtensionReplaces: SIPExtension.Unsupported, - sipExtensionExtraSupported: [], - sipjsId: "", - transportConstructor: WebTransport, - transportOptions: {}, - uri: new URI("sip", "anonymous", "anonymous.invalid"), - userAgentString: "SIP.js/" + LIBRARY_VERSION, - viaHost: "" - }; - } - /** - * Strip properties with undefined values from options. - * This is a work around while waiting for missing vs undefined to be addressed (or not)... - * https://github.com/Microsoft/TypeScript/issues/13195 - * @param options - Options to reduce - */ - static stripUndefinedProperties(options) { - return Object.keys(options).reduce((object, key) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (options[key] !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object[key] = options[key]; - } - return object; - }, {}); - } - /** - * User agent configuration. - */ - get configuration() { - return this.options; - } - /** - * User agent contact. - */ - get contact() { - return this._contact; - } - /** - * User agent state. - */ - get state() { - return this._state; - } - /** - * User agent state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * User agent transport. - */ - get transport() { - return this._transport; - } - /** - * User agent core. - */ - get userAgentCore() { - return this._userAgentCore; - } - /** - * The logger. - */ - getLogger(category, label) { - return this.loggerFactory.getLogger(category, label); - } - /** - * The logger factory. - */ - getLoggerFactory() { - return this.loggerFactory; - } - /** - * True if transport is connected. - */ - isConnected() { - return this.transport.isConnected(); - } - /** - * Reconnect the transport. - */ - reconnect() { - if (this.state === UserAgentState.Stopped) { - return Promise.reject(new Error("User agent stopped.")); - } - // Make sure we don't call synchronously - return Promise.resolve().then(() => this.transport.connect()); - } - /** - * Start the user agent. - * - * @remarks - * Resolves if transport connects, otherwise rejects. - * - * @example - * ```ts - * userAgent.start() - * .then(() => { - * // userAgent.isConnected() === true - * }) - * .catch((error: Error) => { - * // userAgent.isConnected() === false - * }); - * ``` - */ - start() { - if (this.state === UserAgentState.Started) { - this.logger.warn(`User agent already started`); - return Promise.resolve(); - } - this.logger.log(`Starting ${this.configuration.uri}`); - // Transition state - this.transitionState(UserAgentState.Started); - // TODO: Review this as it is not clear it has any benefit and at worst causes additional load the server. - // On unload it may be best to simply in most scenarios to do nothing. Furthermore and regardless, this - // kind of behavior seems more appropriate to be managed by the consumer of the API than the API itself. - // Should this perhaps be deprecated? - // - // Add window unload event listener - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && typeof window.addEventListener === "function" && !googleChromePackagedApp) { - window.addEventListener("unload", this.unloadListener); - } - } - return this.transport.connect(); - } - /** - * Stop the user agent. - * - * @remarks - * Resolves when the user agent has completed a graceful shutdown. - * ```txt - * 1) Sessions terminate. - * 2) Registerers unregister. - * 3) Subscribers unsubscribe. - * 4) Publishers unpublish. - * 5) Transport disconnects. - * 6) User Agent Core resets. - * ``` - * NOTE: While this is a "graceful shutdown", it can also be very slow one if you - * are waiting for the returned Promise to resolve. The disposal of the clients and - * dialogs is done serially - waiting on one to finish before moving on to the next. - * This can be slow if there are lot of subscriptions to unsubscribe for example. - * - * THE SLOW PACE IS INTENTIONAL! - * While one could spin them all down in parallel, this could slam the remote server. - * It is bad practice to denial of service attack (DoS attack) servers!!! - * Moreover, production servers will automatically blacklist clients which send too - * many requests in too short a period of time - dropping any additional requests. - * - * If a different approach to disposing is needed, one can implement whatever is - * needed and execute that prior to calling `stop()`. Alternatively one may simply - * not wait for the Promise returned by `stop()` to complete. - */ - async stop() { - if (this.state === UserAgentState.Stopped) { - this.logger.warn(`User agent already stopped`); - return Promise.resolve(); - } - this.logger.log(`Stopping ${this.configuration.uri}`); - // Transition state - this.transitionState(UserAgentState.Stopped); - // TODO: See comments with associated complimentary code in start(). Should this perhaps be deprecated? - // Remove window unload event listener - if (this.options.autoStop) { - // Google Chrome Packaged Apps don't allow 'unload' listeners: unload is not available in packaged apps - const googleChromePackagedApp = typeof chrome !== "undefined" && chrome.app && chrome.app.runtime ? true : false; - if (typeof window !== "undefined" && window.removeEventListener && !googleChromePackagedApp) { - window.removeEventListener("unload", this.unloadListener); - } - } - // Be careful here to use a local references as start() can be called - // again before we complete and we don't want to touch new clients - // and we don't want to step on the new instances (or vice versa). - const publishers = Object.assign({}, this._publishers); - const registerers = Object.assign({}, this._registerers); - const sessions = Object.assign({}, this._sessions); - const subscriptions = Object.assign({}, this._subscriptions); - const transport = this.transport; - const userAgentCore = this.userAgentCore; - // - // At this point we have completed the state transition and everything - // following will effectively run async and MUST NOT cause any issues - // if UserAgent.start() is called while the following code continues. - // - // TODO: Minor optimization. - // The disposal in all cases involves, in part, sending messages which - // is not worth doing if the transport is not connected as we know attempting - // to send messages will be futile. But none of these disposal methods check - // if that's is the case and it would be easy for them to do so at this point. - // Dispose of Registerers - this.logger.log(`Dispose of registerers`); - for (const id in registerers) { - if (registerers[id]) { - await registerers[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._registerers[id]; - throw error; - }); - } - } - // Dispose of Sessions - this.logger.log(`Dispose of sessions`); - for (const id in sessions) { - if (sessions[id]) { - await sessions[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._sessions[id]; - throw error; - }); - } - } - // Dispose of Subscriptions - this.logger.log(`Dispose of subscriptions`); - for (const id in subscriptions) { - if (subscriptions[id]) { - await subscriptions[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._subscriptions[id]; - throw error; - }); - } - } - // Dispose of Publishers - this.logger.log(`Dispose of publishers`); - for (const id in publishers) { - if (publishers[id]) { - await publishers[id].dispose().catch((error) => { - this.logger.error(error.message); - delete this._publishers[id]; - throw error; - }); - } - } - // Dispose of the transport (disconnecting) - this.logger.log(`Dispose of transport`); - await transport.dispose().catch((error) => { - this.logger.error(error.message); - throw error; - }); - // Dispose of the user agent core (resetting) - this.logger.log(`Dispose of core`); - userAgentCore.dispose(); - } - /** - * Used to avoid circular references. - * @internal - */ - _makeInviter(targetURI, options) { - return new Inviter(this, targetURI, options); - } - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - attemptReconnection(reconnectionAttempt = 1) { - const reconnectionAttempts = this.options.reconnectionAttempts; - const reconnectionDelay = this.options.reconnectionDelay; - if (reconnectionAttempt > reconnectionAttempts) { - this.logger.log(`Maximum reconnection attempts reached`); - return; - } - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); - setTimeout(() => { - this.reconnect() - .then(() => { - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); - }) - .catch((error) => { - this.logger.error(error.message); - this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); - this.attemptReconnection(++reconnectionAttempt); - }); - }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); - } - /** - * Initialize contact. - */ - initContact() { - const contactName = createRandomToken(8); // FIXME: should be configurable - const contactTransport = this.options.hackWssInTransport ? "wss" : "ws"; // FIXME: clearly broken for non ws transports - const contact = { - pubGruu: undefined, - tempGruu: undefined, - uri: new URI("sip", contactName, this.options.viaHost, undefined, { transport: contactTransport }), - toString: (contactToStringOptions = {}) => { - const anonymous = contactToStringOptions.anonymous || false; - const outbound = contactToStringOptions.outbound || false; - let contactString = "<"; - if (anonymous) { - contactString += this.contact.tempGruu || `sip:anonymous@anonymous.invalid;transport=${contactTransport}`; - } - else { - contactString += this.contact.pubGruu || this.contact.uri; - } - if (outbound) { - contactString += ";ob"; - } - contactString += ">"; - return contactString; - } - }; - return contact; - } - /** - * Initialize user agent core. - */ - initCore() { - // supported options - let supportedOptionTags = []; - supportedOptionTags.push("outbound"); // TODO: is this really supported? - if (this.options.sipExtension100rel === SIPExtension.Supported) { - supportedOptionTags.push("100rel"); - } - if (this.options.sipExtensionReplaces === SIPExtension.Supported) { - supportedOptionTags.push("replaces"); - } - if (this.options.sipExtensionExtraSupported) { - supportedOptionTags.push(...this.options.sipExtensionExtraSupported); - } - if (!this.options.hackAllowUnregisteredOptionTags) { - supportedOptionTags = supportedOptionTags.filter((optionTag) => UserAgentRegisteredOptionTags[optionTag]); - } - supportedOptionTags = Array.from(new Set(supportedOptionTags)); // array of unique values - // FIXME: TODO: This was ported, but this is and was just plain broken. - const supportedOptionTagsResponse = supportedOptionTags.slice(); - if (this.contact.pubGruu || this.contact.tempGruu) { - supportedOptionTagsResponse.push("gruu"); - } - // core configuration - const userAgentCoreConfiguration = { - aor: this.options.uri, - contact: this.contact, - displayName: this.options.displayName, - loggerFactory: this.loggerFactory, - hackViaTcp: this.options.hackViaTcp, - routeSet: this.options.preloadedRouteSet, - supportedOptionTags, - supportedOptionTagsResponse, - sipjsId: this.options.sipjsId, - userAgentHeaderFieldValue: this.options.userAgentString, - viaForceRport: this.options.forceRport, - viaHost: this.options.viaHost, - authenticationFactory: () => { - const username = this.options.authorizationUsername - ? this.options.authorizationUsername - : this.options.uri.user; // if authorization username not provided, use uri user as username - const password = this.options.authorizationPassword ? this.options.authorizationPassword : undefined; - const ha1 = this.options.authorizationHa1 ? this.options.authorizationHa1 : undefined; - return new DigestAuthentication(this.getLoggerFactory(), ha1, username, password); - }, - transportAccessor: () => this.transport - }; - const userAgentCoreDelegate = { - onInvite: (incomingInviteRequest) => { - var _a; - const invitation = new Invitation(this, incomingInviteRequest); - incomingInviteRequest.delegate = { - onCancel: (cancel) => { - invitation._onCancel(cancel); - }, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTransportError: (error) => { - // A server transaction MUST NOT discard transaction state based only on - // encountering a non-recoverable transport error when sending a - // response. Instead, the associated INVITE server transaction state - // machine MUST remain in its current state. (Timers will eventually - // cause it to transition to the "Terminated" state). - // https://tools.ietf.org/html/rfc6026#section-7.1 - // As noted in the comment above, we are to leaving it to the transaction - // timers to eventually cause the transaction to sort itself out in the case - // of a transport failure in an invite server transaction. This delegate method - // is here simply here for completeness and to make it clear that it provides - // nothing more than informational hook into the core. That is, if you think - // you should be trying to deal with a transport error here, you are likely wrong. - this.logger.error("A transport error has occurred while handling an incoming INVITE request."); - } - }; - // FIXME: Ported - 100 Trying send should be configurable. - // Only required if TU will not respond in 200ms. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - incomingInviteRequest.trying(); - // The Replaces header contains information used to match an existing - // SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE - // with a Replaces header, the User Agent (UA) attempts to match this - // information with a confirmed or early dialog. - // https://tools.ietf.org/html/rfc3891#section-3 - if (this.options.sipExtensionReplaces !== SIPExtension.Unsupported) { - const message = incomingInviteRequest.message; - const replaces = message.parseHeader("replaces"); - if (replaces) { - const callId = replaces.call_id; - if (typeof callId !== "string") { - throw new Error("Type of call id is not string"); - } - const toTag = replaces.replaces_to_tag; - if (typeof toTag !== "string") { - throw new Error("Type of to tag is not string"); - } - const fromTag = replaces.replaces_from_tag; - if (typeof fromTag !== "string") { - throw new Error("type of from tag is not string"); - } - const targetDialogId = callId + toTag + fromTag; - const targetDialog = this.userAgentCore.dialogs.get(targetDialogId); - // If no match is found, the UAS rejects the INVITE and returns a 481 - // Call/Transaction Does Not Exist response. Likewise, if the Replaces - // header field matches a dialog which was not created with an INVITE, - // the UAS MUST reject the request with a 481 response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog) { - invitation.reject({ statusCode: 481 }); - return; - } - // If the Replaces header field matches a confirmed dialog, it checks - // for the presence of the "early-only" flag in the Replaces header - // field. (This flag allows the UAC to prevent a potentially - // undesirable race condition described in Section 7.1.) If the flag is - // present, the UA rejects the request with a 486 Busy response. - // https://tools.ietf.org/html/rfc3891#section-3 - if (!targetDialog.early && replaces.early_only === true) { - invitation.reject({ statusCode: 486 }); - return; - } - // Provide a handle on the session being replaced. - const targetSession = this._sessions[callId + fromTag] || this._sessions[callId + toTag] || undefined; - if (!targetSession) { - throw new Error("Session does not exist."); - } - invitation._replacee = targetSession; - } - } - // Delegate invitation handling. - if ((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) { - if (invitation.autoSendAnInitialProvisionalResponse) { - invitation.progress().then(() => { - var _a; - if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onInvite) === undefined) { - throw new Error("onInvite undefined."); - } - this.delegate.onInvite(invitation); - }); - return; - } - this.delegate.onInvite(invitation); - return; - } - // A common scenario occurs when the callee is currently not willing or - // able to take additional calls at this end system. A 486 (Busy Here) - // SHOULD be returned in such a scenario. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - invitation.reject({ statusCode: 486 }); - }, - onMessage: (incomingMessageRequest) => { - if (this.delegate && this.delegate.onMessage) { - const message = new Message(incomingMessageRequest); - this.delegate.onMessage(message); - } - else { - // Accept the MESSAGE request, but do nothing with it. - incomingMessageRequest.accept(); - } - }, - onNotify: (incomingNotifyRequest) => { - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - if (this.delegate && this.delegate.onNotify) { - const notification = new Notification(incomingNotifyRequest); - this.delegate.onNotify(notification); - } - else { - // Per the above which obsoletes https://tools.ietf.org/html/rfc3265, - // the use of out of dialog NOTIFY is obsolete, but... - if (this.options.allowLegacyNotifications) { - incomingNotifyRequest.accept(); // Accept the NOTIFY request, but do nothing with it. - } - else { - incomingNotifyRequest.reject({ statusCode: 481 }); - } - } - }, - onRefer: (incomingReferRequest) => { - this.logger.warn("Received an out of dialog REFER request"); - // TOOD: this.delegate.onRefer(...) - if (this.delegate && this.delegate.onReferRequest) { - this.delegate.onReferRequest(incomingReferRequest); - } - else { - incomingReferRequest.reject({ statusCode: 405 }); - } - }, - onRegister: (incomingRegisterRequest) => { - this.logger.warn("Received an out of dialog REGISTER request"); - // TOOD: this.delegate.onRegister(...) - if (this.delegate && this.delegate.onRegisterRequest) { - this.delegate.onRegisterRequest(incomingRegisterRequest); - } - else { - incomingRegisterRequest.reject({ statusCode: 405 }); - } - }, - onSubscribe: (incomingSubscribeRequest) => { - this.logger.warn("Received an out of dialog SUBSCRIBE request"); - // TOOD: this.delegate.onSubscribe(...) - if (this.delegate && this.delegate.onSubscribeRequest) { - this.delegate.onSubscribeRequest(incomingSubscribeRequest); - } - else { - incomingSubscribeRequest.reject({ statusCode: 405 }); - } - } - }; - return new UserAgentCore(userAgentCoreConfiguration, userAgentCoreDelegate); - } - initTransportCallbacks() { - this.transport.onConnect = () => this.onTransportConnect(); - this.transport.onDisconnect = (error) => this.onTransportDisconnect(error); - this.transport.onMessage = (message) => this.onTransportMessage(message); - } - onTransportConnect() { - if (this.state === UserAgentState.Stopped) { - return; - } - if (this.delegate && this.delegate.onConnect) { - this.delegate.onConnect(); - } - } - onTransportDisconnect(error) { - if (this.state === UserAgentState.Stopped) { - return; - } - if (this.delegate && this.delegate.onDisconnect) { - this.delegate.onDisconnect(error); - } - // Only attempt to reconnect if network/server dropped the connection. - if (error && this.options.reconnectionAttempts > 0) { - this.attemptReconnection(); - } - } - onTransportMessage(messageString) { - const message = Parser.parseMessage(messageString, this.getLogger("sip.Parser")); - if (!message) { - this.logger.warn("Failed to parse incoming message. Dropping."); - return; - } - if (this.state === UserAgentState.Stopped && message instanceof IncomingRequestMessage) { - this.logger.warn(`Received ${message.method} request while stopped. Dropping.`); - return; - } - // A valid SIP request formulated by a UAC MUST, at a minimum, contain - // the following header fields: To, From, CSeq, Call-ID, Max-Forwards, - // and Via; all of these header fields are mandatory in all SIP - // requests. - // https://tools.ietf.org/html/rfc3261#section-8.1.1 - const hasMinimumHeaders = () => { - const mandatoryHeaders = ["from", "to", "call_id", "cseq", "via"]; - for (const header of mandatoryHeaders) { - if (!message.hasHeader(header)) { - this.logger.warn(`Missing mandatory header field : ${header}.`); - return false; - } - } - return true; - }; - // Request Checks - if (message instanceof IncomingRequestMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn(`Request missing mandatory header field. Dropping.`); - return; - } - // FIXME: This is non-standard and should be a configurable behavior (desirable regardless). - // Custom SIP.js check to reject request from ourself (this instance of SIP.js). - // This is port of SanityCheck.rfc3261_16_3_4(). - if (!message.toTag && message.callId.substr(0, 5) === this.options.sipjsId) { - this.userAgentCore.replyStateless(message, { statusCode: 482 }); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_request(). - const len = utf8Length(message.body); - const contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.userAgentCore.replyStateless(message, { statusCode: 400 }); - return; - } - } - // Response Checks - if (message instanceof IncomingResponseMessage) { - // This is port of SanityCheck.minimumHeaders(). - if (!hasMinimumHeaders()) { - this.logger.warn(`Response missing mandatory header field. Dropping.`); - return; - } - // Custom SIP.js check to drop responses if multiple Via headers. - // This is port of SanityCheck.rfc3261_8_1_3_3(). - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to drop responses if bad Via header. - // This is port of SanityCheck.rfc3261_18_1_2(). - if (message.via.host !== this.options.viaHost || message.via.port !== undefined) { - this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping."); - return; - } - // FIXME: This should be Transport check before we get here (Section 18). - // Custom SIP.js check to reject requests if body length wrong. - // This is port of SanityCheck.rfc3261_18_3_response(). - const len = utf8Length(message.body); - const contentLength = message.getHeader("content-length"); - if (contentLength && len < Number(contentLength)) { - this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping."); - return; - } - } - // Handle Request - if (message instanceof IncomingRequestMessage) { - this.userAgentCore.receiveIncomingRequestFromTransport(message); - return; - } - // Handle Response - if (message instanceof IncomingResponseMessage) { - this.userAgentCore.receiveIncomingResponseFromTransport(message); - return; - } - throw new Error("Invalid message type."); - } - /** - * Transition state. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - transitionState(newState, error) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - // Validate state transition - switch (this._state) { - case UserAgentState.Started: - if (newState !== UserAgentState.Stopped) { - invalidTransition(); - } - break; - case UserAgentState.Stopped: - if (newState !== UserAgentState.Started) { - invalidTransition(); - } - break; - default: - throw new Error("Unknown state."); - } - // Update state - this.logger.log(`Transitioned from ${this._state} to ${newState}`); - this._state = newState; - this._stateEventEmitter.emit(this._state); - } -} diff --git a/lib/core/dialogs/dialog-state.d.ts b/lib/core/dialogs/dialog-state.d.ts deleted file mode 100644 index 1d97f8759..000000000 --- a/lib/core/dialogs/dialog-state.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { URI } from "../../grammar"; -/** - * Dialog state. - * @remarks - * A dialog contains certain pieces of state needed for further message - * transmissions within the dialog. This state consists of the dialog - * ID, a local sequence number (used to order requests from the UA to - * its peer), a remote sequence number (used to order requests from its - * peer to the UA), a local URI, a remote URI, remote target, a boolean - * flag called "secure", and a route set, which is an ordered list of - * URIs. The route set is the list of servers that need to be traversed - * to send a request to the peer. A dialog can also be in the "early" - * state, which occurs when it is created with a provisional response, - * and then transition to the "confirmed" state when a 2xx final - * response arrives. For other responses, or if no response arrives at - * all on that dialog, the early dialog terminates. - * - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -export interface DialogState { - id: string; - early: boolean; - callId: string; - localTag: string; - remoteTag: string; - localSequenceNumber: number | undefined; - remoteSequenceNumber: number | undefined; - localURI: URI; - remoteURI: URI; - remoteTarget: URI; - routeSet: Array; - secure: boolean; -} -//# sourceMappingURL=dialog-state.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/dialog-state.d.ts.map b/lib/core/dialogs/dialog-state.d.ts.map deleted file mode 100644 index e9eebc558..000000000 --- a/lib/core/dialogs/dialog-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dialog-state.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/dialog-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAEpC;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,mBAAmB,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,QAAQ,EAAE,GAAG,CAAC;IACd,SAAS,EAAE,GAAG,CAAC;IACf,YAAY,EAAE,GAAG,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACxB,MAAM,EAAE,OAAO,CAAC;CACjB"} \ No newline at end of file diff --git a/lib/core/dialogs/dialog-state.js b/lib/core/dialogs/dialog-state.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/dialogs/dialog.d.ts b/lib/core/dialogs/dialog.d.ts deleted file mode 100644 index 1c33af893..000000000 --- a/lib/core/dialogs/dialog.d.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingRequestMessage, URI } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { DialogState } from "./dialog-state"; -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -export declare class Dialog { - protected core: UserAgentCore; - protected dialogState: DialogState; - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - protected constructor(core: UserAgentCore, dialogState: DialogState); - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForUserAgentClient(outgoingRequestMessage: OutgoingRequestMessage, incomingResponseMessage: IncomingResponseMessage): DialogState; - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - static initialDialogStateForUserAgentServer(incomingRequestMessage: IncomingRequestMessage, toTag: string, early?: boolean): DialogState; - /** Destructor. */ - dispose(): void; - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get id(): string; - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get early(): boolean; - /** Call identifier component of the dialog id. */ - get callId(): string; - /** Local tag component of the dialog id. */ - get localTag(): string; - /** Remote tag component of the dialog id. */ - get remoteTag(): string; - /** Local sequence number (used to order requests from the UA to its peer). */ - get localSequenceNumber(): number | undefined; - /** Remote sequence number (used to order requests from its peer to the UA). */ - get remoteSequenceNumber(): number | undefined; - /** Local URI. */ - get localURI(): URI; - /** Remote URI. */ - get remoteURI(): URI; - /** Remote target. */ - get remoteTarget(): URI; - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get routeSet(): Array; - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get secure(): boolean; - /** The user agent core servicing this dialog. */ - get userAgentCore(): UserAgentCore; - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm(): void; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message: IncomingRequestMessage): void; - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - recomputeRouteSet(message: IncomingResponseMessage): void; - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - createOutgoingRequestMessage(method: string, options?: { - cseq?: number; - extraHeaders?: Array; - body?: Body; - }): OutgoingRequestMessage; - /** - * Increment the local sequence number by one. - * It feels like this should be protected, but the current authentication handling currently - * needs this to keep the dialog in sync when "auto re-sends" request messages. - * @internal - */ - incrementLocalSequenceNumber(): void; - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - protected sequenceGuard(message: IncomingRequestMessage): boolean; -} -//# sourceMappingURL=dialog.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/dialog.d.ts.map b/lib/core/dialogs/dialog.d.ts.map deleted file mode 100644 index 119237ac3..000000000 --- a/lib/core/dialogs/dialog.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dialog.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/dialog.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EAEJ,sBAAsB,EACtB,uBAAuB,EAEvB,sBAAsB,EACtB,GAAG,EACJ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;;;;;;;;;GAWG;AACH,qBAAa,MAAM;IAMK,SAAS,CAAC,IAAI,EAAE,aAAa;IAAE,SAAS,CAAC,WAAW,EAAE,WAAW;IALvF;;;;OAIG;IACH,SAAS,aAAuB,IAAI,EAAE,aAAa,EAAY,WAAW,EAAE,WAAW;IAIvF;;;;;;;OAOG;WACW,oCAAoC,CAChD,sBAAsB,EAAE,sBAAsB,EAC9C,uBAAuB,EAAE,uBAAuB,GAC/C,WAAW;IA2Gd;;;;;;OAMG;WACW,oCAAoC,CAChD,sBAAsB,EAAE,sBAAsB,EAC9C,KAAK,EAAE,MAAM,EACb,KAAK,UAAQ,GACZ,WAAW;IAqEd,kBAAkB;IACX,OAAO,IAAI,IAAI;IAItB;;;;;;;;OAQG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED;;;;;;;;;;;;;OAaG;IACH,IAAW,KAAK,IAAI,OAAO,CAE1B;IAED,kDAAkD;IAClD,IAAW,MAAM,IAAI,MAAM,CAE1B;IAED,4CAA4C;IAC5C,IAAW,QAAQ,IAAI,MAAM,CAE5B;IAED,6CAA6C;IAC7C,IAAW,SAAS,IAAI,MAAM,CAE7B;IAED,8EAA8E;IAC9E,IAAW,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAEnD;IAED,+EAA+E;IAC/E,IAAW,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAEpD;IAED,iBAAiB;IACjB,IAAW,QAAQ,IAAI,GAAG,CAEzB;IAED,kBAAkB;IAClB,IAAW,SAAS,IAAI,GAAG,CAE1B;IAED,qBAAqB;IACrB,IAAW,YAAY,IAAI,GAAG,CAE7B;IAED;;;OAGG;IACH,IAAW,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,CAEnC;IAED;;;OAGG;IACH,IAAW,MAAM,IAAI,OAAO,CAE3B;IAED,iDAAiD;IACjD,IAAW,aAAa,IAAI,aAAa,CAExC;IAED,qEAAqE;IAC9D,OAAO,IAAI,IAAI;IAItB;;;;;;;;;;;OAWG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAkD5D;;;;;;;;;;;;;;;;;;OAkBG;IACI,iBAAiB,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAIhE;;;;;OAKG;IACI,4BAA4B,CACjC,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;QACR,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,IAAI,CAAC,EAAE,IAAI,CAAC;KACb,GACA,sBAAsB;IAkHzB;;;;;OAKG;IACI,4BAA4B,IAAI,IAAI;IAO3C;;;;;;;;;OASG;IACH,SAAS,CAAC,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO;CAmClE"} \ No newline at end of file diff --git a/lib/core/dialogs/dialog.js b/lib/core/dialogs/dialog.js deleted file mode 100644 index 5b5c5d130..000000000 --- a/lib/core/dialogs/dialog.js +++ /dev/null @@ -1,532 +0,0 @@ -import { C, NameAddrHeader } from "../messages"; -/** - * Dialog. - * @remarks - * A key concept for a user agent is that of a dialog. A dialog - * represents a peer-to-peer SIP relationship between two user agents - * that persists for some time. The dialog facilitates sequencing of - * messages between the user agents and proper routing of requests - * between both of them. The dialog represents a context in which to - * interpret SIP messages. - * https://tools.ietf.org/html/rfc3261#section-12 - * @public - */ -export class Dialog { - /** - * Dialog constructor. - * @param core - User agent core. - * @param dialogState - Initial dialog state. - */ - constructor(core, dialogState) { - this.core = core; - this.dialogState = dialogState; - this.core.dialogs.set(this.id, this); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForUserAgentClient(outgoingRequestMessage, incomingResponseMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const routeSet = incomingResponseMessage.getHeaders("record-route").reverse(); - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const contact = incomingResponseMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const localSequenceNumber = outgoingRequestMessage.cseq; - const remoteSequenceNumber = undefined; - const callId = outgoingRequestMessage.callId; - const localTag = outgoingRequestMessage.fromTag; - const remoteTag = incomingResponseMessage.toTag; - if (!callId) { - // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { - // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { - // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingRequestMessage.from) { - // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingRequestMessage.to) { - // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - const localURI = outgoingRequestMessage.from.uri; - const remoteURI = outgoingRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - if (!incomingResponseMessage.statusCode) { - throw new Error("Incoming response status code undefined."); - } - const early = incomingResponseMessage.statusCode < 200 ? true : false; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - /** - * The UAS then constructs the state of the dialog. This state MUST be - * maintained for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.1 - * @param incomingRequestMessage - Incoming request message creating dialog. - * @param toTag - Tag in the To field in the response to the incoming request. - */ - static initialDialogStateForUserAgentServer(incomingRequestMessage, toTag, early = false) { - // If the request arrived over TLS, and the Request-URI contained a SIPS - // URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the request, taken in order and preserving all URI - // parameters. If no Record-Route header field is present in the - // request, the route set MUST be set to the empty set. This route set, - // even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the request. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const routeSet = incomingRequestMessage.getHeaders("record-route"); - const contact = incomingRequestMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The remote sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The local sequence - // number MUST be empty. The call identifier component of the dialog ID - // MUST be set to the value of the Call-ID in the request. The local - // tag component of the dialog ID MUST be set to the tag in the To field - // in the response to the request (which always includes a tag), and the - // remote tag component of the dialog ID MUST be set to the tag from the - // From field in the request. A UAS MUST be prepared to receive a - // request without a tag in the From field, in which case the tag is - // considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate From tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const remoteSequenceNumber = incomingRequestMessage.cseq; - const localSequenceNumber = undefined; - const callId = incomingRequestMessage.callId; - const localTag = toTag; - const remoteTag = incomingRequestMessage.fromTag; - // The remote URI MUST be set to the URI in the From field, and the - // local URI MUST be set to the URI in the To field. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const remoteURI = incomingRequestMessage.from.uri; - const localURI = incomingRequestMessage.to.uri; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - /** Destructor. */ - dispose() { - this.core.dialogs.delete(this.id); - } - /** - * A dialog is identified at each UA with a dialog ID, which consists of - * a Call-ID value, a local tag and a remote tag. The dialog ID at each - * UA involved in the dialog is not the same. Specifically, the local - * tag at one UA is identical to the remote tag at the peer UA. The - * tags are opaque tokens that facilitate the generation of unique - * dialog IDs. - * https://tools.ietf.org/html/rfc3261#section-12 - */ - get id() { - return this.dialogState.id; - } - /** - * A dialog can also be in the "early" state, which occurs when it is - * created with a provisional response, and then it transition to the - * "confirmed" state when a 2xx final response received or is sent. - * - * Note: RFC 3261 is concise on when a dialog is "confirmed", but it - * can be a point of confusion if an INVITE dialog is "confirmed" after - * a 2xx is sent or after receiving the ACK for the 2xx response. - * With careful reading it can be inferred a dialog is always is - * "confirmed" when the 2xx is sent (regardless of type of dialog). - * However a INVITE dialog does have additional considerations - * when it is confirmed but an ACK has not yet been received (in - * particular with regard to a callee sending BYE requests). - */ - get early() { - return this.dialogState.early; - } - /** Call identifier component of the dialog id. */ - get callId() { - return this.dialogState.callId; - } - /** Local tag component of the dialog id. */ - get localTag() { - return this.dialogState.localTag; - } - /** Remote tag component of the dialog id. */ - get remoteTag() { - return this.dialogState.remoteTag; - } - /** Local sequence number (used to order requests from the UA to its peer). */ - get localSequenceNumber() { - return this.dialogState.localSequenceNumber; - } - /** Remote sequence number (used to order requests from its peer to the UA). */ - get remoteSequenceNumber() { - return this.dialogState.remoteSequenceNumber; - } - /** Local URI. */ - get localURI() { - return this.dialogState.localURI; - } - /** Remote URI. */ - get remoteURI() { - return this.dialogState.remoteURI; - } - /** Remote target. */ - get remoteTarget() { - return this.dialogState.remoteTarget; - } - /** - * Route set, which is an ordered list of URIs. The route set is the - * list of servers that need to be traversed to send a request to the peer. - */ - get routeSet() { - return this.dialogState.routeSet; - } - /** - * If the request was sent over TLS, and the Request-URI contained - * a SIPS URI, the "secure" flag is set to true. *NOT IMPLEMENTED* - */ - get secure() { - return this.dialogState.secure; - } - /** The user agent core servicing this dialog. */ - get userAgentCore() { - return this.core; - } - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm() { - this.dialogState.early = false; - } - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * - * Note that some requests, such as INVITEs, affect several pieces of - * state. - * - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message) { - // ACK guard. - // By convention, the handling of ACKs is the responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, ACKs have same sequence number as the associated INVITE. - if (message.method === C.ACK) { - return; - } - // If the remote sequence number was not empty, but the sequence number - // of the request is lower than the remote sequence number, the request - // is out of order and MUST be rejected with a 500 (Server Internal - // Error) response. If the remote sequence number was not empty, and - // the sequence number of the request is greater than the remote - // sequence number, the request is in order. It is possible for the - // CSeq sequence number to be higher than the remote sequence number by - // more than one. This is not an error condition, and a UAS SHOULD be - // prepared to receive and process requests with CSeq values more than - // one higher than the previous received request. The UAS MUST then set - // the remote sequence number to the value of the sequence number in the - // CSeq header field value in the request. - // - // If a proxy challenges a request generated by the UAC, the UAC has - // to resubmit the request with credentials. The resubmitted request - // will have a new CSeq number. The UAS will never see the first - // request, and thus, it will notice a gap in the CSeq number space. - // Such a gap does not represent any error condition. - // - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (this.remoteSequenceNumber) { - if (message.cseq <= this.remoteSequenceNumber) { - throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?"); - } - this.dialogState.remoteSequenceNumber = message.cseq; - } - // If the remote sequence number is empty, it MUST be set to the value - // of the sequence number in the CSeq header field value in the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.remoteSequenceNumber) { - this.dialogState.remoteSequenceNumber = message.cseq; - } - // When a UAS receives a target refresh request, it MUST replace the - // dialog's remote target URI with the URI from the Contact header field - // in that request, if present. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - // Note: "target refresh request" processing delegated to sub-class. - } - /** - * If the dialog identifier in the 2xx response matches the dialog - * identifier of an existing dialog, the dialog MUST be transitioned to - * the "confirmed" state, and the route set for the dialog MUST be - * recomputed based on the 2xx response using the procedures of Section - * 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - * constructed using the procedures of Section 12.1.2. - * - * Note that the only piece of state that is recomputed is the route - * set. Other pieces of state such as the highest sequence numbers - * (remote and local) sent within the dialog are not recomputed. The - * route set only is recomputed for backwards compatibility. RFC - * 2543 did not mandate mirroring of the Record-Route header field in - * a 1xx, only 2xx. However, we cannot update the entire state of - * the dialog, since mid-dialog requests may have been sent within - * the early dialog, modifying the sequence numbers, for example. - * - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - */ - recomputeRouteSet(message) { - this.dialogState.routeSet = message.getHeaders("record-route").reverse(); - } - /** - * A request within a dialog is constructed by using many of the - * components of the state stored as part of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - * @param method - Outgoing request method. - */ - createOutgoingRequestMessage(method, options) { - // The URI in the To field of the request MUST be set to the remote URI - // from the dialog state. The tag in the To header field of the request - // MUST be set to the remote tag of the dialog ID. The From URI of the - // request MUST be set to the local URI from the dialog state. The tag - // in the From header field of the request MUST be set to the local tag - // of the dialog ID. If the value of the remote or local tags is null, - // the tag parameter MUST be omitted from the To or From header fields, - // respectively. - // - // Usage of the URI from the To and From fields in the original - // request within subsequent requests is done for backwards - // compatibility with RFC 2543, which used the URI for dialog - // identification. In this specification, only the tags are used for - // dialog identification. It is expected that mandatory reflection - // of the original To and From URI in mid-dialog requests will be - // deprecated in a subsequent revision of this specification. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - const toUri = this.remoteURI; - const toTag = this.remoteTag; - const fromUri = this.localURI; - const fromTag = this.localTag; - // The Call-ID of the request MUST be set to the Call-ID of the dialog. - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. If the local sequence number is - // empty, an initial value MUST be chosen using the guidelines of - // Section 8.1.1.5. The method field in the CSeq header field value - // MUST match the method of the request. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - const callId = this.callId; - let cseq; - if (options && options.cseq) { - cseq = options.cseq; - } - else if (!this.dialogState.localSequenceNumber) { - cseq = this.dialogState.localSequenceNumber = 1; // https://tools.ietf.org/html/rfc3261#section-8.1.1.5 - } - else { - cseq = this.dialogState.localSequenceNumber += 1; - } - // The UAC uses the remote target and route set to build the Request-URI - // and Route header field of the request. - // - // If the route set is empty, the UAC MUST place the remote target URI - // into the Request-URI. The UAC MUST NOT add a Route header field to - // the request. - // - // If the route set is not empty, and the first URI in the route set - // contains the lr parameter (see Section 19.1.1), the UAC MUST place - // the remote target URI into the Request-URI and MUST include a Route - // header field containing the route set values in order, including all - // parameters. - // - // If the route set is not empty, and its first URI does not contain the - // lr parameter, the UAC MUST place the first URI from the route set - // into the Request-URI, stripping any parameters that are not allowed - // in a Request-URI. The UAC MUST add a Route header field containing - // the remainder of the route set values in order, including all - // parameters. The UAC MUST then place the remote target URI into the - // Route header field as the last value. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - // The lr parameter, when present, indicates that the element - // responsible for this resource implements the routing mechanisms - // specified in this document. This parameter will be used in the - // URIs proxies place into Record-Route header field values, and - // may appear in the URIs in a pre-existing route set. - // - // This parameter is used to achieve backwards compatibility with - // systems implementing the strict-routing mechanisms of RFC 2543 - // and the rfc2543bis drafts up to bis-05. An element preparing - // to send a request based on a URI not containing this parameter - // can assume the receiving element implements strict-routing and - // reformat the message to preserve the information in the - // Request-URI. - // https://tools.ietf.org/html/rfc3261#section-19.1.1 - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - const ruri = this.remoteTarget; - const routeSet = this.routeSet; - const extraHeaders = options && options.extraHeaders; - const body = options && options.body; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - const message = this.userAgentCore.makeOutgoingRequestMessage(method, ruri, fromUri, toUri, { - callId, - cseq, - fromTag, - toTag, - routeSet - }, extraHeaders, body); - return message; - } - /** - * Increment the local sequence number by one. - * It feels like this should be protected, but the current authentication handling currently - * needs this to keep the dialog in sync when "auto re-sends" request messages. - * @internal - */ - incrementLocalSequenceNumber() { - if (!this.dialogState.localSequenceNumber) { - throw new Error("Local sequence number undefined."); - } - this.dialogState.localSequenceNumber += 1; - } - /** - * If the remote sequence number was not empty, but the sequence number - * of the request is lower than the remote sequence number, the request - * is out of order and MUST be rejected with a 500 (Server Internal - * Error) response. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param request - Incoming request to guard. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise a 500 Server Internal Error was stateless sent and request processing must stop. - */ - sequenceGuard(message) { - // ACK guard. - // By convention, handling of unexpected ACKs is responsibility - // the particular dialog implementation. For example, see SessionDialog. - // Furthermore, we cannot reply to an "out of sequence" ACK. - if (message.method === C.ACK) { - return true; - } - // Note: We are rejecting on "less than or equal to" the remote - // sequence number (excepting ACK whose numbers equal the requests - // being acknowledged or cancelled), which is the correct thing to - // do in our case. The only time a request with the same sequence number - // will show up here if is a) it is a very late retransmission of a - // request we already handled or b) it is a different request with the - // same sequence number which would be violation of the standard. - // Request retransmissions are absorbed by the transaction layer, - // so any request with a duplicate sequence number getting here - // would have to be a retransmission after the transaction terminated - // or a broken request (with unique via branch value). - // Requests within a dialog MUST contain strictly monotonically - // increasing and contiguous CSeq sequence numbers (increasing-by-one) - // in each direction (excepting ACK and CANCEL of course, whose numbers - // equal the requests being acknowledged or cancelled). Therefore, if - // the local sequence number is not empty, the value of the local - // sequence number MUST be incremented by one, and this value MUST be - // placed into the CSeq header field. - // https://tools.ietf.org/html/rfc3261#section-12.2.1.1 - if (this.remoteSequenceNumber && message.cseq <= this.remoteSequenceNumber) { - this.core.replyStateless(message, { statusCode: 500 }); - return false; - } - return true; - } -} diff --git a/lib/core/dialogs/index.d.ts b/lib/core/dialogs/index.d.ts deleted file mode 100644 index c09e33400..000000000 --- a/lib/core/dialogs/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./dialog"; -export * from "./dialog-state"; -export * from "./session-dialog"; -export * from "./subscription-dialog"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/index.d.ts.map b/lib/core/dialogs/index.d.ts.map deleted file mode 100644 index 12c5dbfac..000000000 --- a/lib/core/dialogs/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/lib/core/dialogs/index.js b/lib/core/dialogs/index.js deleted file mode 100644 index 7cacf07f2..000000000 --- a/lib/core/dialogs/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./dialog"; -export * from "./dialog-state"; -export * from "./session-dialog"; -export * from "./subscription-dialog"; diff --git a/lib/core/dialogs/session-dialog.d.ts b/lib/core/dialogs/session-dialog.d.ts deleted file mode 100644 index 2388594d2..000000000 --- a/lib/core/dialogs/session-dialog.d.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingAckRequest, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, OutgoingRequestMessage, RequestOptions } from "../messages"; -import { Session, SessionDelegate, SessionState, SignalingState } from "../session"; -import { InviteClientTransaction, InviteServerTransaction } from "../transactions"; -import { UserAgentCore } from "../user-agent-core"; -import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client"; -import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server"; -import { Dialog } from "./dialog"; -import { DialogState } from "./dialog-state"; -/** - * Session Dialog. - * @public - */ -export declare class SessionDialog extends Dialog implements Session { - private initialTransaction; - delegate: SessionDelegate | undefined; - reinviteUserAgentClient: ReInviteUserAgentClient | undefined; - reinviteUserAgentServer: ReInviteUserAgentServer | undefined; - /** The state of the offer/answer exchange. */ - private _signalingState; - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, or Stable. */ - private _offer; - /** The current answer. Undefined unless signaling state Stable. */ - private _answer; - /** The rollback offer. Undefined unless signaling state HaveLocalOffer or HaveRemoteOffer. */ - private _rollbackOffer; - /** The rollback answer. Undefined unless signaling state HaveLocalOffer or HaveRemoteOffer. */ - private _rollbackAnswer; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - private ackWait; - /** True if processing an ACK to the initial transaction 2xx (UAS only). */ - private ackProcessing; - /** Retransmission timer for 2xx response which confirmed the dialog. */ - private invite2xxTimer; - /** The rseq of the last reliable response. */ - private rseq; - private logger; - constructor(initialTransaction: InviteClientTransaction | InviteServerTransaction, core: UserAgentCore, state: DialogState, delegate?: SessionDelegate); - dispose(): void; - get sessionState(): SessionState; - /** The state of the offer/answer exchange. */ - get signalingState(): SignalingState; - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get offer(): Body | undefined; - /** The current answer. Undefined unless signaling state Stable. */ - get answer(): Body | undefined; - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm(): void; - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - reConfirm(): void; - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - ack(options?: RequestOptions): OutgoingAckRequest; - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; - /** - * A UAC MAY associate a MESSAGE request with an existing dialog. If a - * MESSAGE request is sent within a dialog, it is "associated" with any - * media session or sessions associated with that dialog. - * https://tools.ietf.org/html/rfc3428#section-4 - * @param options - Options bucket. - */ - message(delegate: OutgoingRequestDelegate, options?: RequestOptions): OutgoingMessageRequest; - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message: IncomingRequestMessage): void; - /** - * Guard against out of order reliable provisional responses and retransmissions. - * Returns false if the response should be discarded, otherwise true. - * @param message - Incoming response message within this dialog. - */ - reliableSequenceGuard(message: IncomingResponseMessage): boolean; - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - signalingStateRollback(): void; - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - signalingStateTransition(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | Body): void; - private start2xxRetransmissionTimer; - private startReInvite2xxRetransmissionTimer; -} -//# sourceMappingURL=session-dialog.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/session-dialog.d.ts.map b/lib/core/dialogs/session-dialog.d.ts.map deleted file mode 100644 index bd291f5d8..000000000 --- a/lib/core/dialogs/session-dialog.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-dialog.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/session-dialog.ts"],"names":[],"mappings":"AACA,OAAO,EACL,IAAI,EAGJ,sBAAsB,EACtB,uBAAuB,EAGvB,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,6BAA6B,EAC7B,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEpF,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAoB,MAAM,iBAAiB,CAAC;AACrG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAWnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AAGrF,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;GAGG;AACH,qBAAa,aAAc,SAAQ,MAAO,YAAW,OAAO;IA6BxD,OAAO,CAAC,kBAAkB;IA5BrB,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IAEtC,uBAAuB,EAAE,uBAAuB,GAAG,SAAS,CAAC;IAC7D,uBAAuB,EAAE,uBAAuB,GAAG,SAAS,CAAC;IAEpE,8CAA8C;IAC9C,OAAO,CAAC,eAAe,CAA0C;IACjE,sGAAsG;IACtG,OAAO,CAAC,MAAM,CAAmB;IACjC,mEAAmE;IACnE,OAAO,CAAC,OAAO,CAAmB;IAClC,8FAA8F;IAC9F,OAAO,CAAC,cAAc,CAAmB;IACzC,+FAA+F;IAC/F,OAAO,CAAC,eAAe,CAAmB;IAE1C,4EAA4E;IAC5E,OAAO,CAAC,OAAO,CAAS;IACxB,2EAA2E;IAC3E,OAAO,CAAC,aAAa,CAAS;IAC9B,wEAAwE;IACxE,OAAO,CAAC,cAAc,CAAqB;IAC3C,8CAA8C;IAC9C,OAAO,CAAC,IAAI,CAAqB;IAEjC,OAAO,CAAC,MAAM,CAAS;gBAGb,kBAAkB,EAAE,uBAAuB,GAAG,uBAAuB,EAC7E,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE,WAAW,EAClB,QAAQ,CAAC,EAAE,eAAe;IAmBrB,OAAO,IAAI,IAAI;IAsBtB,IAAI,YAAY,IAAI,YAAY,CAU/B;IAED,8CAA8C;IAC9C,IAAI,cAAc,IAAI,cAAc,CAEnC;IAED,sGAAsG;IACtG,IAAI,KAAK,IAAI,IAAI,GAAG,SAAS,CAE5B;IAED,mEAAmE;IACnE,IAAI,MAAM,IAAI,IAAI,GAAG,SAAS,CAE7B;IAED,qEAAqE;IAC9D,OAAO,IAAI,IAAI;IAStB,yEAAyE;IAClE,SAAS,IAAI,IAAI;IAQxB;;;;;;;;;;;;;;OAcG;IACI,GAAG,CAAC,OAAO,GAAE,cAAmB,GAAG,kBAAkB;IA2B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoCG;IACI,GAAG,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,kBAAkB;IA0C5F;;;;;;;;;OASG;IACI,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,mBAAmB;IAS9F;;;;;;;;;;;;;;;;;;;;OAoBG;IACI,MAAM,CAAC,QAAQ,CAAC,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB;IAkCxG;;;;;;OAMG;IACI,OAAO,CAAC,QAAQ,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,sBAAsB;IAUnG;;;;;OAKG;IACI,MAAM,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB;IASlG;;;;;;;;;OASG;IACI,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB;IAKhG;;;;;OAKG;IACI,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB;IAUhG;;;;;;;OAOG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAiR5D;;;;OAIG;IACI,qBAAqB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO;IAgDvE;;OAEG;IACI,sBAAsB,IAAI,IAAI;IAarC;;;OAGG;IACI,wBAAwB,CAC7B,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,sBAAsB,GAAG,IAAI,GACxF,IAAI;IAmHP,OAAO,CAAC,2BAA2B;IAqDnC,OAAO,CAAC,mCAAmC;CA+C5C"} \ No newline at end of file diff --git a/lib/core/dialogs/session-dialog.js b/lib/core/dialogs/session-dialog.js deleted file mode 100644 index dda12375c..000000000 --- a/lib/core/dialogs/session-dialog.js +++ /dev/null @@ -1,895 +0,0 @@ -import { C, getBody, IncomingRequestMessage, IncomingResponseMessage, isBody, NameAddrHeader, OutgoingRequestMessage } from "../messages"; -import { SessionState, SignalingState } from "../session"; -import { Timers } from "../timers"; -import { InviteClientTransaction, InviteServerTransaction, TransactionState } from "../transactions"; -import { ByeUserAgentClient } from "../user-agents/bye-user-agent-client"; -import { ByeUserAgentServer } from "../user-agents/bye-user-agent-server"; -import { InfoUserAgentClient } from "../user-agents/info-user-agent-client"; -import { InfoUserAgentServer } from "../user-agents/info-user-agent-server"; -import { MessageUserAgentClient } from "../user-agents/message-user-agent-client"; -import { MessageUserAgentServer } from "../user-agents/message-user-agent-server"; -import { NotifyUserAgentClient } from "../user-agents/notify-user-agent-client"; -import { NotifyUserAgentServer } from "../user-agents/notify-user-agent-server"; -import { PrackUserAgentClient } from "../user-agents/prack-user-agent-client"; -import { PrackUserAgentServer } from "../user-agents/prack-user-agent-server"; -import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client"; -import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server"; -import { ReferUserAgentClient } from "../user-agents/refer-user-agent-client"; -import { ReferUserAgentServer } from "../user-agents/refer-user-agent-server"; -import { Dialog } from "./dialog"; -/** - * Session Dialog. - * @public - */ -export class SessionDialog extends Dialog { - constructor(initialTransaction, core, state, delegate) { - super(core, state); - this.initialTransaction = initialTransaction; - /** The state of the offer/answer exchange. */ - this._signalingState = SignalingState.Initial; - /** True if waiting for an ACK to the initial transaction 2xx (UAS only). */ - this.ackWait = false; - /** True if processing an ACK to the initial transaction 2xx (UAS only). */ - this.ackProcessing = false; - this.delegate = delegate; - if (initialTransaction instanceof InviteServerTransaction) { - // If we're created by an invite server transaction, we're - // going to be waiting for an ACK if are to be confirmed. - this.ackWait = true; - } - // If we're confirmed upon creation start the retransmitting whatever - // the 2xx final response was that confirmed us into existence. - if (!this.early) { - this.start2xxRetransmissionTimer(); - } - this.signalingStateTransition(initialTransaction.request); - this.logger = core.loggerFactory.getLogger("sip.invite-dialog"); - this.logger.log(`INVITE dialog ${this.id} constructed`); - } - dispose() { - super.dispose(); - this._signalingState = SignalingState.Closed; - this._offer = undefined; - this._answer = undefined; - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - // TODO: - // this.userAgentServers.forEach((uas) => uas.reply(487)); - this.logger.log(`INVITE dialog ${this.id} destroyed`); - } - // FIXME: Need real state machine - get sessionState() { - if (this.early) { - return SessionState.Early; - } - else if (this.ackWait) { - return SessionState.AckWait; - } - else if (this._signalingState === SignalingState.Closed) { - return SessionState.Terminated; - } - else { - return SessionState.Confirmed; - } - } - /** The state of the offer/answer exchange. */ - get signalingState() { - return this._signalingState; - } - /** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */ - get offer() { - return this._offer; - } - /** The current answer. Undefined unless signaling state Stable. */ - get answer() { - return this._answer; - } - /** Confirm the dialog. Only matters if dialog is currently early. */ - confirm() { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.early) { - this.start2xxRetransmissionTimer(); - } - super.confirm(); - } - /** Re-confirm the dialog. Only matters if handling re-INVITE request. */ - reConfirm() { - // When we're confirmed start the retransmitting whatever - // the 2xx final response that may have confirmed us. - if (this.reinviteUserAgentServer) { - this.startReInvite2xxRetransmissionTimer(); - } - } - /** - * The UAC core MUST generate an ACK request for each 2xx received from - * the transaction layer. The header fields of the ACK are constructed - * in the same way as for any request sent within a dialog (see Section - * 12) with the exception of the CSeq and the header fields related to - * authentication. The sequence number of the CSeq header field MUST be - * the same as the INVITE being acknowledged, but the CSeq method MUST - * be ACK. The ACK MUST contain the same credentials as the INVITE. If - * the 2xx contains an offer (based on the rules above), the ACK MUST - * carry an answer in its body. If the offer in the 2xx response is not - * acceptable, the UAC core MUST generate a valid answer in the ACK and - * then send a BYE immediately. - * https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - * @param options - ACK options bucket. - */ - ack(options = {}) { - this.logger.log(`INVITE dialog ${this.id} sending ACK request`); - let transaction; - if (this.reinviteUserAgentClient) { - // We're sending ACK for a re-INVITE - if (!(this.reinviteUserAgentClient.transaction instanceof InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - transaction = this.reinviteUserAgentClient.transaction; - this.reinviteUserAgentClient = undefined; - } - else { - // We're sending ACK for the initial INVITE - if (!(this.initialTransaction instanceof InviteClientTransaction)) { - throw new Error("Initial transaction not instance of InviteClientTransaction."); - } - transaction = this.initialTransaction; - } - const message = this.createOutgoingRequestMessage(C.ACK, { - cseq: transaction.request.cseq, - extraHeaders: options.extraHeaders, - body: options.body - }); - transaction.ackResponse(message); // See InviteClientTransaction for details. - this.signalingStateTransition(message); - return { message }; - } - /** - * Terminating a Session - * - * This section describes the procedures for terminating a session - * established by SIP. The state of the session and the state of the - * dialog are very closely related. When a session is initiated with an - * INVITE, each 1xx or 2xx response from a distinct UAS creates a - * dialog, and if that response completes the offer/answer exchange, it - * also creates a session. As a result, each session is "associated" - * with a single dialog - the one which resulted in its creation. If an - * initial INVITE generates a non-2xx final response, that terminates - * all sessions (if any) and all dialogs (if any) that were created - * through responses to the request. By virtue of completing the - * transaction, a non-2xx final response also prevents further sessions - * from being created as a result of the INVITE. The BYE request is - * used to terminate a specific session or attempted session. In this - * case, the specific session is the one with the peer UA on the other - * side of the dialog. When a BYE is received on a dialog, any session - * associated with that dialog SHOULD terminate. A UA MUST NOT send a - * BYE outside of a dialog. The caller's UA MAY send a BYE for either - * confirmed or early dialogs, and the callee's UA MAY send a BYE on - * confirmed dialogs, but MUST NOT send a BYE on early dialogs. - * - * However, the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out. If no SIP extensions have defined other - * application layer states associated with the dialog, the BYE also - * terminates the dialog. - * - * https://tools.ietf.org/html/rfc3261#section-15 - * FIXME: Make these proper Exceptions... - * @param options - BYE options bucket. - * @returns - * Throws `Error` if callee's UA attempts a BYE on an early dialog. - * Throws `Error` if callee's UA attempts a BYE on a confirmed dialog - * while it's waiting on the ACK for its 2xx response. - */ - bye(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending BYE request`); - // The caller's UA MAY send a BYE for either - // confirmed or early dialogs, and the callee's UA MAY send a BYE on - // confirmed dialogs, but MUST NOT send a BYE on early dialogs. - // - // However, the callee's UA MUST NOT send a BYE on a confirmed dialog - // until it has received an ACK for its 2xx response or until the server - // transaction times out. - // https://tools.ietf.org/html/rfc3261#section-15 - if (this.initialTransaction instanceof InviteServerTransaction) { - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on early dialogs."); - } - if (this.ackWait && this.initialTransaction.state !== TransactionState.Terminated) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("UAS MUST NOT send a BYE on a confirmed dialog " + - "until it has received an ACK for its 2xx response " + - "or until the server transaction times out."); - } - } - // A BYE request is constructed as would any other request within a - // dialog, as described in Section 12. - // - // Once the BYE is constructed, the UAC core creates a new non-INVITE - // client transaction, and passes it the BYE request. The UAC MUST - // consider the session terminated (and therefore stop sending or - // listening for media) as soon as the BYE request is passed to the - // client transaction. If the response for the BYE is a 481 - // (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no - // response at all is received for the BYE (that is, a timeout is - // returned by the client transaction), the UAC MUST consider the - // session and the dialog terminated. - // https://tools.ietf.org/html/rfc3261#section-15.1.1 - return new ByeUserAgentClient(this, delegate, options); - } - /** - * An INFO request can be associated with an Info Package (see - * Section 5), or associated with a legacy INFO usage (see Section 2). - * - * The construction of the INFO request is the same as any other - * non-target refresh request within an existing invite dialog usage as - * described in Section 12.2 of RFC 3261. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param options - Options bucket. - */ - info(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending INFO request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new InfoUserAgentClient(this, delegate, options); - } - /** - * Modifying an Existing Session - * - * A successful INVITE request (see Section 13) establishes both a - * dialog between two user agents and a session using the offer-answer - * model. Section 12 explains how to modify an existing dialog using a - * target refresh request (for example, changing the remote target URI - * of the dialog). This section describes how to modify the actual - * session. This modification can involve changing addresses or ports, - * adding a media stream, deleting a media stream, and so on. This is - * accomplished by sending a new INVITE request within the same dialog - * that established the session. An INVITE request sent within an - * existing dialog is known as a re-INVITE. - * - * Note that a single re-INVITE can modify the dialog and the - * parameters of the session at the same time. - * - * Either the caller or callee can modify an existing session. - * https://tools.ietf.org/html/rfc3261#section-14 - * @param options - Options bucket - */ - invite(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending INVITE request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // Note that a UAC MUST NOT initiate a new INVITE transaction within a - // dialog while another INVITE transaction is in progress in either - // direction. - // - // 1. If there is an ongoing INVITE client transaction, the TU MUST - // wait until the transaction reaches the completed or terminated - // state before initiating the new INVITE. - // - // 2. If there is an ongoing INVITE server transaction, the TU MUST - // wait until the transaction reaches the confirmed or terminated - // state before initiating the new INVITE. - // - // However, a UA MAY initiate a regular transaction while an INVITE - // transaction is in progress. A UA MAY also initiate an INVITE - // transaction while a regular transaction is in progress. - // https://tools.ietf.org/html/rfc3261#section-14.1 - if (this.reinviteUserAgentClient) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE client transaction."); - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("There is an ongoing re-INVITE server transaction."); - } - return new ReInviteUserAgentClient(this, delegate, options); - } - /** - * A UAC MAY associate a MESSAGE request with an existing dialog. If a - * MESSAGE request is sent within a dialog, it is "associated" with any - * media session or sessions associated with that dialog. - * https://tools.ietf.org/html/rfc3428#section-4 - * @param options - Options bucket. - */ - message(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - const message = this.createOutgoingRequestMessage(C.MESSAGE, options); - return new MessageUserAgentClient(this.core, message, delegate); - } - /** - * The NOTIFY mechanism defined in [2] MUST be used to inform the agent - * sending the REFER of the status of the reference. - * https://tools.ietf.org/html/rfc3515#section-2.4.4 - * @param options - Options bucket. - */ - notify(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - return new NotifyUserAgentClient(this, delegate, options); - } - /** - * Assuming the response is to be transmitted reliably, the UAC MUST - * create a new request with method PRACK. This request is sent within - * the dialog associated with the provisional response (indeed, the - * provisional response may have created the dialog). PRACK requests - * MAY contain bodies, which are interpreted according to their type and - * disposition. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param options - Options bucket. - */ - prack(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending PRACK request`); - return new PrackUserAgentClient(this, delegate, options); - } - /** - * REFER is a SIP request and is constructed as defined in [1]. A REFER - * request MUST contain exactly one Refer-To header field value. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param options - Options bucket. - */ - refer(delegate, options) { - this.logger.log(`INVITE dialog ${this.id} sending REFER request`); - if (this.early) { - // FIXME: TODO: This should throw a proper exception. - throw new Error("Dialog not confirmed."); - } - // FIXME: TODO: Validate Refer-To header field value. - return new ReferUserAgentClient(this, delegate, options); - } - /** - * Requests sent within a dialog, as any other requests, are atomic. If - * a particular request is accepted by the UAS, all the state changes - * associated with it are performed. If the request is rejected, none - * of the state changes are performed. - * https://tools.ietf.org/html/rfc3261#section-12.2.2 - * @param message - Incoming request message within this dialog. - */ - receiveRequest(message) { - this.logger.log(`INVITE dialog ${this.id} received ${message.method} request`); - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - if (message.method === C.ACK) { - // If ackWait is true, then this is the ACK to the initial INVITE, - // otherwise this is an ACK to an in dialog INVITE. In either case, - // guard to make sure the sequence number of the ACK matches the INVITE. - if (this.ackWait) { - if (this.initialTransaction instanceof InviteClientTransaction) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - if (this.initialTransaction.request.cseq !== message.cseq) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - // Update before the delegate has a chance to handle the - // message as delegate may callback into this dialog. - this.ackWait = false; - } - else { - if (!this.reinviteUserAgentServer) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) { - this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`); - return; - } - this.reinviteUserAgentServer = undefined; - } - this.signalingStateTransition(message); - if (this.delegate && this.delegate.onAck) { - const promiseOrVoid = this.delegate.onAck({ message }); - if (promiseOrVoid instanceof Promise) { - this.ackProcessing = true; // make sure this is always reset to false - promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false)); - } - } - return; - } - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log(`INVITE dialog ${this.id} rejected out of order ${message.method} request.`); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - super.receiveRequest(message); - // Handle various INVITE related cross-over, glare and race conditions - if (message.method === C.INVITE) { - // Hopefully this message is helpful... - const warning = () => { - const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK"; - this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`); - let msg = "RFC 5407 suggests the following to avoid this race condition... "; - msg += " Note: Implementation issues are outside the scope of this document,"; - msg += " but the following tip is provided for avoiding race conditions of"; - msg += " this type. The caller can delay sending re-INVITE F6 for some period"; - msg += " of time (2 seconds, perhaps), after which the caller can reasonably"; - msg += " assume that its ACK has been received. Implementors can decouple the"; - msg += " actions of the user (e.g., pressing the hold button) from the actions"; - msg += " of the protocol (the sending of re-INVITE F6), so that the UA can"; - msg += " behave like this. In this case, it is the implementor's choice as to"; - msg += " how long to wait. In most cases, such an implementation may be"; - msg += " useful to prevent the type of race condition shown in this section."; - msg += " This document expresses no preference about whether or not they"; - msg += " should wait for an ACK to be delivered. After considering the impact"; - msg += " on user experience, implementors should decide whether or not to wait"; - msg += " for a while, because the user experience depends on the"; - msg += " implementation and has no direct bearing on protocol behavior."; - this.logger.warn(msg); - return; // drop re-INVITE request message - }; - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - const retryAfter = Math.floor(Math.random() * 10) + 1; - const extraHeaders = [`Retry-After: ${retryAfter}`]; - // There may be ONLY ONE offer/answer negotiation in progress for a - // single dialog at any point in time. Section 4 explains how to ensure - // this. - // https://tools.ietf.org/html/rfc6337#section-2.2 - if (this.ackProcessing) { - // UAS-IsI: While an INVITE server transaction is incomplete or ACK - // transaction associated with an offer/answer is incomplete, - // a UA must reject another INVITE request with a 500 - // response. - // https://tools.ietf.org/html/rfc6337#section-4.3 - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - warning(); - return; - } - // 3.1.4. Callee Receives re-INVITE (Established State) While in the - // Moratorium State (Case 1) - // https://tools.ietf.org/html/rfc5407#section-3.1.4 - // 3.1.5. Callee Receives re-INVITE (Established State) While in the - // Moratorium State (Case 2) - // https://tools.ietf.org/html/rfc5407#section-3.1.5 - if (this.ackWait && this.signalingState !== SignalingState.Stable) { - // This scenario is basically the same as that of Section 3.1.4, but - // differs in sending an offer in the 200 and an answer in the ACK. In - // contrast to the previous case, the offer in the 200 (F3) and the - // offer in the re-INVITE (F6) collide with each other. - // - // Bob sends a 491 to the re-INVITE (F6) since he is not able to - // properly handle a new request until he receives an answer. (Note: - // 500 with a Retry-After header may be returned if the 491 response is - // understood to indicate request collision. However, 491 is - // recommended here because 500 applies to so many cases that it is - // difficult to determine what the real problem was.) - // https://tools.ietf.org/html/rfc5407#section-3.1.5 - // UAS-IsI: While an INVITE server transaction is incomplete or ACK - // transaction associated with an offer/answer is incomplete, - // a UA must reject another INVITE request with a 500 - // response. - // https://tools.ietf.org/html/rfc6337#section-4.3 - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - warning(); - return; - } - // A UAS that receives a second INVITE before it sends the final - // response to a first INVITE with a lower CSeq sequence number on the - // same dialog MUST return a 500 (Server Internal Error) response to the - // second INVITE and MUST include a Retry-After header field with a - // randomly chosen value of between 0 and 10 seconds. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentServer) { - this.core.replyStateless(message, { statusCode: 500, extraHeaders }); - return; - } - // A UAS that receives an INVITE on a dialog while an INVITE it had sent - // on that dialog is in progress MUST return a 491 (Request Pending) - // response to the received INVITE. - // https://tools.ietf.org/html/rfc3261#section-14.2 - if (this.reinviteUserAgentClient) { - this.core.replyStateless(message, { statusCode: 491 }); - return; - } - } - // Requests within a dialog MAY contain Record-Route and Contact header - // fields. However, these requests do not cause the dialog's route set - // to be modified, although they may modify the remote target URI. - // Specifically, requests that are not target refresh requests do not - // modify the dialog's remote target URI, and requests that are target - // refresh requests do. For dialogs that have been established with an - // INVITE, the only target refresh request defined is re-INVITE (see - // Section 14). Other extensions may define different target refresh - // requests for dialogs established in other ways. - // - // Note that an ACK is NOT a target refresh request. - // - // Target refresh requests only update the dialog's remote target URI, - // and not the route set formed from the Record-Route. Updating the - // latter would introduce severe backwards compatibility problems with - // RFC 2543-compliant systems. - // https://tools.ietf.org/html/rfc3261#section-15 - if (message.method === C.INVITE) { - // FIXME: parser needs to be typed... - const contact = message.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - this.dialogState.remoteTarget = contact.uri; - } - // Switch on method and then delegate. - switch (message.method) { - case C.BYE: - // A UAS core receiving a BYE request for an existing dialog MUST follow - // the procedures of Section 12.2.2 to process the request. Once done, - // the UAS SHOULD terminate the session (and therefore stop sending and - // listening for media). The only case where it can elect not to are - // multicast sessions, where participation is possible even if the other - // participant in the dialog has terminated its involvement in the - // session. Whether or not it ends its participation on the session, - // the UAS core MUST generate a 2xx response to the BYE, and MUST pass - // that to the server transaction for transmission. - // - // The UAS MUST still respond to any pending requests received for that - // dialog. It is RECOMMENDED that a 487 (Request Terminated) response - // be generated to those pending requests. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - { - const uas = new ByeUserAgentServer(this, message); - this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept(); - this.dispose(); - } - break; - case C.INFO: - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - { - const uas = new InfoUserAgentServer(this, message); - this.delegate && this.delegate.onInfo - ? this.delegate.onInfo(uas) - : uas.reject({ - statusCode: 469, - extraHeaders: ["Recv-Info :"] - }); - } - break; - case C.INVITE: - // If the new session description is not acceptable, the UAS can reject - // it by returning a 488 (Not Acceptable Here) response for the re- - // INVITE. This response SHOULD include a Warning header field. - // https://tools.ietf.org/html/rfc3261#section-14.2 - { - const uas = new ReInviteUserAgentServer(this, message); - this.signalingStateTransition(message); - this.delegate && this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject({ statusCode: 488 }); // TODO: Warning header field. - } - break; - case C.MESSAGE: - { - const uas = new MessageUserAgentServer(this.core, message); - this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); - } - break; - case C.NOTIFY: - // https://tools.ietf.org/html/rfc3515#section-2.4.4 - { - const uas = new NotifyUserAgentServer(this, message); - this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept(); - } - break; - case C.PRACK: - // https://tools.ietf.org/html/rfc3262#section-4 - { - const uas = new PrackUserAgentServer(this, message); - this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept(); - } - break; - case C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - const uas = new ReferUserAgentServer(this, message); - this.delegate && this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject(); - } - break; - default: - { - this.logger.log(`INVITE dialog ${this.id} received unimplemented ${message.method} request`); - this.core.replyStateless(message, { statusCode: 501 }); - } - break; - } - } - /** - * Guard against out of order reliable provisional responses and retransmissions. - * Returns false if the response should be discarded, otherwise true. - * @param message - Incoming response message within this dialog. - */ - reliableSequenceGuard(message) { - const statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Status code undefined"); - } - if (statusCode > 100 && statusCode < 200) { - // If a provisional response is received for an initial request, and - // that response contains a Require header field containing the option - // tag 100rel, the response is to be sent reliably. If the response is - // a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be - // ignored, and the procedures below MUST NOT be used. - // https://tools.ietf.org/html/rfc3262#section-4 - const requireHeader = message.getHeader("require"); - const rseqHeader = message.getHeader("rseq"); - const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined; - if (rseq) { - // Handling of subsequent reliable provisional responses for the same - // initial request follows the same rules as above, with the following - // difference: reliable provisional responses are guaranteed to be in - // order. As a result, if the UAC receives another reliable provisional - // response to the same request, and its RSeq value is not one higher - // than the value of the sequence number, that response MUST NOT be - // acknowledged with a PRACK, and MUST NOT be processed further by the - // UAC. An implementation MAY discard the response, or MAY cache the - // response in the hopes of receiving the missing responses. - // https://tools.ietf.org/html/rfc3262#section-4 - if (this.rseq && this.rseq + 1 !== rseq) { - return false; - } - // Once a reliable provisional response is received, retransmissions of - // that response MUST be discarded. A response is a retransmission when - // its dialog ID, CSeq, and RSeq match the original response. The UAC - // MUST maintain a sequence number that indicates the most recently - // received in-order reliable provisional response for the initial - // request. This sequence number MUST be maintained until a final - // response is received for the initial request. Its value MUST be - // initialized to the RSeq header field in the first reliable - // provisional response received for the initial request. - // https://tools.ietf.org/html/rfc3262#section-4 - this.rseq = this.rseq ? this.rseq + 1 : rseq; - } - } - return true; - } - /** - * If not in a stable signaling state, rollback to prior stable signaling state. - */ - signalingStateRollback() { - if (this._signalingState === SignalingState.HaveLocalOffer || - this.signalingState === SignalingState.HaveRemoteOffer) { - if (this._rollbackOffer && this._rollbackAnswer) { - this._signalingState = SignalingState.Stable; - this._offer = this._rollbackOffer; - this._answer = this._rollbackAnswer; - } - } - } - /** - * Update the signaling state of the dialog. - * @param message - The message to base the update off of. - */ - signalingStateTransition(message) { - const body = getBody(message); - // No body, no session. No, woman, no cry. - if (!body || body.contentDisposition !== "session") { - return; - } - // We've got an existing offer and answer which we may wish to rollback to - if (this._signalingState === SignalingState.Stable) { - this._rollbackOffer = this._offer; - this._rollbackAnswer = this._answer; - } - // We're in UAS role, receiving incoming request with session description - if (message instanceof IncomingRequestMessage) { - switch (this._signalingState) { - case SignalingState.Initial: - case SignalingState.Stable: - this._signalingState = SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case SignalingState.HaveLocalOffer: - this._signalingState = SignalingState.Stable; - this._answer = body; - break; - case SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, receiving incoming response with session description - if (message instanceof IncomingResponseMessage) { - switch (this._signalingState) { - case SignalingState.Initial: - case SignalingState.Stable: - this._signalingState = SignalingState.HaveRemoteOffer; - this._offer = body; - this._answer = undefined; - break; - case SignalingState.HaveLocalOffer: - this._signalingState = SignalingState.Stable; - this._answer = body; - break; - case SignalingState.HaveRemoteOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAC role, sending outgoing request with session description - if (message instanceof OutgoingRequestMessage) { - switch (this._signalingState) { - case SignalingState.Initial: - case SignalingState.Stable: - this._signalingState = SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case SignalingState.HaveRemoteOffer: - this._signalingState = SignalingState.Stable; - this._answer = body; - break; - case SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - // We're in UAS role, sending outgoing response with session description - if (isBody(message)) { - switch (this._signalingState) { - case SignalingState.Initial: - case SignalingState.Stable: - this._signalingState = SignalingState.HaveLocalOffer; - this._offer = body; - this._answer = undefined; - break; - case SignalingState.HaveLocalOffer: - // You cannot make a new offer while one is in progress. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - // FIXME: What to do here? - break; - case SignalingState.HaveRemoteOffer: - this._signalingState = SignalingState.Stable; - this._answer = body; - break; - case SignalingState.Closed: - break; - default: - throw new Error("Unexpected signaling state."); - } - } - } - start2xxRetransmissionTimer() { - if (this.initialTransaction instanceof InviteServerTransaction) { - const transaction = this.initialTransaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - let timeout = Timers.T1; - const retransmission = () => { - if (!this.ackWait) { - this.invite2xxTimer = undefined; - return; - } - this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction.retransmitAcceptedResponse(); - timeout = Math.min(timeout * 2, Timers.T2); - this.invite2xxTimer = setTimeout(retransmission, timeout); - }; - this.invite2xxTimer = setTimeout(retransmission, timeout); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - const stateChanged = () => { - if (transaction.state === TransactionState.Terminated) { - transaction.removeStateChangeListener(stateChanged); - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - if (this.ackWait) { - if (this.delegate && this.delegate.onAckTimeout) { - this.delegate.onAckTimeout(); - } - else { - this.bye(); - } - } - } - }; - transaction.addStateChangeListener(stateChanged); - } - } - // FIXME: Refactor - startReInvite2xxRetransmissionTimer() { - if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof InviteServerTransaction) { - const transaction = this.reinviteUserAgentServer.transaction; - // Once the response has been constructed, it is passed to the INVITE - // server transaction. In order to ensure reliable end-to-end - // transport of the response, it is necessary to periodically pass - // the response directly to the transport until the ACK arrives. The - // 2xx response is passed to the transport with an interval that - // starts at T1 seconds and doubles for each retransmission until it - // reaches T2 seconds (T1 and T2 are defined in Section 17). - // Response retransmissions cease when an ACK request for the - // response is received. This is independent of whatever transport - // protocols are used to send the response. - // https://tools.ietf.org/html/rfc6026#section-8.1 - let timeout = Timers.T1; - const retransmission = () => { - if (!this.reinviteUserAgentServer) { - this.invite2xxTimer = undefined; - return; - } - this.logger.log("No ACK for 2xx response received, attempting retransmission"); - transaction.retransmitAcceptedResponse(); - timeout = Math.min(timeout * 2, Timers.T2); - this.invite2xxTimer = setTimeout(retransmission, timeout); - }; - this.invite2xxTimer = setTimeout(retransmission, timeout); - // If the server retransmits the 2xx response for 64*T1 seconds without - // receiving an ACK, the dialog is confirmed, but the session SHOULD be - // terminated. This is accomplished with a BYE, as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - const stateChanged = () => { - if (transaction.state === TransactionState.Terminated) { - transaction.removeStateChangeListener(stateChanged); - if (this.invite2xxTimer) { - clearTimeout(this.invite2xxTimer); - this.invite2xxTimer = undefined; - } - if (this.reinviteUserAgentServer) { - // FIXME: TODO: What to do here - } - } - }; - transaction.addStateChangeListener(stateChanged); - } - } -} diff --git a/lib/core/dialogs/subscription-dialog.d.ts b/lib/core/dialogs/subscription-dialog.d.ts deleted file mode 100644 index 62d30aebc..000000000 --- a/lib/core/dialogs/subscription-dialog.d.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { IncomingRequestMessage, OutgoingRequestMessage, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; -import { Subscription, SubscriptionDelegate, SubscriptionState } from "../subscription"; -import { UserAgentCore } from "../user-agent-core/user-agent-core"; -import { Dialog } from "./dialog"; -import { DialogState } from "./dialog-state"; -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -export declare class SubscriptionDialog extends Dialog implements Subscription { - delegate: SubscriptionDelegate | undefined; - private _autoRefresh; - private _subscriptionEvent; - private _subscriptionExpires; - private _subscriptionExpiresInitial; - private _subscriptionExpiresLastSet; - private _subscriptionRefresh; - private _subscriptionRefreshLastSet; - private _subscriptionState; - private logger; - private N; - private refreshTimer; - constructor(subscriptionEvent: string, subscriptionExpires: number, subscriptionState: SubscriptionState, core: UserAgentCore, state: DialogState, delegate?: SubscriptionDelegate); - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForSubscription(outgoingSubscribeRequestMessage: OutgoingRequestMessage, incomingNotifyRequestMessage: IncomingRequestMessage): DialogState; - dispose(): void; - get autoRefresh(): boolean; - set autoRefresh(autoRefresh: boolean); - get subscriptionEvent(): string; - /** Number of seconds until subscription expires. */ - get subscriptionExpires(): number; - set subscriptionExpires(expires: number); - get subscriptionExpiresInitial(): number; - /** Number of seconds until subscription auto refresh. */ - get subscriptionRefresh(): number | undefined; - get subscriptionState(): SubscriptionState; - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - receiveRequest(message: IncomingRequestMessage): void; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh(): OutgoingSubscribeRequest; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - terminate(): void; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe(): OutgoingSubscribeRequest; - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - private onNotify; - private onRefresh; - private onTerminated; - private refreshTimerClear; - private refreshTimerSet; - private stateTransition; - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - private timerN; -} -//# sourceMappingURL=subscription-dialog.d.ts.map \ No newline at end of file diff --git a/lib/core/dialogs/subscription-dialog.d.ts.map b/lib/core/dialogs/subscription-dialog.d.ts.map deleted file mode 100644 index a16a5a935..000000000 --- a/lib/core/dialogs/subscription-dialog.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-dialog.d.ts","sourceRoot":"","sources":["../../../src/core/dialogs/subscription-dialog.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sBAAsB,EAEtB,sBAAsB,EACtB,wBAAwB,EACxB,gCAAgC,EAChC,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGxF,OAAO,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAGnE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,kBAAmB,SAAQ,MAAO,YAAW,YAAY;IAC7D,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAElD,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,2BAA2B,CAAS;IAC5C,OAAO,CAAC,2BAA2B,CAAS;IAC5C,OAAO,CAAC,oBAAoB,CAAqB;IACjD,OAAO,CAAC,2BAA2B,CAAqB;IACxD,OAAO,CAAC,kBAAkB,CAAoB;IAE9C,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,YAAY,CAAqB;gBAGvC,iBAAiB,EAAE,MAAM,EACzB,mBAAmB,EAAE,MAAM,EAC3B,iBAAiB,EAAE,iBAAiB,EACpC,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE,WAAW,EAClB,QAAQ,CAAC,EAAE,oBAAoB;IAgBjC;;;;;;;OAOG;WACW,iCAAiC,CAC7C,+BAA+B,EAAE,sBAAsB,EACvD,4BAA4B,EAAE,sBAAsB,GACnD,WAAW;IA+FP,OAAO,IAAI,IAAI;IAUtB,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,IAAI,WAAW,CAAC,WAAW,EAAE,OAAO,EAGnC;IAED,IAAI,iBAAiB,IAAI,MAAM,CAE9B;IAED,oDAAoD;IACpD,IAAI,mBAAmB,IAAI,MAAM,CAIhC;IAED,IAAI,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAYtC;IAED,IAAI,0BAA0B,IAAI,MAAM,CAEvC;IAED,yDAAyD;IACzD,IAAI,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAO5C;IAED,IAAI,iBAAiB,IAAI,iBAAiB,CAEzC;IAED;;;OAGG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IA0B5D;;;OAGG;IACI,OAAO,IAAI,wBAAwB;IAW1C;;;;;OAKG;IACI,SAAS,CACd,QAAQ,CAAC,EAAE,gCAAgC,EAC3C,OAAO,GAAE,cAAmB,GAC3B,wBAAwB;IAqB3B;;;;;;OAMG;IACI,SAAS,IAAI,IAAI;IAKxB;;;OAGG;IACI,WAAW,IAAI,wBAAwB;IAW9C;;;;OAIG;IACH,OAAO,CAAC,QAAQ;IAyDhB,OAAO,CAAC,SAAS;IAMjB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,eAAe;IAevB,OAAO,CAAC,eAAe;IAwFvB;;;;;;;;;;OAUG;IACH,OAAO,CAAC,MAAM;CAOf"} \ No newline at end of file diff --git a/lib/core/dialogs/subscription-dialog.js b/lib/core/dialogs/subscription-dialog.js deleted file mode 100644 index d28e4feb3..000000000 --- a/lib/core/dialogs/subscription-dialog.js +++ /dev/null @@ -1,471 +0,0 @@ -import { C, NameAddrHeader } from "../messages"; -import { SubscriptionState } from "../subscription"; -import { Timers } from "../timers"; -import { AllowedMethods } from "../user-agent-core/allowed-methods"; -import { NotifyUserAgentServer } from "../user-agents/notify-user-agent-server"; -import { ReSubscribeUserAgentClient } from "../user-agents/re-subscribe-user-agent-client"; -import { Dialog } from "./dialog"; -/** - * Subscription Dialog. - * @remarks - * SIP-Specific Event Notification - * - * Abstract - * - * This document describes an extension to the Session Initiation - * Protocol (SIP) defined by RFC 3261. The purpose of this extension is - * to provide an extensible framework by which SIP nodes can request - * notification from remote nodes indicating that certain events have - * occurred. - * - * Note that the event notification mechanisms defined herein are NOT - * intended to be a general-purpose infrastructure for all classes of - * event subscription and notification. - * - * This document represents a backwards-compatible improvement on the - * original mechanism described by RFC 3265, taking into account several - * years of implementation experience. Accordingly, this document - * obsoletes RFC 3265. This document also updates RFC 4660 slightly to - * accommodate some small changes to the mechanism that were discussed - * in that document. - * - * https://tools.ietf.org/html/rfc6665 - * @public - */ -export class SubscriptionDialog extends Dialog { - constructor(subscriptionEvent, subscriptionExpires, subscriptionState, core, state, delegate) { - super(core, state); - this.delegate = delegate; - this._autoRefresh = false; - this._subscriptionEvent = subscriptionEvent; - this._subscriptionExpires = subscriptionExpires; - this._subscriptionExpiresInitial = subscriptionExpires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - this._subscriptionRefresh = undefined; - this._subscriptionRefreshLastSet = undefined; - this._subscriptionState = subscriptionState; - this.logger = core.loggerFactory.getLogger("sip.subscribe-dialog"); - this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`); - } - /** - * When a UAC receives a response that establishes a dialog, it - * constructs the state of the dialog. This state MUST be maintained - * for the duration of the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.1.2 - * @param outgoingRequestMessage - Outgoing request message for dialog. - * @param incomingResponseMessage - Incoming response message creating dialog. - */ - static initialDialogStateForSubscription(outgoingSubscribeRequestMessage, incomingNotifyRequestMessage) { - // If the request was sent over TLS, and the Request-URI contained a - // SIPS URI, the "secure" flag is set to TRUE. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const secure = false; // FIXME: Currently no support for TLS. - // The route set MUST be set to the list of URIs in the Record-Route - // header field from the response, taken in reverse order and preserving - // all URI parameters. If no Record-Route header field is present in - // the response, the route set MUST be set to the empty set. This route - // set, even if empty, overrides any pre-existing route set for future - // requests in this dialog. The remote target MUST be set to the URI - // from the Contact header field of the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const routeSet = incomingNotifyRequestMessage.getHeaders("record-route"); - const contact = incomingNotifyRequestMessage.parseHeader("contact"); - if (!contact) { - // TODO: Review to make sure this will never happen - throw new Error("Contact undefined."); - } - if (!(contact instanceof NameAddrHeader)) { - throw new Error("Contact not instance of NameAddrHeader."); - } - const remoteTarget = contact.uri; - // The local sequence number MUST be set to the value of the sequence - // number in the CSeq header field of the request. The remote sequence - // number MUST be empty (it is established when the remote UA sends a - // request within the dialog). The call identifier component of the - // dialog ID MUST be set to the value of the Call-ID in the request. - // The local tag component of the dialog ID MUST be set to the tag in - // the From field in the request, and the remote tag component of the - // dialog ID MUST be set to the tag in the To field of the response. A - // UAC MUST be prepared to receive a response without a tag in the To - // field, in which case the tag is considered to have a value of null. - // - // This is to maintain backwards compatibility with RFC 2543, which - // did not mandate To tags. - // - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - const localSequenceNumber = outgoingSubscribeRequestMessage.cseq; - const remoteSequenceNumber = undefined; - const callId = outgoingSubscribeRequestMessage.callId; - const localTag = outgoingSubscribeRequestMessage.fromTag; - const remoteTag = incomingNotifyRequestMessage.fromTag; - if (!callId) { - // TODO: Review to make sure this will never happen - throw new Error("Call id undefined."); - } - if (!localTag) { - // TODO: Review to make sure this will never happen - throw new Error("From tag undefined."); - } - if (!remoteTag) { - // TODO: Review to make sure this will never happen - throw new Error("To tag undefined."); // FIXME: No backwards compatibility with RFC 2543 - } - // The remote URI MUST be set to the URI in the To field, and the local - // URI MUST be set to the URI in the From field. - // https://tools.ietf.org/html/rfc3261#section-12.1.2 - if (!outgoingSubscribeRequestMessage.from) { - // TODO: Review to make sure this will never happen - throw new Error("From undefined."); - } - if (!outgoingSubscribeRequestMessage.to) { - // TODO: Review to make sure this will never happen - throw new Error("To undefined."); - } - const localURI = outgoingSubscribeRequestMessage.from.uri; - const remoteURI = outgoingSubscribeRequestMessage.to.uri; - // A dialog can also be in the "early" state, which occurs when it is - // created with a provisional response, and then transition to the - // "confirmed" state when a 2xx final response arrives. - // https://tools.ietf.org/html/rfc3261#section-12 - const early = false; - const dialogState = { - id: callId + localTag + remoteTag, - early, - callId, - localTag, - remoteTag, - localSequenceNumber, - remoteSequenceNumber, - localURI, - remoteURI, - remoteTarget, - routeSet, - secure - }; - return dialogState; - } - dispose() { - super.dispose(); - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - this.refreshTimerClear(); - this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`); - } - get autoRefresh() { - return this._autoRefresh; - } - set autoRefresh(autoRefresh) { - this._autoRefresh = true; - this.refreshTimerSet(); - } - get subscriptionEvent() { - return this._subscriptionEvent; - } - /** Number of seconds until subscription expires. */ - get subscriptionExpires() { - const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionExpiresLastSet; - const secondsUntilExpires = this._subscriptionExpires - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - } - set subscriptionExpires(expires) { - if (expires < 0) { - throw new Error("Expires must be greater than or equal to zero."); - } - this._subscriptionExpires = expires; - this._subscriptionExpiresLastSet = Math.floor(Date.now() / 1000); - if (this.autoRefresh) { - const refresh = this.subscriptionRefresh; - if (refresh === undefined || refresh >= expires) { - this.refreshTimerSet(); - } - } - } - get subscriptionExpiresInitial() { - return this._subscriptionExpiresInitial; - } - /** Number of seconds until subscription auto refresh. */ - get subscriptionRefresh() { - if (this._subscriptionRefresh === undefined || this._subscriptionRefreshLastSet === undefined) { - return undefined; - } - const secondsSinceLastSet = Math.floor(Date.now() / 1000) - this._subscriptionRefreshLastSet; - const secondsUntilExpires = this._subscriptionRefresh - secondsSinceLastSet; - return Math.max(secondsUntilExpires, 0); - } - get subscriptionState() { - return this._subscriptionState; - } - /** - * Receive in dialog request message from transport. - * @param message - The incoming request message. - */ - receiveRequest(message) { - this.logger.log(`SUBSCRIBE dialog ${this.id} received ${message.method} request`); - // Request within a dialog out of sequence guard. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (!this.sequenceGuard(message)) { - this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${message.method} request.`); - return; - } - // Request within a dialog common processing. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - super.receiveRequest(message); - // Switch on method and then delegate. - switch (message.method) { - case C.NOTIFY: - this.onNotify(message); - break; - default: - this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${message.method} request`); - this.core.replyStateless(message, { statusCode: 501 }); - break; - } - } - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh() { - const allowHeader = "Allow: " + AllowedMethods.toString(); - const options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: " + this.subscriptionExpiresInitial); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - } - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Delegate to handle responses. - * @param options - Options bucket. - */ - subscribe(delegate, options = {}) { - if (this.subscriptionState !== SubscriptionState.Pending && this.subscriptionState !== SubscriptionState.Active) { - // FIXME: This needs to be a proper exception - throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`); - } - this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`); - const uac = new ReSubscribeUserAgentClient(this, delegate, options); - // Abort any outstanding timer (as it would otherwise become guaranteed to terminate us). - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // When refreshing a subscription, a subscriber starts Timer N, set to - // 64*T1, when it sends the SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - this.N = setTimeout(() => this.timerN(), Timers.TIMER_N); - return uac; - } - /** - * 4.4.1. Dialog Creation and Termination - * A subscription is destroyed after a notifier sends a NOTIFY request - * with a "Subscription-State" of "terminated", or in certain error - * situations described elsewhere in this document. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - terminate() { - this.stateTransition(SubscriptionState.Terminated); - this.onTerminated(); - } - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe() { - const allowHeader = "Allow: " + AllowedMethods.toString(); - const options = {}; - options.extraHeaders = (options.extraHeaders || []).slice(); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push("Event: " + this.subscriptionEvent); - options.extraHeaders.push("Expires: 0"); - options.extraHeaders.push("Contact: " + this.core.configuration.contact.toString()); - return this.subscribe(undefined, options); - } - /** - * Handle in dialog NOTIFY requests. - * This does not include the first NOTIFY which created the dialog. - * @param message - The incoming NOTIFY request message. - */ - onNotify(message) { - // If, for some reason, the event package designated in the "Event" - // header field of the NOTIFY request is not supported, the subscriber - // will respond with a 489 (Bad Event) response. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const event = message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - // In the state diagram, "Re-subscription times out" means that an - // attempt to refresh or update the subscription using a new SUBSCRIBE - // request does not result in a NOTIFY request before the corresponding - // Timer N expires. - // https://tools.ietf.org/html/rfc6665#section-4.1.2 - if (this.N) { - clearTimeout(this.N); - this.N = undefined; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.core.replyStateless(message, { statusCode: 489 }); - return; - } - const state = subscriptionState.state; - const expires = subscriptionState.expires ? Math.max(subscriptionState.expires, 0) : undefined; - // Update our state and expiration. - switch (state) { - case "pending": - this.stateTransition(SubscriptionState.Pending, expires); - break; - case "active": - this.stateTransition(SubscriptionState.Active, expires); - break; - case "terminated": - this.stateTransition(SubscriptionState.Terminated, expires); - break; - default: - this.logger.warn("Unrecognized subscription state."); - break; - } - // Delegate remainder of NOTIFY handling. - const uas = new NotifyUserAgentServer(this, message); - if (this.delegate && this.delegate.onNotify) { - this.delegate.onNotify(uas); - } - else { - uas.accept(); - } - } - onRefresh(request) { - if (this.delegate && this.delegate.onRefresh) { - this.delegate.onRefresh(request); - } - } - onTerminated() { - if (this.delegate && this.delegate.onTerminated) { - this.delegate.onTerminated(); - } - } - refreshTimerClear() { - if (this.refreshTimer) { - clearTimeout(this.refreshTimer); - this.refreshTimer = undefined; - } - } - refreshTimerSet() { - this.refreshTimerClear(); - if (this.autoRefresh && this.subscriptionExpires > 0) { - const refresh = this.subscriptionExpires * 900; - this._subscriptionRefresh = Math.floor(refresh / 1000); - this._subscriptionRefreshLastSet = Math.floor(Date.now() / 1000); - this.refreshTimer = setTimeout(() => { - this.refreshTimer = undefined; - this._subscriptionRefresh = undefined; - this._subscriptionRefreshLastSet = undefined; - this.onRefresh(this.refresh()); - }, refresh); - } - } - stateTransition(newState, newExpires) { - // Assert valid state transitions. - const invalidStateTransition = () => { - this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${newState}`); - }; - switch (newState) { - case SubscriptionState.Initial: - invalidStateTransition(); - return; - case SubscriptionState.NotifyWait: - invalidStateTransition(); - return; - case SubscriptionState.Pending: - if (this.subscriptionState !== SubscriptionState.NotifyWait && - this.subscriptionState !== SubscriptionState.Pending) { - invalidStateTransition(); - return; - } - break; - case SubscriptionState.Active: - if (this.subscriptionState !== SubscriptionState.NotifyWait && - this.subscriptionState !== SubscriptionState.Pending && - this.subscriptionState !== SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - case SubscriptionState.Terminated: - if (this.subscriptionState !== SubscriptionState.NotifyWait && - this.subscriptionState !== SubscriptionState.Pending && - this.subscriptionState !== SubscriptionState.Active) { - invalidStateTransition(); - return; - } - break; - default: - invalidStateTransition(); - return; - } - // If the "Subscription-State" value is "pending", the subscription has - // been received by the notifier, but there is insufficient policy - // information to grant or deny the subscription yet. If the header - // field also contains an "expires" parameter, the subscriber SHOULD - // take it as the authoritative subscription duration and adjust - // accordingly. No further action is necessary on the part of the - // subscriber. The "retry-after" and "reason" parameters have no - // semantics for "pending". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === SubscriptionState.Pending) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" header field value is "active", it means - // that the subscription has been accepted and (in general) has been - // authorized. If the header field also contains an "expires" - // parameter, the subscriber SHOULD take it as the authoritative - // subscription duration and adjust accordingly. The "retry-after" and - // "reason" parameters have no semantics for "active". - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - if (newState === SubscriptionState.Active) { - if (newExpires) { - this.subscriptionExpires = newExpires; - } - } - // If the "Subscription-State" value is "terminated", the subscriber - // MUST consider the subscription terminated. The "expires" parameter - // has no semantics for "terminated" -- notifiers SHOULD NOT include an - // "expires" parameter on a "Subscription-State" header field with a - // value of "terminated", and subscribers MUST ignore any such - // parameter, if present. - if (newState === SubscriptionState.Terminated) { - this.dispose(); - } - this._subscriptionState = newState; - } - /** - * When refreshing a subscription, a subscriber starts Timer N, set to - * 64*T1, when it sends the SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription terminated. If the subscriber receives a success - * response to the SUBSCRIBE request that indicates that no NOTIFY - * request will be generated -- such as the 204 response defined for use - * with the optional extension described in [RFC5839] -- then it MUST - * cancel Timer N. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - timerN() { - this.logger.warn(`Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY.`); - if (this.subscriptionState !== SubscriptionState.Terminated) { - this.stateTransition(SubscriptionState.Terminated); - this.onTerminated(); - } - } -} diff --git a/lib/core/exceptions/exception.d.ts b/lib/core/exceptions/exception.d.ts deleted file mode 100644 index 476b4fad0..000000000 --- a/lib/core/exceptions/exception.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -export declare abstract class Exception extends Error { - protected constructor(message?: string); -} -//# sourceMappingURL=exception.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/exception.d.ts.map b/lib/core/exceptions/exception.d.ts.map deleted file mode 100644 index d9b0b27c2..000000000 --- a/lib/core/exceptions/exception.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"exception.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/exception.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,8BAAsB,SAAU,SAAQ,KAAK;IAC3C,SAAS,aAAa,OAAO,CAAC,EAAE,MAAM;CAIvC"} \ No newline at end of file diff --git a/lib/core/exceptions/exception.js b/lib/core/exceptions/exception.js deleted file mode 100644 index f1fb9b899..000000000 --- a/lib/core/exceptions/exception.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * An Exception is considered a condition that a reasonable application may wish to catch. - * An Error indicates serious problems that a reasonable application should not try to catch. - * @public - */ -export class Exception extends Error { - constructor(message) { - super(message); // 'Error' breaks prototype chain here - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain - } -} diff --git a/lib/core/exceptions/index.d.ts b/lib/core/exceptions/index.d.ts deleted file mode 100644 index fad2dd3c9..000000000 --- a/lib/core/exceptions/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./exception"; -export * from "./transaction-state-error"; -export * from "./transport-error"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/index.d.ts.map b/lib/core/exceptions/index.d.ts.map deleted file mode 100644 index cb6188c01..000000000 --- a/lib/core/exceptions/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"} \ No newline at end of file diff --git a/lib/core/exceptions/index.js b/lib/core/exceptions/index.js deleted file mode 100644 index a7b5eb621..000000000 --- a/lib/core/exceptions/index.js +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./exception"; -export * from "./transaction-state-error"; -export * from "./transport-error"; diff --git a/lib/core/exceptions/transaction-state-error.d.ts b/lib/core/exceptions/transaction-state-error.d.ts deleted file mode 100644 index efac75de6..000000000 --- a/lib/core/exceptions/transaction-state-error.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "./exception"; -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -export declare class TransactionStateError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=transaction-state-error.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/transaction-state-error.d.ts.map b/lib/core/exceptions/transaction-state-error.d.ts.map deleted file mode 100644 index a9ee2adab..000000000 --- a/lib/core/exceptions/transaction-state-error.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction-state-error.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/transaction-state-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,SAAS;gBACtC,OAAO,CAAC,EAAE,MAAM;CAG7B"} \ No newline at end of file diff --git a/lib/core/exceptions/transaction-state-error.js b/lib/core/exceptions/transaction-state-error.js deleted file mode 100644 index 60c5493f0..000000000 --- a/lib/core/exceptions/transaction-state-error.js +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "./exception"; -/** - * Indicates that the operation could not be completed given the current transaction state. - * @public - */ -export class TransactionStateError extends Exception { - constructor(message) { - super(message ? message : "Transaction state error."); - } -} diff --git a/lib/core/exceptions/transport-error.d.ts b/lib/core/exceptions/transport-error.d.ts deleted file mode 100644 index 29db45f93..000000000 --- a/lib/core/exceptions/transport-error.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Exception } from "./exception"; -/** - * Transport error. - * @public - */ -export declare class TransportError extends Exception { - constructor(message?: string); -} -//# sourceMappingURL=transport-error.d.ts.map \ No newline at end of file diff --git a/lib/core/exceptions/transport-error.d.ts.map b/lib/core/exceptions/transport-error.d.ts.map deleted file mode 100644 index 7f7e3f494..000000000 --- a/lib/core/exceptions/transport-error.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport-error.d.ts","sourceRoot":"","sources":["../../../src/core/exceptions/transport-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,qBAAa,cAAe,SAAQ,SAAS;gBAC/B,OAAO,CAAC,EAAE,MAAM;CAG7B"} \ No newline at end of file diff --git a/lib/core/exceptions/transport-error.js b/lib/core/exceptions/transport-error.js deleted file mode 100644 index e5fb84d6c..000000000 --- a/lib/core/exceptions/transport-error.js +++ /dev/null @@ -1,10 +0,0 @@ -import { Exception } from "./exception"; -/** - * Transport error. - * @public - */ -export class TransportError extends Exception { - constructor(message) { - super(message ? message : "Unspecified transport error."); - } -} diff --git a/lib/core/index.d.ts b/lib/core/index.d.ts deleted file mode 100644 index aeaad6230..000000000 --- a/lib/core/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -export * from "./dialogs"; -export * from "./exceptions"; -export * from "./log"; -export * from "./messages"; -export * from "./session"; -export * from "./subscription"; -export * from "./transactions"; -export * from "./user-agent-core"; -export * from "./user-agents"; -export * from "./timers"; -export * from "./transport"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/index.d.ts.map b/lib/core/index.d.ts.map deleted file mode 100644 index d5d7687f4..000000000 --- a/lib/core/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,cAAc,WAAW,CAAC;AAC1B,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAG9B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/core/index.js b/lib/core/index.js deleted file mode 100644 index 7df7074f8..000000000 --- a/lib/core/index.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * A core library implementing low level SIP protocol elements. - * @packageDocumentation - */ -// Directories -export * from "./dialogs"; -export * from "./exceptions"; -export * from "./log"; -export * from "./messages"; -export * from "./session"; -export * from "./subscription"; -export * from "./transactions"; -export * from "./user-agent-core"; -export * from "./user-agents"; -// Files -export * from "./timers"; -export * from "./transport"; diff --git a/lib/core/log/index.d.ts b/lib/core/log/index.d.ts deleted file mode 100644 index 011860395..000000000 --- a/lib/core/log/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./levels"; -export * from "./logger-factory"; -export * from "./logger"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/log/index.d.ts.map b/lib/core/log/index.d.ts.map deleted file mode 100644 index b9ae7b73a..000000000 --- a/lib/core/log/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/log/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/lib/core/log/index.js b/lib/core/log/index.js deleted file mode 100644 index 2d59354ff..000000000 --- a/lib/core/log/index.js +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./levels"; -export * from "./logger-factory"; -export * from "./logger"; diff --git a/lib/core/log/levels.d.ts b/lib/core/log/levels.d.ts deleted file mode 100644 index 49a9b7296..000000000 --- a/lib/core/log/levels.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Log levels. - * @public - */ -export declare enum Levels { - error = 0, - warn = 1, - log = 2, - debug = 3 -} -//# sourceMappingURL=levels.d.ts.map \ No newline at end of file diff --git a/lib/core/log/levels.d.ts.map b/lib/core/log/levels.d.ts.map deleted file mode 100644 index 494d285b6..000000000 --- a/lib/core/log/levels.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"levels.d.ts","sourceRoot":"","sources":["../../../src/core/log/levels.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,MAAM;IAChB,KAAK,IAAA;IACL,IAAI,IAAA;IACJ,GAAG,IAAA;IACH,KAAK,IAAA;CACN"} \ No newline at end of file diff --git a/lib/core/log/levels.js b/lib/core/log/levels.js deleted file mode 100644 index ec90080e5..000000000 --- a/lib/core/log/levels.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Log levels. - * @public - */ -export var Levels; -(function (Levels) { - Levels[Levels["error"] = 0] = "error"; - Levels[Levels["warn"] = 1] = "warn"; - Levels[Levels["log"] = 2] = "log"; - Levels[Levels["debug"] = 3] = "debug"; -})(Levels || (Levels = {})); diff --git a/lib/core/log/logger-factory.d.ts b/lib/core/log/logger-factory.d.ts deleted file mode 100644 index 667eb99bf..000000000 --- a/lib/core/log/logger-factory.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Levels } from "./levels"; -import { Logger } from "./logger"; -/** - * Logger. - * @public - */ -export declare class LoggerFactory { - builtinEnabled: boolean; - private _level; - private _connector; - private loggers; - private logger; - constructor(); - get level(): Levels; - set level(newLevel: Levels); - get connector(): ((level: string, category: string, label: string | undefined, content: any) => void) | undefined; - set connector(value: ((level: string, category: string, label: string | undefined, content: any) => void) | undefined); - getLogger(category: string, label?: string): Logger; - genericLog(levelToLog: Levels, category: string, label: string | undefined, content: any): void; - private print; -} -//# sourceMappingURL=logger-factory.d.ts.map \ No newline at end of file diff --git a/lib/core/log/logger-factory.d.ts.map b/lib/core/log/logger-factory.d.ts.map deleted file mode 100644 index 48072ee40..000000000 --- a/lib/core/log/logger-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"logger-factory.d.ts","sourceRoot":"","sources":["../../../src/core/log/logger-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC;;;GAGG;AACH,qBAAa,aAAa;IACjB,cAAc,UAAQ;IAE7B,OAAO,CAAC,MAAM,CAAsB;IAEpC,OAAO,CAAC,UAAU,CAAmG;IAGrH,OAAO,CAAC,OAAO,CAAW;IAC1B,OAAO,CAAC,MAAM,CAAS;;IAMvB,IAAI,KAAK,IAAI,MAAM,CAElB;IACD,IAAI,KAAK,CAAC,QAAQ,EAAE,MAAM,EAWzB;IAGD,IAAI,SAAS,IAAI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC,GAAG,SAAS,CAEhH;IACD,IAAI,SAAS,CACX,KAAK,EACD,CAAC,CACC,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,SAAS,EAEzB,OAAO,EAAE,GAAG,KACT,IAAI,CAAC,GACV,SAAS,EASd;IAEM,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;IAanD,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,GAAG,GAAG,IAAI;IAatG,OAAO,CAAC,KAAK;CA8Bd"} \ No newline at end of file diff --git a/lib/core/log/logger-factory.js b/lib/core/log/logger-factory.js deleted file mode 100644 index 81d5034a3..000000000 --- a/lib/core/log/logger-factory.js +++ /dev/null @@ -1,103 +0,0 @@ -import { Levels } from "./levels"; -import { Logger } from "./logger"; -/** - * Logger. - * @public - */ -export class LoggerFactory { - constructor() { - this.builtinEnabled = true; - this._level = Levels.log; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.loggers = {}; - this.logger = this.getLogger("sip:loggerfactory"); - } - get level() { - return this._level; - } - set level(newLevel) { - if (newLevel >= 0 && newLevel <= 3) { - this._level = newLevel; - } - else if (newLevel > 3) { - this._level = 3; - // eslint-disable-next-line no-prototype-builtins - } - else if (Levels.hasOwnProperty(newLevel)) { - this._level = newLevel; - } - else { - this.logger.error("invalid 'level' parameter value: " + JSON.stringify(newLevel)); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get connector() { - return this._connector; - } - set connector(value) { - if (!value) { - this._connector = undefined; - } - else if (typeof value === "function") { - this._connector = value; - } - else { - this.logger.error("invalid 'connector' parameter value: " + JSON.stringify(value)); - } - } - getLogger(category, label) { - if (label && this.level === 3) { - return new Logger(this, category, label); - } - else if (this.loggers[category]) { - return this.loggers[category]; - } - else { - const logger = new Logger(this, category); - this.loggers[category] = logger; - return logger; - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - genericLog(levelToLog, category, label, content) { - if (this.level >= levelToLog) { - if (this.builtinEnabled) { - this.print(levelToLog, category, label, content); - } - } - if (this.connector) { - this.connector(Levels[levelToLog], category, label, content); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - print(levelToLog, category, label, content) { - if (typeof content === "string") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const prefix = [new Date(), category]; - if (label) { - prefix.push(label); - } - content = prefix.concat(content).join(" | "); - } - switch (levelToLog) { - case Levels.error: - // eslint-disable-next-line no-console - console.error(content); - break; - case Levels.warn: - // eslint-disable-next-line no-console - console.warn(content); - break; - case Levels.log: - // eslint-disable-next-line no-console - console.log(content); - break; - case Levels.debug: - // eslint-disable-next-line no-console - console.debug(content); - break; - default: - break; - } - } -} diff --git a/lib/core/log/logger.d.ts b/lib/core/log/logger.d.ts deleted file mode 100644 index b48b629cc..000000000 --- a/lib/core/log/logger.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { LoggerFactory } from "./logger-factory"; -/** - * Logger. - * @public - */ -export declare class Logger { - private logger; - private category; - private label; - constructor(logger: LoggerFactory, category: string, label?: string); - error(content: string): void; - warn(content: string): void; - log(content: string): void; - debug(content: string): void; - private genericLog; -} -//# sourceMappingURL=logger.d.ts.map \ No newline at end of file diff --git a/lib/core/log/logger.d.ts.map b/lib/core/log/logger.d.ts.map deleted file mode 100644 index d2d2d47ef..000000000 --- a/lib/core/log/logger.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../../src/core/log/logger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD;;;GAGG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,KAAK,CAAqB;gBAEtB,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM;IAM5D,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAG5B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAG3B,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAG1B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAInC,OAAO,CAAC,UAAU;CAGnB"} \ No newline at end of file diff --git a/lib/core/log/logger.js b/lib/core/log/logger.js deleted file mode 100644 index 90b24b86c..000000000 --- a/lib/core/log/logger.js +++ /dev/null @@ -1,27 +0,0 @@ -import { Levels } from "./levels"; -/** - * Logger. - * @public - */ -export class Logger { - constructor(logger, category, label) { - this.logger = logger; - this.category = category; - this.label = label; - } - error(content) { - this.genericLog(Levels.error, content); - } - warn(content) { - this.genericLog(Levels.warn, content); - } - log(content) { - this.genericLog(Levels.log, content); - } - debug(content) { - this.genericLog(Levels.debug, content); - } - genericLog(level, content) { - this.logger.genericLog(level, this.category, this.label, content); - } -} diff --git a/lib/core/messages/body.d.ts b/lib/core/messages/body.d.ts deleted file mode 100644 index 3bf8c6c33..000000000 --- a/lib/core/messages/body.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { IncomingRequestMessage } from "./incoming-request-message"; -import { IncomingResponseMessage } from "./incoming-response-message"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -/** - * Message body. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-7.4 - * @public - */ -export interface Body { - /** - * If the Content-Disposition header field is missing, bodies of - * Content-Type application/sdp imply the disposition "session", while - * other content types imply "render". - * https://tools.ietf.org/html/rfc3261#section-13.2.1 - * For backward-compatibility, if the Content-Disposition header field - * is missing, the server SHOULD assume bodies of Content-Type - * application/sdp are the disposition "session", while other content - * types are "render". - * https://tools.ietf.org/html/rfc3261#section-20.11 - */ - contentDisposition: string; - /** - * The Content-Type header field indicates the media type of the - * message-body sent to the recipient. The Content-Type header field - * MUST be present if the body is not empty. If the body is empty, - * and a Content-Type header field is present, it indicates that the body - * of the specific type has zero length (for example, an empty audio file). - * https://tools.ietf.org/html/rfc3261#section-20.15 - */ - contentType: string; - /** - * Requests, including new requests defined in extensions to this - * specification, MAY contain message bodies unless otherwise noted. - * The interpretation of the body depends on the request method. - * For response messages, the request method and the response status - * code determine the type and interpretation of any message body. All - * responses MAY include a body. - * https://tools.ietf.org/html/rfc3261#section-7.4 - */ - content: string; -} -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -export declare function fromBodyLegacy(bodyLegacy: string | { - body: string; - contentType: string; -}): Body; -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -export declare function isBody(body: any): body is Body; -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -export declare function getBody(message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | Body): Body | undefined; -//# sourceMappingURL=body.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/body.d.ts.map b/lib/core/messages/body.d.ts.map deleted file mode 100644 index 146bf548e..000000000 --- a/lib/core/messages/body.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../../../src/core/messages/body.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAcpE;;;;;GAKG;AACH,MAAM,WAAW,IAAI;IACnB;;;;;;;;;;OAUG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;;;;;;OAOG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;;;;;;OAQG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAM/F;AAED;;;;GAIG;AAEH,wBAAgB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,IAAI,CAO9C;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CACrB,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,GAAG,sBAAsB,GAAG,IAAI,GACxF,IAAI,GAAG,SAAS,CA4ElB"} \ No newline at end of file diff --git a/lib/core/messages/body.js b/lib/core/messages/body.js deleted file mode 100644 index ae97e762c..000000000 --- a/lib/core/messages/body.js +++ /dev/null @@ -1,118 +0,0 @@ -import { IncomingRequestMessage } from "./incoming-request-message"; -import { IncomingResponseMessage } from "./incoming-response-message"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -// If the Content-Disposition header field is missing, bodies of -// Content-Type application/sdp imply the disposition "session", while -// other content types imply "render". -// https://tools.ietf.org/html/rfc3261#section-13.2.1 -function contentTypeToContentDisposition(contentType) { - if (contentType === "application/sdp") { - return "session"; - } - else { - return "render"; - } -} -/** - * Create a Body given a legacy body type. - * @param bodyLegacy - Body Object - * @internal - */ -export function fromBodyLegacy(bodyLegacy) { - const content = typeof bodyLegacy === "string" ? bodyLegacy : bodyLegacy.body; - const contentType = typeof bodyLegacy === "string" ? "application/sdp" : bodyLegacy.contentType; - const contentDisposition = contentTypeToContentDisposition(contentType); - const body = { contentDisposition, contentType, content }; - return body; -} -/** - * User-Defined Type Guard for Body. - * @param body - Body to check. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export function isBody(body) { - return body && - typeof body.content === "string" && - typeof body.contentType === "string" && - body.contentDisposition === undefined - ? true - : typeof body.contentDisposition === "string"; -} -/** - * Given a message, get a normalized body. - * The content disposition is inferred if not set. - * @param message - The message. - * @internal - */ -export function getBody(message) { - let contentDisposition; - let contentType; - let content; - // We're in UAS role, receiving incoming request - if (message instanceof IncomingRequestMessage) { - if (message.body) { - // FIXME: Parsing needs typing - const parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, receiving incoming response - if (message instanceof IncomingResponseMessage) { - if (message.body) { - // FIXME: Parsing needs typing - const parse = message.parseHeader("Content-Disposition"); - contentDisposition = parse ? parse.type : undefined; - contentType = message.parseHeader("Content-Type"); - content = message.body; - } - } - // We're in UAC role, sending outgoing request - if (message instanceof OutgoingRequestMessage) { - if (message.body) { - contentDisposition = message.getHeader("Content-Disposition"); - contentType = message.getHeader("Content-Type"); - if (typeof message.body === "string") { - // FIXME: OutgoingRequest should not allow a "string" body without a "Content-Type" header. - if (!contentType) { - throw new Error("Header content type header does not equal body content type."); - } - content = message.body; - } - else { - // FIXME: OutgoingRequest should not allow the "Content-Type" header not to match th body content type - if (contentType && contentType !== message.body.contentType) { - throw new Error("Header content type header does not equal body content type."); - } - contentType = message.body.contentType; - content = message.body.body; - } - } - } - // We're in UAS role, sending outgoing response - if (isBody(message)) { - contentDisposition = message.contentDisposition; - contentType = message.contentType; - content = message.content; - } - // No content, no body. - if (!content) { - return undefined; - } - if (contentType && !contentDisposition) { - contentDisposition = contentTypeToContentDisposition(contentType); - } - if (!contentDisposition) { - throw new Error("Content disposition undefined."); - } - if (!contentType) { - throw new Error("Content type undefined."); - } - return { - contentDisposition, - contentType, - content - }; -} diff --git a/lib/core/messages/digest-authentication.d.ts b/lib/core/messages/digest-authentication.d.ts deleted file mode 100644 index 39a6755d7..000000000 --- a/lib/core/messages/digest-authentication.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { LoggerFactory } from "../log"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -/** - * Digest Authentication. - * @internal - */ -export declare class DigestAuthentication { - stale: boolean | undefined; - private logger; - private ha1; - private username; - private password; - private cnonce; - private nc; - private ncHex; - private response; - private algorithm; - private realm; - private nonce; - private opaque; - private qop; - private method; - private uri; - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - constructor(loggerFactory: LoggerFactory, ha1: string | undefined, username: string | undefined, password: string | undefined); - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - authenticate(request: OutgoingRequestMessage, challenge: any, body?: string): boolean; - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - toString(): string; - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - private updateNcHex; - /** - * Generate Digest 'response' value. - */ - private calculateResponse; -} -//# sourceMappingURL=digest-authentication.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/digest-authentication.d.ts.map b/lib/core/messages/digest-authentication.d.ts.map deleted file mode 100644 index 02e471095..000000000 --- a/lib/core/messages/digest-authentication.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"digest-authentication.d.ts","sourceRoot":"","sources":["../../../src/core/messages/digest-authentication.ts"],"names":[],"mappings":"AAGA,OAAO,EAAU,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAOpE;;;GAGG;AACH,qBAAa,oBAAoB;IACxB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;IAElC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,GAAG,CAAqB;IAChC,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,GAAG,CAAqB;IAChC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,GAAG,CAA2B;IAEtC;;;;;OAKG;gBAED,aAAa,EAAE,aAAa,EAC5B,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,QAAQ,EAAE,MAAM,GAAG,SAAS;IAU9B;;;;;;OAMG;IAEI,YAAY,CAAC,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO;IA+D5F;;OAEG;IACI,QAAQ,IAAI,MAAM;IAwBzB;;OAEG;IACH,OAAO,CAAC,WAAW;IAKnB;;OAEG;IACH,OAAO,CAAC,iBAAiB;CA0B1B"} \ No newline at end of file diff --git a/lib/core/messages/digest-authentication.js b/lib/core/messages/digest-authentication.js deleted file mode 100644 index b40b36cee..000000000 --- a/lib/core/messages/digest-authentication.js +++ /dev/null @@ -1,149 +0,0 @@ -import { Md5 } from "./md5"; -import { createRandomToken } from "./utils"; -function MD5(s) { - return Md5.hashStr(s); -} -/** - * Digest Authentication. - * @internal - */ -export class DigestAuthentication { - /** - * Constructor. - * @param loggerFactory - LoggerFactory. - * @param username - Username. - * @param password - Password. - */ - constructor(loggerFactory, ha1, username, password) { - this.logger = loggerFactory.getLogger("sipjs.digestauthentication"); - this.username = username; - this.password = password; - this.ha1 = ha1; - this.nc = 0; - this.ncHex = "00000000"; - } - /** - * Performs Digest authentication given a SIP request and the challenge - * received in a response to that request. - * @param request - - * @param challenge - - * @returns true if credentials were successfully generated, false otherwise. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - authenticate(request, challenge, body) { - // Inspect and validate the challenge. - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - if (this.algorithm) { - if (this.algorithm !== "MD5") { - this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"); - return false; - } - } - else { - this.algorithm = "MD5"; - } - if (!this.realm) { - this.logger.warn("challenge without Digest realm, authentication aborted"); - return false; - } - if (!this.nonce) { - this.logger.warn("challenge without Digest nonce, authentication aborted"); - return false; - } - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf("auth") > -1) { - this.qop = "auth"; - } - else if (challenge.qop.indexOf("auth-int") > -1) { - this.qop = "auth-int"; - } - else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"); - return false; - } - } - else { - this.qop = undefined; - } - // Fill other attributes. - this.method = request.method; - this.uri = request.ruri; - this.cnonce = createRandomToken(12); - this.nc += 1; - this.updateNcHex(); - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = "00000001"; - } - // Calculate the Digest "response" value. - this.calculateResponse(body); - return true; - } - /** - * Return the Proxy-Authorization or WWW-Authorization header value. - */ - toString() { - const authParams = []; - if (!this.response) { - throw new Error("response field does not exist, cannot generate Authorization header"); - } - authParams.push("algorithm=" + this.algorithm); - authParams.push('username="' + this.username + '"'); - authParams.push('realm="' + this.realm + '"'); - authParams.push('nonce="' + this.nonce + '"'); - authParams.push('uri="' + this.uri + '"'); - authParams.push('response="' + this.response + '"'); - if (this.opaque) { - authParams.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - authParams.push("qop=" + this.qop); - authParams.push('cnonce="' + this.cnonce + '"'); - authParams.push("nc=" + this.ncHex); - } - return "Digest " + authParams.join(", "); - } - /** - * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. - */ - updateNcHex() { - const hex = Number(this.nc).toString(16); - this.ncHex = "00000000".substr(0, 8 - hex.length) + hex; - } - /** - * Generate Digest 'response' value. - */ - calculateResponse(body) { - let ha1, ha2; - // HA1 = MD5(A1) = MD5(username:realm:password) - ha1 = this.ha1; - if (ha1 === "" || ha1 === undefined) { - ha1 = MD5(this.username + ":" + this.realm + ":" + this.password); - } - if (this.qop === "auth") { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = MD5(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)` - this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth:" + ha2); - } - else if (this.qop === "auth-int") { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = MD5(this.method + ":" + this.uri + ":" + MD5(body ? body : "")); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = MD5(ha1 + ":" + this.nonce + ":" + this.ncHex + ":" + this.cnonce + ":auth-int:" + ha2); - } - else if (this.qop === undefined) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = MD5(this.method + ":" + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = MD5(ha1 + ":" + this.nonce + ":" + ha2); - } - } -} diff --git a/lib/core/messages/incoming-message.d.ts b/lib/core/messages/incoming-message.d.ts deleted file mode 100644 index 196d2f2f3..000000000 --- a/lib/core/messages/incoming-message.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { NameAddrHeader } from "../../grammar"; -/** - * Incoming message. - * @public - */ -export declare class IncomingMessage { - viaBranch: string; - method: string; - body: string; - toTag: string; - to: NameAddrHeader; - fromTag: string; - from: NameAddrHeader; - callId: string; - cseq: number; - via: { - host: string; - port: number; - }; - headers: { - [name: string]: Array<{ - parsed?: any; - raw: string; - }>; - }; - referTo: string | undefined; - data: string; - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - addHeader(name: string, value: string): void; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name: string): string | undefined; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - getHeaders(name: string): Array; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name: string): boolean; - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - parseHeader(name: string, idx?: number): any | undefined; - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - s(name: string, idx?: number): any | undefined; - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - setHeader(name: string, value: string): void; - toString(): string; -} -//# sourceMappingURL=incoming-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-message.d.ts.map b/lib/core/messages/incoming-message.d.ts.map deleted file mode 100644 index 7dbd82dd7..000000000 --- a/lib/core/messages/incoming-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,cAAc,EAAE,MAAM,eAAe,CAAC;AAGxD;;;GAGG;AACH,qBAAa,eAAe;IACnB,SAAS,EAAG,MAAM,CAAC;IACnB,MAAM,EAAG,MAAM,CAAC;IAChB,IAAI,EAAG,MAAM,CAAC;IACd,KAAK,EAAG,MAAM,CAAC;IACf,EAAE,EAAG,cAAc,CAAC;IACpB,OAAO,EAAG,MAAM,CAAC;IACjB,IAAI,EAAG,cAAc,CAAC;IACtB,MAAM,EAAG,MAAM,CAAC;IAChB,IAAI,EAAG,MAAM,CAAC;IACd,GAAG,EAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAErC,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC;YAAE,MAAM,CAAC,EAAE,GAAG,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAE,CAAM;IACvE,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,IAAI,EAAG,MAAM,CAAC;IAErB;;;;;OAKG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAWnD;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAYlD;;;;OAIG;IACI,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAc9C;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIvC;;;;;;OAMG;IAEI,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAI,GAAG,GAAG,GAAG,SAAS;IA+B1D;;;;;;;;;OASG;IAEI,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAI,GAAG,GAAG,GAAG,SAAS;IAIhD;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAI5C,QAAQ,IAAI,MAAM;CAG1B"} \ No newline at end of file diff --git a/lib/core/messages/incoming-message.js b/lib/core/messages/incoming-message.js deleted file mode 100644 index eb9023b3c..000000000 --- a/lib/core/messages/incoming-message.js +++ /dev/null @@ -1,129 +0,0 @@ -import { Grammar } from "../../grammar"; -import { headerize } from "./utils"; -/** - * Incoming message. - * @public - */ -export class IncomingMessage { - constructor() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.headers = {}; - } - /** - * Insert a header of the given name and value into the last position of the - * header array. - * @param name - header name - * @param value - header value - */ - addHeader(name, value) { - const header = { raw: value }; - name = headerize(name); - if (this.headers[name]) { - this.headers[name].push(header); - } - else { - this.headers[name] = [header]; - } - } - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name) { - const header = this.headers[headerize(name)]; - if (header) { - if (header[0]) { - return header[0].raw; - } - } - else { - return; - } - } - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array - with all the headers of the specified name. - */ - getHeaders(name) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const header = this.headers[headerize(name)]; - const result = []; - if (!header) { - return []; - } - for (const headerPart of header) { - result.push(headerPart.raw); - } - return result; - } - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name) { - return !!this.headers[headerize(name)]; - } - /** - * Parse the given header on the given index. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - parseHeader(name, idx = 0) { - name = headerize(name); - if (!this.headers[name]) { - // this.logger.log("header '" + name + "' not present"); - return; - } - else if (idx >= this.headers[name].length) { - // this.logger.log("not so many '" + name + "' headers present"); - return; - } - const header = this.headers[name][idx]; - const value = header.raw; - if (header.parsed) { - return header.parsed; - } - // substitute '-' by '_' for grammar rule matching. - const parsed = Grammar.parse(value, name.replace(/-/g, "_")); - if (parsed === -1) { - this.headers[name].splice(idx, 1); // delete from headers - // this.logger.warn('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } - else { - header.parsed = parsed; - return parsed; - } - } - /** - * Message Header attribute selector. Alias of parseHeader. - * @param name - header name - * @param idx - header index - * @returns Parsed header object, undefined if the - * header is not present or in case of a parsing error. - * - * @example - * message.s('via',3).port - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - s(name, idx = 0) { - return this.parseHeader(name, idx); - } - /** - * Replace the value of the given header by the value. - * @param name - header name - * @param value - header value - */ - setHeader(name, value) { - this.headers[headerize(name)] = [{ raw: value }]; - } - toString() { - return this.data; - } -} diff --git a/lib/core/messages/incoming-request-message.d.ts b/lib/core/messages/incoming-request-message.d.ts deleted file mode 100644 index eb50bbc8e..000000000 --- a/lib/core/messages/incoming-request-message.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { URI } from "../messages"; -import { IncomingMessage } from "./incoming-message"; -/** - * Incoming request message. - * @public - */ -export declare class IncomingRequestMessage extends IncomingMessage { - ruri: URI | undefined; - constructor(); -} -//# sourceMappingURL=incoming-request-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-request-message.d.ts.map b/lib/core/messages/incoming-request-message.d.ts.map deleted file mode 100644 index 23beeffa3..000000000 --- a/lib/core/messages/incoming-request-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-request-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-request-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAe;IAClD,IAAI,EAAE,GAAG,GAAG,SAAS,CAAC;;CAK9B"} \ No newline at end of file diff --git a/lib/core/messages/incoming-request-message.js b/lib/core/messages/incoming-request-message.js deleted file mode 100644 index 6e5abb2ea..000000000 --- a/lib/core/messages/incoming-request-message.js +++ /dev/null @@ -1,10 +0,0 @@ -import { IncomingMessage } from "./incoming-message"; -/** - * Incoming request message. - * @public - */ -export class IncomingRequestMessage extends IncomingMessage { - constructor() { - super(); - } -} diff --git a/lib/core/messages/incoming-request.d.ts b/lib/core/messages/incoming-request.d.ts deleted file mode 100644 index 56da6209b..000000000 --- a/lib/core/messages/incoming-request.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { TransportError } from "../exceptions"; -import { URI } from "../messages"; -import { IncomingRequestMessage } from "./incoming-request-message"; -import { OutgoingResponse, ResponseOptions } from "./outgoing-response"; -/** - * A SIP message sent from a remote client to a local server. - * @remarks - * For the purpose of invoking a particular operation. - * https://tools.ietf.org/html/rfc3261#section-7.1 - * @public - */ -export interface IncomingRequest { - /** Delegate providing custom handling of this incoming request. */ - delegate?: IncomingRequestDelegate; - /** The incoming message. */ - readonly message: IncomingRequestMessage; - /** - * Send a 2xx positive final response to this request. Defaults to 200. - * @param options - Response options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponse; - /** - * Send a 1xx provisional response to this request. Defaults to 180. Excludes 100. - * Note that per RFC 4320, this method may only be used to respond to INVITE requests. - * @param options - Response options bucket. - */ - progress(options?: ResponseOptions): OutgoingResponse; - /** - * Send a 3xx negative final response to this request. Defaults to 302. - * @param contacts - Contacts to redirect the UAC to. - * @param options - Response options bucket. - */ - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - /** - * Send a 4xx, 5xx, or 6xx negative final response to this request. Defaults to 480. - * @param options - Response options bucket. - */ - reject(options?: ResponseOptions): OutgoingResponse; - /** - * Send a 100 outgoing response to this request. - * @param options - Response options bucket. - */ - trying(options?: ResponseOptions): OutgoingResponse; -} -/** - * Delegate providing custom handling of incoming requests. - * @public - */ -export interface IncomingRequestDelegate { - /** - * Receive CANCEL request. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * Note: Currently CANCEL is being handled as a special case. - * No UAS is created to handle the CANCEL and the response to - * it CANCEL is being handled statelessly by the user agent core. - * As such, there is currently no way to externally impact the - * response to the a CANCEL request and thus the method here is - * receiving a "message" (as apposed to a "uas"). - * @param message - Incoming CANCEL request message. - */ - onCancel?(message: IncomingRequestMessage): void; - /** - * A transport error occurred attempted to send a response. - * @param error - Transport error. - */ - onTransportError?(error: TransportError): void; -} -//# sourceMappingURL=incoming-request.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-request.d.ts.map b/lib/core/messages/incoming-request.d.ts.map deleted file mode 100644 index 5cde494a7..000000000 --- a/lib/core/messages/incoming-request.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-request.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-request.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,mEAAmE;IACnE,QAAQ,CAAC,EAAE,uBAAuB,CAAC;IACnC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;IAEzC;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEpD;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEtD;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAE5E;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEpD;;;OAGG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC;CACrD;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAEjD;;;OAGG;IACH,gBAAgB,CAAC,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI,CAAC;CAChD"} \ No newline at end of file diff --git a/lib/core/messages/incoming-request.js b/lib/core/messages/incoming-request.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/incoming-response-message.d.ts b/lib/core/messages/incoming-response-message.d.ts deleted file mode 100644 index a04152af4..000000000 --- a/lib/core/messages/incoming-response-message.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IncomingMessage } from "./incoming-message"; -/** - * Incoming response message. - * @public - */ -export declare class IncomingResponseMessage extends IncomingMessage { - statusCode: number | undefined; - reasonPhrase: string | undefined; - constructor(); -} -//# sourceMappingURL=incoming-response-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-response-message.d.ts.map b/lib/core/messages/incoming-response-message.d.ts.map deleted file mode 100644 index 7c9d9853b..000000000 --- a/lib/core/messages/incoming-response-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-response-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-response-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,eAAe;IACnD,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;;CAKzC"} \ No newline at end of file diff --git a/lib/core/messages/incoming-response-message.js b/lib/core/messages/incoming-response-message.js deleted file mode 100644 index 65bada916..000000000 --- a/lib/core/messages/incoming-response-message.js +++ /dev/null @@ -1,10 +0,0 @@ -import { IncomingMessage } from "./incoming-message"; -/** - * Incoming response message. - * @public - */ -export class IncomingResponseMessage extends IncomingMessage { - constructor() { - super(); - } -} diff --git a/lib/core/messages/incoming-response.d.ts b/lib/core/messages/incoming-response.d.ts deleted file mode 100644 index f2a2daefa..000000000 --- a/lib/core/messages/incoming-response.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { IncomingResponseMessage } from "./incoming-response-message"; -/** - * A SIP message sent from a remote server to a local client. - * @remarks - * For indicating the status of a request sent from the client to the server. - * https://tools.ietf.org/html/rfc3261#section-7.2 - * @public - */ -export interface IncomingResponse { - /** The incoming message. */ - readonly message: IncomingResponseMessage; -} -//# sourceMappingURL=incoming-response.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/incoming-response.d.ts.map b/lib/core/messages/incoming-response.d.ts.map deleted file mode 100644 index 96bd96b83..000000000 --- a/lib/core/messages/incoming-response.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"incoming-response.d.ts","sourceRoot":"","sources":["../../../src/core/messages/incoming-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;CAC3C"} \ No newline at end of file diff --git a/lib/core/messages/incoming-response.js b/lib/core/messages/incoming-response.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/index.d.ts b/lib/core/messages/index.d.ts deleted file mode 100644 index 03d0aa8da..000000000 --- a/lib/core/messages/index.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from "../../grammar"; -export * from "./methods"; -export * from "./body"; -export * from "./digest-authentication"; -export * from "./incoming-message"; -export * from "./incoming-request-message"; -export * from "./incoming-request"; -export * from "./incoming-response-message"; -export * from "./incoming-response"; -export * from "./outgoing-request-message"; -export * from "./outgoing-request"; -export * from "./outgoing-response"; -export * from "./parser"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/index.d.ts.map b/lib/core/messages/index.d.ts.map deleted file mode 100644 index 00c0a820a..000000000 --- a/lib/core/messages/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/messages/index.ts"],"names":[],"mappings":"AACA,cAAc,eAAe,CAAC;AAG9B,cAAc,WAAW,CAAC;AAG1B,cAAc,QAAQ,CAAC;AACvB,cAAc,yBAAyB,CAAC;AACxC,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/lib/core/messages/index.js b/lib/core/messages/index.js deleted file mode 100644 index ccf8af4bc..000000000 --- a/lib/core/messages/index.js +++ /dev/null @@ -1,16 +0,0 @@ -// Grammar -export * from "../../grammar"; -// Directories -export * from "./methods"; -// Files -export * from "./body"; -export * from "./digest-authentication"; -export * from "./incoming-message"; -export * from "./incoming-request-message"; -export * from "./incoming-request"; -export * from "./incoming-response-message"; -export * from "./incoming-response"; -export * from "./outgoing-request-message"; -export * from "./outgoing-request"; -export * from "./outgoing-response"; -export * from "./parser"; diff --git a/lib/core/messages/md5.d.ts b/lib/core/messages/md5.d.ts deleted file mode 100644 index 73d63f408..000000000 --- a/lib/core/messages/md5.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -export declare class Md5 { - static hashStr(str: string, raw?: false): string; - static hashStr(str: string, raw?: true): Int32Array; - static hashAsciiStr(str: string, raw?: false): string; - static hashAsciiStr(str: string, raw?: true): Int32Array; - private static stateIdentity; - private static buffer32Identity; - private static hexChars; - private static hexOut; - private static onePassHasher; - private static _hex; - private static _md5cycle; - private _dataLength; - private _bufferLength; - private _state; - private _buffer; - private _buffer8; - private _buffer32; - constructor(); - start(): this; - appendStr(str: string): this; - appendAsciiStr(str: string): this; - appendByteArray(input: Uint8Array): this; - getState(): { - buffer: string; - buflen: number; - length: number; - state: number[]; - }; - setState(state: any): void; - end(raw?: boolean): string | Int32Array | undefined; -} -//# sourceMappingURL=md5.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/md5.d.ts.map b/lib/core/messages/md5.d.ts.map deleted file mode 100644 index 0a4c6d95c..000000000 --- a/lib/core/messages/md5.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"md5.d.ts","sourceRoot":"","sources":["../../../src/core/messages/md5.ts"],"names":[],"mappings":"AA2DA,qBAAa,GAAG;WAGA,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM;WACzC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,GAAG,UAAU;WAQ5C,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM;WAC9C,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,GAAG,UAAU;IAQ/D,OAAO,CAAC,MAAM,CAAC,aAAa,CAAoE;IAChG,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAoE;IACnG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAsB;IAC7C,OAAO,CAAC,MAAM,CAAC,MAAM,CAAgB;IAGrC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAa;IAEzC,OAAO,CAAC,MAAM,CAAC,IAAI;IAqBnB,OAAO,CAAC,MAAM,CAAC,SAAS;IAgJxB,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,aAAa,CAAa;IAElC,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,OAAO,CAAoC;IACnD,OAAO,CAAC,QAAQ,CAAa;IAC7B,OAAO,CAAC,SAAS,CAAc;;IAQxB,KAAK;IAUL,SAAS,CAAC,GAAG,EAAE,MAAM;IAuCrB,cAAc,CAAC,GAAG,EAAE,MAAM;IAuB1B,eAAe,CAAC,KAAK,EAAE,UAAU;IAuBjC,QAAQ;;;;;;IAYR,QAAQ,CAAC,KAAK,EAAE,GAAG;IAkBnB,GAAG,CAAC,GAAG,GAAE,OAAe;CAwChC"} \ No newline at end of file diff --git a/lib/core/messages/md5.js b/lib/core/messages/md5.js deleted file mode 100644 index 0f2bafe98..000000000 --- a/lib/core/messages/md5.js +++ /dev/null @@ -1,399 +0,0 @@ -/* eslint-disable */ -// -// Scoped from: https://github.com/cotag/ts-md5 -// -/* - -TypeScript Md5 -============== - -Based on work by -* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html -* André Cruz: https://github.com/satazor/SparkMD5 -* Raymond Hill: https://github.com/gorhill/yamd5.js - -Effectively a TypeScrypt re-write of Raymond Hill JS Library - -The MIT License (MIT) - -Copyright (C) 2014 Raymond Hill - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2015 André Cruz - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - - -*/ -export class Md5 { - constructor() { - this._dataLength = 0; - this._bufferLength = 0; - this._state = new Int32Array(4); - this._buffer = new ArrayBuffer(68); - this._buffer8 = new Uint8Array(this._buffer, 0, 68); - this._buffer32 = new Uint32Array(this._buffer, 0, 17); - this.start(); - } - static hashStr(str, raw = false) { - return this.onePassHasher - .start() - .appendStr(str) - .end(raw); - } - static hashAsciiStr(str, raw = false) { - return this.onePassHasher - .start() - .appendAsciiStr(str) - .end(raw); - } - static _hex(x) { - const hc = Md5.hexChars; - const ho = Md5.hexOut; - let n; - let offset; - let j; - let i; - for (i = 0; i < 4; i += 1) { - offset = i * 8; - n = x[i]; - for (j = 0; j < 8; j += 2) { - ho[offset + 1 + j] = hc.charAt(n & 0x0F); - n >>>= 4; - ho[offset + 0 + j] = hc.charAt(n & 0x0F); - n >>>= 4; - } - } - return ho.join(''); - } - static _md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - // ff() - a += (b & c | ~b & d) + k[0] - 680876936 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[1] - 389564586 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[2] + 606105819 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[3] - 1044525330 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[4] - 176418897 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[5] + 1200080426 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[6] - 1473231341 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[7] - 45705983 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[8] + 1770035416 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[9] - 1958414417 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[10] - 42063 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[11] - 1990404162 | 0; - b = (b << 22 | b >>> 10) + c | 0; - a += (b & c | ~b & d) + k[12] + 1804603682 | 0; - a = (a << 7 | a >>> 25) + b | 0; - d += (a & b | ~a & c) + k[13] - 40341101 | 0; - d = (d << 12 | d >>> 20) + a | 0; - c += (d & a | ~d & b) + k[14] - 1502002290 | 0; - c = (c << 17 | c >>> 15) + d | 0; - b += (c & d | ~c & a) + k[15] + 1236535329 | 0; - b = (b << 22 | b >>> 10) + c | 0; - // gg() - a += (b & d | c & ~d) + k[1] - 165796510 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[6] - 1069501632 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[11] + 643717713 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[0] - 373897302 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[5] - 701558691 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[10] + 38016083 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[15] - 660478335 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[4] - 405537848 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[9] + 568446438 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[14] - 1019803690 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[3] - 187363961 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[8] + 1163531501 | 0; - b = (b << 20 | b >>> 12) + c | 0; - a += (b & d | c & ~d) + k[13] - 1444681467 | 0; - a = (a << 5 | a >>> 27) + b | 0; - d += (a & c | b & ~c) + k[2] - 51403784 | 0; - d = (d << 9 | d >>> 23) + a | 0; - c += (d & b | a & ~b) + k[7] + 1735328473 | 0; - c = (c << 14 | c >>> 18) + d | 0; - b += (c & a | d & ~a) + k[12] - 1926607734 | 0; - b = (b << 20 | b >>> 12) + c | 0; - // hh() - a += (b ^ c ^ d) + k[5] - 378558 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[8] - 2022574463 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[11] + 1839030562 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[14] - 35309556 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[1] - 1530992060 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[4] + 1272893353 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[7] - 155497632 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[10] - 1094730640 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[13] + 681279174 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[0] - 358537222 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[3] - 722521979 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[6] + 76029189 | 0; - b = (b << 23 | b >>> 9) + c | 0; - a += (b ^ c ^ d) + k[9] - 640364487 | 0; - a = (a << 4 | a >>> 28) + b | 0; - d += (a ^ b ^ c) + k[12] - 421815835 | 0; - d = (d << 11 | d >>> 21) + a | 0; - c += (d ^ a ^ b) + k[15] + 530742520 | 0; - c = (c << 16 | c >>> 16) + d | 0; - b += (c ^ d ^ a) + k[2] - 995338651 | 0; - b = (b << 23 | b >>> 9) + c | 0; - // ii() - a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; - b = (b << 21 | b >>> 11) + c | 0; - a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; - a = (a << 6 | a >>> 26) + b | 0; - d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; - d = (d << 10 | d >>> 22) + a | 0; - c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; - c = (c << 15 | c >>> 17) + d | 0; - b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; - b = (b << 21 | b >>> 11) + c | 0; - x[0] = a + x[0] | 0; - x[1] = b + x[1] | 0; - x[2] = c + x[2] | 0; - x[3] = d + x[3] | 0; - } - start() { - this._dataLength = 0; - this._bufferLength = 0; - this._state.set(Md5.stateIdentity); - return this; - } - // Char to code point to to array conversion: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt - // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown - appendStr(str) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let code; - let i; - for (i = 0; i < str.length; i += 1) { - code = str.charCodeAt(i); - if (code < 128) { - buf8[bufLen++] = code; - } - else if (code < 0x800) { - buf8[bufLen++] = (code >>> 6) + 0xC0; - buf8[bufLen++] = code & 0x3F | 0x80; - } - else if (code < 0xD800 || code > 0xDBFF) { - buf8[bufLen++] = (code >>> 12) + 0xE0; - buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; - buf8[bufLen++] = (code & 0x3F) | 0x80; - } - else { - code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; - if (code > 0x10FFFF) { - throw new Error('Unicode standard supports code points up to U+10FFFF'); - } - buf8[bufLen++] = (code >>> 18) + 0xF0; - buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; - buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; - buf8[bufLen++] = (code & 0x3F) | 0x80; - } - if (bufLen >= 64) { - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen -= 64; - buf32[0] = buf32[16]; - } - } - this._bufferLength = bufLen; - return this; - } - appendAsciiStr(str) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let i; - let j = 0; - for (;;) { - i = Math.min(str.length - j, 64 - bufLen); - while (i--) { - buf8[bufLen++] = str.charCodeAt(j++); - } - if (bufLen < 64) { - break; - } - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen = 0; - } - this._bufferLength = bufLen; - return this; - } - appendByteArray(input) { - const buf8 = this._buffer8; - const buf32 = this._buffer32; - let bufLen = this._bufferLength; - let i; - let j = 0; - for (;;) { - i = Math.min(input.length - j, 64 - bufLen); - while (i--) { - buf8[bufLen++] = input[j++]; - } - if (bufLen < 64) { - break; - } - this._dataLength += 64; - Md5._md5cycle(this._state, buf32); - bufLen = 0; - } - this._bufferLength = bufLen; - return this; - } - getState() { - const self = this; - const s = self._state; - return { - buffer: String.fromCharCode.apply(null, self._buffer8), - buflen: self._bufferLength, - length: self._dataLength, - state: [s[0], s[1], s[2], s[3]] - }; - } - setState(state) { - const buf = state.buffer; - const x = state.state; - const s = this._state; - let i; - this._dataLength = state.length; - this._bufferLength = state.buflen; - s[0] = x[0]; - s[1] = x[1]; - s[2] = x[2]; - s[3] = x[3]; - for (i = 0; i < buf.length; i += 1) { - this._buffer8[i] = buf.charCodeAt(i); - } - } - end(raw = false) { - const bufLen = this._bufferLength; - const buf8 = this._buffer8; - const buf32 = this._buffer32; - const i = (bufLen >> 2) + 1; - let dataBitsLen; - this._dataLength += bufLen; - buf8[bufLen] = 0x80; - buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; - buf32.set(Md5.buffer32Identity.subarray(i), i); - if (bufLen > 55) { - Md5._md5cycle(this._state, buf32); - buf32.set(Md5.buffer32Identity); - } - // Do the final computation based on the tail and length - // Beware that the final length may not fit in 32 bits so we take care of that - dataBitsLen = this._dataLength * 8; - if (dataBitsLen <= 0xFFFFFFFF) { - buf32[14] = dataBitsLen; - } - else { - const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); - if (matches === null) { - return; - } - const lo = parseInt(matches[2], 16); - const hi = parseInt(matches[1], 16) || 0; - buf32[14] = lo; - buf32[15] = hi; - } - Md5._md5cycle(this._state, buf32); - return raw ? this._state : Md5._hex(this._state); - } -} -// Private Static Variables -Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); -Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); -Md5.hexChars = '0123456789abcdef'; -Md5.hexOut = []; -// Permanent instance is to use for one-call hashing -Md5.onePassHasher = new Md5(); -if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { - console.error('Md5 self test failed.'); -} diff --git a/lib/core/messages/methods/ack.d.ts b/lib/core/messages/methods/ack.d.ts deleted file mode 100644 index 864a450e2..000000000 --- a/lib/core/messages/methods/ack.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { IncomingRequestMessage } from "../incoming-request-message"; -import { OutgoingRequestMessage } from "../outgoing-request-message"; -/** - * Incoming ACK request. - * @public - */ -export interface IncomingAckRequest { - /** The incoming message. */ - readonly message: IncomingRequestMessage; -} -/** - * Outgoing ACK request. - * @public - */ -export interface OutgoingAckRequest { - /** The outgoing message. */ - readonly message: OutgoingRequestMessage; -} -//# sourceMappingURL=ack.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/ack.d.ts.map b/lib/core/messages/methods/ack.d.ts.map deleted file mode 100644 index 28a6505ec..000000000 --- a/lib/core/messages/methods/ack.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ack.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/ack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAIrE;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;CAC1C"} \ No newline at end of file diff --git a/lib/core/messages/methods/ack.js b/lib/core/messages/methods/ack.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/bye.d.ts b/lib/core/messages/methods/bye.d.ts deleted file mode 100644 index b1252b205..000000000 --- a/lib/core/messages/methods/bye.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming BYE request. - * @public - */ -export interface IncomingByeRequest extends IncomingRequest { -} -/** - * Incoming BYE response. - * @public - */ -export interface IncomingByeResponse extends IncomingResponse { -} -/** - * Outgoing BYE request. - * @public - */ -export interface OutgoingByeRequest extends OutgoingRequest { -} -//# sourceMappingURL=bye.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/bye.d.ts.map b/lib/core/messages/methods/bye.d.ts.map deleted file mode 100644 index 280284ced..000000000 --- a/lib/core/messages/methods/bye.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/bye.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,eAAe;CAAG;AAE9D;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;CAAG;AAEhE;;;GAGG;AACH,MAAM,WAAW,kBAAmB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/bye.js b/lib/core/messages/methods/bye.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/cancel.d.ts b/lib/core/messages/methods/cancel.d.ts deleted file mode 100644 index 8046a0a5b..000000000 --- a/lib/core/messages/methods/cancel.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming CANCEL request. - * @public - */ -export interface IncomingCancelRequest extends IncomingRequest { -} -/** - * Incoming CANCEL response. - * @public - */ -export interface IncomingCancelResponse extends IncomingResponse { -} -/** - * Outgoing CANCEL request. - * @public - */ -export interface OutgoingCancelRequest extends OutgoingRequest { -} -//# sourceMappingURL=cancel.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/cancel.d.ts.map b/lib/core/messages/methods/cancel.d.ts.map deleted file mode 100644 index bb7b87db7..000000000 --- a/lib/core/messages/methods/cancel.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cancel.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/cancel.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG;AAEjE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;CAAG;AAEnE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/cancel.js b/lib/core/messages/methods/cancel.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/constants.d.ts b/lib/core/messages/methods/constants.d.ts deleted file mode 100644 index 02e5a2fdb..000000000 --- a/lib/core/messages/methods/constants.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * SIP Methods - * @internal - */ -export declare namespace C { - const ACK = "ACK"; - const BYE = "BYE"; - const CANCEL = "CANCEL"; - const INFO = "INFO"; - const INVITE = "INVITE"; - const MESSAGE = "MESSAGE"; - const NOTIFY = "NOTIFY"; - const OPTIONS = "OPTIONS"; - const REGISTER = "REGISTER"; - const UPDATE = "UPDATE"; - const SUBSCRIBE = "SUBSCRIBE"; - const PUBLISH = "PUBLISH"; - const REFER = "REFER"; - const PRACK = "PRACK"; -} -//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/constants.d.ts.map b/lib/core/messages/methods/constants.d.ts.map deleted file mode 100644 index 95b4929ab..000000000 --- a/lib/core/messages/methods/constants.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/constants.ts"],"names":[],"mappings":"AACA;;;GAGG;AACH,yBAAiB,CAAC,CAAC;IACV,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,GAAG,QAAQ,CAAC;IAClB,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,IAAI,SAAS,CAAC;IACpB,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,QAAQ,aAAa,CAAC;IAC5B,MAAM,MAAM,WAAW,CAAC;IACxB,MAAM,SAAS,cAAc,CAAC;IAC9B,MAAM,OAAO,YAAY,CAAC;IAC1B,MAAM,KAAK,UAAU,CAAC;IACtB,MAAM,KAAK,UAAU,CAAC;CAC9B"} \ No newline at end of file diff --git a/lib/core/messages/methods/constants.js b/lib/core/messages/methods/constants.js deleted file mode 100644 index 9a744dde4..000000000 --- a/lib/core/messages/methods/constants.js +++ /dev/null @@ -1,22 +0,0 @@ -/* eslint-disable @typescript-eslint/no-namespace */ -/** - * SIP Methods - * @internal - */ -export var C; -(function (C) { - C.ACK = "ACK"; - C.BYE = "BYE"; - C.CANCEL = "CANCEL"; - C.INFO = "INFO"; - C.INVITE = "INVITE"; - C.MESSAGE = "MESSAGE"; - C.NOTIFY = "NOTIFY"; - C.OPTIONS = "OPTIONS"; - C.REGISTER = "REGISTER"; - C.UPDATE = "UPDATE"; - C.SUBSCRIBE = "SUBSCRIBE"; - C.PUBLISH = "PUBLISH"; - C.REFER = "REFER"; - C.PRACK = "PRACK"; -})(C || (C = {})); diff --git a/lib/core/messages/methods/index.d.ts b/lib/core/messages/methods/index.d.ts deleted file mode 100644 index 84e1892a3..000000000 --- a/lib/core/messages/methods/index.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from "./constants"; -export * from "./ack"; -export * from "./bye"; -export * from "./cancel"; -export * from "./info"; -export * from "./invite"; -export * from "./message"; -export * from "./notify"; -export * from "./prack"; -export * from "./publish"; -export * from "./register"; -export * from "./refer"; -export * from "./subscribe"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/index.d.ts.map b/lib/core/messages/methods/index.d.ts.map deleted file mode 100644 index 95b4d8d8b..000000000 --- a/lib/core/messages/methods/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AACvB,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/core/messages/methods/index.js b/lib/core/messages/methods/index.js deleted file mode 100644 index f60ff2931..000000000 --- a/lib/core/messages/methods/index.js +++ /dev/null @@ -1,13 +0,0 @@ -export * from "./constants"; -export * from "./ack"; -export * from "./bye"; -export * from "./cancel"; -export * from "./info"; -export * from "./invite"; -export * from "./message"; -export * from "./notify"; -export * from "./prack"; -export * from "./publish"; -export * from "./register"; -export * from "./refer"; -export * from "./subscribe"; diff --git a/lib/core/messages/methods/info.d.ts b/lib/core/messages/methods/info.d.ts deleted file mode 100644 index c5c26d00c..000000000 --- a/lib/core/messages/methods/info.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming INFO request. - * @public - */ -export interface IncomingInfoRequest extends IncomingRequest { -} -/** - * Incoming INFO response. - * @public - */ -export interface IncomingInfoResponse extends IncomingResponse { -} -/** - * Outgoing INFO request. - * @public - */ -export interface OutgoingInfoRequest extends OutgoingRequest { -} -//# sourceMappingURL=info.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/info.d.ts.map b/lib/core/messages/methods/info.d.ts.map deleted file mode 100644 index 2d98e15a5..000000000 --- a/lib/core/messages/methods/info.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/info.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;CAAG;AAE/D;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;CAAG;AAEjE;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/info.js b/lib/core/messages/methods/info.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/invite.d.ts b/lib/core/messages/methods/invite.d.ts deleted file mode 100644 index 8ee3ab809..000000000 --- a/lib/core/messages/methods/invite.d.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Session } from "../../session"; -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest, OutgoingRequestDelegate, RequestOptions } from "../outgoing-request"; -import { OutgoingResponse, ResponseOptions } from "../outgoing-response"; -import { OutgoingAckRequest } from "./ack"; -import { OutgoingPrackRequest } from "./prack"; -/** - * Incoming INVITE request. - * @public - */ -export interface IncomingInviteRequest extends IncomingRequest { - /** - * Send a 2xx positive final response to this request. Defaults to 200. - * @param options - Response options bucket. - * @returns Outgoing response and a confirmed Session. - */ - accept(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * Send a 1xx provisional response to this request. Defaults to 180. Excludes 100. - * @param options - Response options bucket. - * @returns Outgoing response and an early Session. - */ - progress(options?: ResponseOptions): OutgoingResponseWithSession; -} -/** - * Outgoing INVITE response with the associated {@link Session}. - * @public - */ -export interface OutgoingResponseWithSession extends OutgoingResponse { - /** - * Session associated with incoming request acceptance, or - * Session associated with incoming request progress (if an out of dialog request, an early dialog). - */ - readonly session: Session; -} -/** - * Outgoing INVITE request. - * @public - */ -export interface OutgoingInviteRequest extends OutgoingRequest { - /** Delegate providing custom handling of this outgoing INVITE request. */ - delegate?: OutgoingInviteRequestDelegate; -} -/** - * Delegate providing custom handling of outgoing INVITE requests. - * @public - */ -export interface OutgoingInviteRequestDelegate extends OutgoingRequestDelegate { - /** - * Received a 2xx positive final response to this request. - * @param response - Incoming response (including a confirmed Session). - */ - onAccept?(response: AckableIncomingResponseWithSession): void; - /** - * Received a 1xx provisional response to this request. Excluding 100 responses. - * @param response - Incoming response (including an early Session). - */ - onProgress?(response: PrackableIncomingResponseWithSession): void; -} -/** - * Incoming INVITE response received when request is accepted. - * @public - */ -export interface AckableIncomingResponseWithSession extends IncomingResponse { - /** Session associated with outgoing request acceptance. */ - readonly session: Session; - /** - * Send an ACK to acknowledge this response. - * @param options - Request options bucket. - */ - ack(options?: RequestOptions): OutgoingAckRequest; -} -/** - * Incoming INVITE response received when request is progressed. - * @public - */ -export interface PrackableIncomingResponseWithSession extends IncomingResponse { - /** Session associated with outgoing request progress. If out of dialog request, an early dialog. */ - readonly session: Session; - /** - * Send an PRACK to acknowledge this response. - * @param options - Request options bucket. - */ - prack(options?: RequestOptions): OutgoingPrackRequest; -} -//# sourceMappingURL=invite.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/invite.d.ts.map b/lib/core/messages/methods/invite.d.ts.map deleted file mode 100644 index 8db910146..000000000 --- a/lib/core/messages/methods/invite.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/invite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAM/C;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,2BAA2B,CAAC;IAE/D;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,2BAA2B,CAAC;CAClE;AAED;;;GAGG;AACH,MAAM,WAAW,2BAA4B,SAAQ,gBAAgB;IACnE;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAMD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,6BAA6B,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,6BAA8B,SAAQ,uBAAuB;IAC5E;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,kCAAkC,GAAG,IAAI,CAAC;IAE9D;;;OAGG;IACH,UAAU,CAAC,CAAC,QAAQ,EAAE,oCAAoC,GAAG,IAAI,CAAC;CACnE;AAED;;;GAGG;AACH,MAAM,WAAW,kCAAmC,SAAQ,gBAAgB;IAC1E,2DAA2D;IAC3D,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,GAAG,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,kBAAkB,CAAC;CACnD;AAED;;;GAGG;AACH,MAAM,WAAW,oCAAqC,SAAQ,gBAAgB;IAC5E,oGAAoG;IACpG,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,KAAK,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB,CAAC;CACvD"} \ No newline at end of file diff --git a/lib/core/messages/methods/invite.js b/lib/core/messages/methods/invite.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/message.d.ts b/lib/core/messages/methods/message.d.ts deleted file mode 100644 index b501e63ed..000000000 --- a/lib/core/messages/methods/message.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming MESSAGE request. - * @public - */ -export interface IncomingMessageRequest extends IncomingRequest { -} -/** - * Incoming MESSAGE response. - * @public - */ -export interface IncomingMessageResponse extends IncomingResponse { -} -/** - * Outgoing MESSAGE request. - * @public - */ -export interface OutgoingMessageRequest extends OutgoingRequest { -} -//# sourceMappingURL=message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/message.d.ts.map b/lib/core/messages/methods/message.d.ts.map deleted file mode 100644 index ca4d83c3b..000000000 --- a/lib/core/messages/methods/message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/message.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;CAAG;AAEpE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/message.js b/lib/core/messages/methods/message.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/notify.d.ts b/lib/core/messages/methods/notify.d.ts deleted file mode 100644 index a19936699..000000000 --- a/lib/core/messages/methods/notify.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming NOTIFY request. - * @public - */ -export interface IncomingNotifyRequest extends IncomingRequest { -} -/** - * Incoming NOTIFY response. - * @public - */ -export interface IncomingNotifyResponse extends IncomingResponse { -} -/** - * Outgoing NOTIFY request. - * @public - */ -export interface OutgoingNotifyRequest extends OutgoingRequest { -} -//# sourceMappingURL=notify.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/notify.d.ts.map b/lib/core/messages/methods/notify.d.ts.map deleted file mode 100644 index 2668f5b3c..000000000 --- a/lib/core/messages/methods/notify.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notify.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/notify.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG;AAEjE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;CAAG;AAEnE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/notify.js b/lib/core/messages/methods/notify.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/prack.d.ts b/lib/core/messages/methods/prack.d.ts deleted file mode 100644 index 4b565334d..000000000 --- a/lib/core/messages/methods/prack.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming PRACK request. - * @public - */ -export interface IncomingPrackRequest extends IncomingRequest { -} -/** - * Incoming PRACK response. - * @public - */ -export interface IncomingPrackResponse extends IncomingResponse { -} -/** - * Outgoing PRACK request. - * @public - */ -export interface OutgoingPrackRequest extends OutgoingRequest { -} -//# sourceMappingURL=prack.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/prack.d.ts.map b/lib/core/messages/methods/prack.d.ts.map deleted file mode 100644 index d8e69158a..000000000 --- a/lib/core/messages/methods/prack.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"prack.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/prack.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG;AAEhE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/prack.js b/lib/core/messages/methods/prack.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/publish.d.ts b/lib/core/messages/methods/publish.d.ts deleted file mode 100644 index c0c25b526..000000000 --- a/lib/core/messages/methods/publish.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming PUBLISH request. - * @public - */ -export interface IncomingPublishRequest extends IncomingRequest { -} -/** - * Incoming PUBLISH response. - * @public - */ -export interface IncomingPublishResponse extends IncomingResponse { -} -/** - * Outgoing PUBLISH request. - * @public - */ -export interface OutgoingPublishRequest extends OutgoingRequest { -} -//# sourceMappingURL=publish.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/publish.d.ts.map b/lib/core/messages/methods/publish.d.ts.map deleted file mode 100644 index 8b963dadd..000000000 --- a/lib/core/messages/methods/publish.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publish.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/publish.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;CAAG;AAEpE;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/publish.js b/lib/core/messages/methods/publish.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/refer.d.ts b/lib/core/messages/methods/refer.d.ts deleted file mode 100644 index cb11370f7..000000000 --- a/lib/core/messages/methods/refer.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming REFER request. - * @public - */ -export interface IncomingReferRequest extends IncomingRequest { -} -/** - * Incoming REFER response. - * @public - */ -export interface IncomingReferResponse extends IncomingResponse { -} -/** - * Outgoing REFER request. - * @public - */ -export interface OutgoingReferRequest extends OutgoingRequest { -} -//# sourceMappingURL=refer.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/refer.d.ts.map b/lib/core/messages/methods/refer.d.ts.map deleted file mode 100644 index 46f632e79..000000000 --- a/lib/core/messages/methods/refer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"refer.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/refer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG;AAEhE;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;CAAG;AAElE;;;GAGG;AACH,MAAM,WAAW,oBAAqB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/refer.js b/lib/core/messages/methods/refer.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/register.d.ts b/lib/core/messages/methods/register.d.ts deleted file mode 100644 index f5fb52552..000000000 --- a/lib/core/messages/methods/register.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest } from "../outgoing-request"; -/** - * Incoming REGISTER request. - * @public - */ -export interface IncomingRegisterRequest extends IncomingRequest { -} -/** - * Incoming REGISTER response. - * @public - */ -export interface IncomingRegisterResponse extends IncomingResponse { -} -/** - * Outgoing REGISTER request. - * @public - */ -export interface OutgoingRegisterRequest extends OutgoingRequest { -} -//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/register.d.ts.map b/lib/core/messages/methods/register.d.ts.map deleted file mode 100644 index 360af5c4e..000000000 --- a/lib/core/messages/methods/register.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/register.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;CAAG;AAEnE;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;CAAG;AAErE;;;GAGG;AACH,MAAM,WAAW,uBAAwB,SAAQ,eAAe;CAAG"} \ No newline at end of file diff --git a/lib/core/messages/methods/register.js b/lib/core/messages/methods/register.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/methods/subscribe.d.ts b/lib/core/messages/methods/subscribe.d.ts deleted file mode 100644 index 43b41c6dc..000000000 --- a/lib/core/messages/methods/subscribe.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { Subscription } from "../../subscription"; -import { IncomingRequest } from "../incoming-request"; -import { IncomingResponse } from "../incoming-response"; -import { OutgoingRequest, OutgoingRequestDelegate } from "../outgoing-request"; -import { IncomingNotifyRequest } from "./notify"; -/** - * Incoming SUBSCRIBE request. - * @public - */ -export interface IncomingSubscribeRequest extends IncomingRequest { -} -/** - * Incoming SUBSCRIBE response. - * @public - */ -export interface IncomingSubscribeResponse extends IncomingResponse { -} -/** - * Outgoing SUBSCRIBE request. - * @public - */ -export interface OutgoingSubscribeRequest extends OutgoingRequest { - /** Delegate providing custom handling of this outgoing SUBSCRIBE request. */ - delegate?: OutgoingSubscribeRequestDelegate; - /** Stop waiting for an inital subscription creating NOTIFY. */ - waitNotifyStop(): void; -} -/** - * Delegate providing custom handling of outgoing SUBSCRIBE requests. - * @public - */ -export interface OutgoingSubscribeRequestDelegate extends OutgoingRequestDelegate { - /** - * Received the initial subscription creating NOTIFY in response to this request. - * Called for out of dialog SUBSCRIBE requests only (not called for re-SUBSCRIBE requests). - * @param request - Incoming NOTIFY request (including a Subscription). - */ - onNotify?(request: IncomingRequestWithSubscription): void; - /** - * Timed out waiting to receive the initial subscription creating NOTIFY in response to this request. - * Called for out of dialog SUBSCRIBE requests only (not called for re-SUBSCRIBE requests). - */ - onNotifyTimeout?(): void; -} -/** - * Incoming NOTIFY request with associated {@link Subscription}. - * @public - */ -export interface IncomingRequestWithSubscription { - /** The NOTIFY request which established the subscription. */ - readonly request: IncomingNotifyRequest; - /** If subscription state is not "terminated", then the subscription. Otherwise undefined. */ - readonly subscription?: Subscription; -} -//# sourceMappingURL=subscribe.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/methods/subscribe.d.ts.map b/lib/core/messages/methods/subscribe.d.ts.map deleted file mode 100644 index 6c028a615..000000000 --- a/lib/core/messages/methods/subscribe.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscribe.d.ts","sourceRoot":"","sources":["../../../../src/core/messages/methods/subscribe.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,eAAe;CAAG;AAEpE;;;GAGG;AACH,MAAM,WAAW,yBAA0B,SAAQ,gBAAgB;CAAG;AAEtE;;;GAGG;AACH,MAAM,WAAW,wBAAyB,SAAQ,eAAe;IAC/D,6EAA6E;IAC7E,QAAQ,CAAC,EAAE,gCAAgC,CAAC;IAC5C,+DAA+D;IAC/D,cAAc,IAAI,IAAI,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,gCAAiC,SAAQ,uBAAuB;IAC/E;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,+BAA+B,GAAG,IAAI,CAAC;IAE1D;;;OAGG;IACH,eAAe,CAAC,IAAI,IAAI,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,+BAA+B;IAC9C,6DAA6D;IAC7D,QAAQ,CAAC,OAAO,EAAE,qBAAqB,CAAC;IACxC,6FAA6F;IAC7F,QAAQ,CAAC,YAAY,CAAC,EAAE,YAAY,CAAC;CACtC"} \ No newline at end of file diff --git a/lib/core/messages/methods/subscribe.js b/lib/core/messages/methods/subscribe.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/outgoing-request-message.d.ts b/lib/core/messages/outgoing-request-message.d.ts deleted file mode 100644 index 5957a1b34..000000000 --- a/lib/core/messages/outgoing-request-message.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { NameAddrHeader, URI } from "../../grammar"; -import { Body } from "./body"; -/** - * Outgoing request message options. - * @public - */ -export interface OutgoingRequestMessageOptions { - callId?: string; - callIdPrefix?: string; - cseq?: number; - toDisplayName?: string; - toTag?: string; - fromDisplayName?: string; - fromTag?: string; - forceRport?: boolean; - hackViaTcp?: boolean; - optionTags?: Array; - routeSet?: Array; - userAgentString?: string; - viaHost?: string; -} -/** - * Outgoing SIP request message. - * @public - */ -export declare class OutgoingRequestMessage { - readonly headers: { - [name: string]: Array; - }; - readonly method: string; - readonly ruri: URI; - readonly from: NameAddrHeader; - readonly fromTag: string; - readonly fromURI: URI; - readonly to: NameAddrHeader; - readonly toTag: string | undefined; - readonly toURI: URI; - branch: string | undefined; - readonly callId: string; - cseq: number; - extraHeaders: Array; - body: { - body: string; - contentType: string; - } | undefined; - private options; - constructor(method: string, ruri: URI, fromURI: URI, toURI: URI, options?: OutgoingRequestMessageOptions, extraHeaders?: Array, body?: Body); - /** Get a copy of the default options. */ - private static getDefaultOptions; - private static makeNameAddrHeader; - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name: string): string | undefined; - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - getHeaders(name: string): Array; - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name: string): boolean; - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - setHeader(name: string, value: string | Array): void; - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param transport - The sent protocol transport. - */ - setViaHeader(branch: string, transport: string): void; - toString(): string; -} -//# sourceMappingURL=outgoing-request-message.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/outgoing-request-message.d.ts.map b/lib/core/messages/outgoing-request-message.d.ts.map deleted file mode 100644 index df46577f0..000000000 --- a/lib/core/messages/outgoing-request-message.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outgoing-request-message.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-request-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAG9B;;;GAGG;AACH,MAAM,WAAW,6BAA6B;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC3B,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,qBAAa,sBAAsB;IACjC,SAAgB,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAA;KAAE,CAAM;IAEhE,SAAgB,MAAM,EAAE,MAAM,CAAC;IAC/B,SAAgB,IAAI,EAAE,GAAG,CAAC;IAC1B,SAAgB,IAAI,EAAE,cAAc,CAAC;IACrC,SAAgB,OAAO,EAAE,MAAM,CAAC;IAChC,SAAgB,OAAO,EAAE,GAAG,CAAC;IAC7B,SAAgB,EAAE,EAAE,cAAc,CAAC;IACnC,SAAgB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,SAAgB,KAAK,EAAE,GAAG,CAAC;IACpB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,SAAgB,MAAM,EAAE,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,CAAM;IACjC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAE/D,OAAO,CAAC,OAAO,CAA0C;gBAGvD,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,GAAG,EACZ,KAAK,EAAE,GAAG,EACV,OAAO,CAAC,EAAE,6BAA6B,EACvC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAC5B,IAAI,CAAC,EAAE,IAAI;IAuEb,yCAAyC;IACzC,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAkBhC,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAQjC;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAkBlD;;;;OAIG;IACI,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAmB9C;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAevC;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI;IAInE;;;;;;;;;;;;;;;;OAgBG;IACI,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI;IAcrD,QAAQ,IAAI,MAAM;CAuC1B"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-request-message.js b/lib/core/messages/outgoing-request-message.js deleted file mode 100644 index 48d3c9c33..000000000 --- a/lib/core/messages/outgoing-request-message.js +++ /dev/null @@ -1,229 +0,0 @@ -import { NameAddrHeader } from "../../grammar"; -import { createRandomToken, headerize, newTag, utf8Length } from "./utils"; -/** - * Outgoing SIP request message. - * @public - */ -export class OutgoingRequestMessage { - constructor(method, ruri, fromURI, toURI, options, extraHeaders, body) { - this.headers = {}; - this.extraHeaders = []; - // Initialize default options - this.options = OutgoingRequestMessage.getDefaultOptions(); - // Options - merge a deep copy - if (options) { - this.options = Object.assign(Object.assign({}, this.options), options); - if (this.options.optionTags && this.options.optionTags.length) { - this.options.optionTags = this.options.optionTags.slice(); - } - if (this.options.routeSet && this.options.routeSet.length) { - this.options.routeSet = this.options.routeSet.slice(); - } - } - // Extra headers - deep copy - if (extraHeaders && extraHeaders.length) { - this.extraHeaders = extraHeaders.slice(); - } - // Body - deep copy - if (body) { - // TODO: internal representation should be Body - // this.body = { ...body }; - this.body = { - body: body.content, - contentType: body.contentType - }; - } - // Method - this.method = method; - // RURI - this.ruri = ruri.clone(); - // From - this.fromURI = fromURI.clone(); - this.fromTag = this.options.fromTag ? this.options.fromTag : newTag(); - this.from = OutgoingRequestMessage.makeNameAddrHeader(this.fromURI, this.options.fromDisplayName, this.fromTag); - // To - this.toURI = toURI.clone(); - this.toTag = this.options.toTag; - this.to = OutgoingRequestMessage.makeNameAddrHeader(this.toURI, this.options.toDisplayName, this.toTag); - // Call-ID - this.callId = this.options.callId ? this.options.callId : this.options.callIdPrefix + createRandomToken(15); - // CSeq - this.cseq = this.options.cseq; - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - this.setHeader("route", this.options.routeSet); - this.setHeader("via", ""); - this.setHeader("to", this.to.toString()); - this.setHeader("from", this.from.toString()); - this.setHeader("cseq", this.cseq + " " + this.method); - this.setHeader("call-id", this.callId); - this.setHeader("max-forwards", "70"); - } - /** Get a copy of the default options. */ - static getDefaultOptions() { - return { - callId: "", - callIdPrefix: "", - cseq: 1, - toDisplayName: "", - toTag: "", - fromDisplayName: "", - fromTag: "", - forceRport: false, - hackViaTcp: false, - optionTags: ["outbound"], - routeSet: [], - userAgentString: "sip.js", - viaHost: "" - }; - } - static makeNameAddrHeader(uri, displayName, tag) { - const parameters = {}; - if (tag) { - parameters.tag = tag; - } - return new NameAddrHeader(uri, displayName, parameters); - } - /** - * Get the value of the given header name at the given position. - * @param name - header name - * @returns Returns the specified header, undefined if header doesn't exist. - */ - getHeader(name) { - const header = this.headers[headerize(name)]; - if (header) { - if (header[0]) { - return header[0]; - } - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const exHeader of this.extraHeaders) { - if (regexp.test(exHeader)) { - return exHeader.substring(exHeader.indexOf(":") + 1).trim(); - } - } - } - return; - } - /** - * Get the header/s of the given name. - * @param name - header name - * @returns Array with all the headers of the specified name. - */ - getHeaders(name) { - const result = []; - const headerArray = this.headers[headerize(name)]; - if (headerArray) { - for (const headerPart of headerArray) { - result.push(headerPart); - } - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const exHeader of this.extraHeaders) { - if (regexp.test(exHeader)) { - result.push(exHeader.substring(exHeader.indexOf(":") + 1).trim()); - } - } - } - return result; - } - /** - * Verify the existence of the given header. - * @param name - header name - * @returns true if header with given name exists, false otherwise - */ - hasHeader(name) { - if (this.headers[headerize(name)]) { - return true; - } - else { - const regexp = new RegExp("^\\s*" + name + "\\s*:", "i"); - for (const extraHeader of this.extraHeaders) { - if (regexp.test(extraHeader)) { - return true; - } - } - } - return false; - } - /** - * Replace the the given header by the given value. - * @param name - header name - * @param value - header value - */ - setHeader(name, value) { - this.headers[headerize(name)] = value instanceof Array ? value : [value]; - } - /** - * The Via header field indicates the transport used for the transaction - * and identifies the location where the response is to be sent. A Via - * header field value is added only after the transport that will be - * used to reach the next hop has been selected (which may involve the - * usage of the procedures in [4]). - * - * When the UAC creates a request, it MUST insert a Via into that - * request. The protocol name and protocol version in the header field - * MUST be SIP and 2.0, respectively. The Via header field value MUST - * contain a branch parameter. This parameter is used to identify the - * transaction created by that request. This parameter is used by both - * the client and the server. - * https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - * @param branchParameter - The branch parameter. - * @param transport - The sent protocol transport. - */ - setViaHeader(branch, transport) { - // FIXME: Hack - if (this.options.hackViaTcp) { - transport = "TCP"; - } - let via = "SIP/2.0/" + transport; - via += " " + this.options.viaHost + ";branch=" + branch; - if (this.options.forceRport) { - via += ";rport"; - } - this.setHeader("via", via); - this.branch = branch; - } - toString() { - let msg = ""; - msg += this.method + " " + this.ruri.toRaw() + " SIP/2.0\r\n"; - for (const header in this.headers) { - if (this.headers[header]) { - for (const headerPart of this.headers[header]) { - msg += header + ": " + headerPart + "\r\n"; - } - } - } - for (const header of this.extraHeaders) { - msg += header.trim() + "\r\n"; - } - msg += "Supported: " + this.options.optionTags.join(", ") + "\r\n"; - msg += "User-Agent: " + this.options.userAgentString + "\r\n"; - if (this.body) { - if (typeof this.body === "string") { - msg += "Content-Length: " + utf8Length(this.body) + "\r\n\r\n"; - msg += this.body; - } - else { - if (this.body.body && this.body.contentType) { - msg += "Content-Type: " + this.body.contentType + "\r\n"; - msg += "Content-Length: " + utf8Length(this.body.body) + "\r\n\r\n"; - msg += this.body.body; - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - } - } - else { - msg += "Content-Length: " + 0 + "\r\n\r\n"; - } - return msg; - } -} diff --git a/lib/core/messages/outgoing-request.d.ts b/lib/core/messages/outgoing-request.d.ts deleted file mode 100644 index c88155faa..000000000 --- a/lib/core/messages/outgoing-request.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Body } from "./body"; -import { IncomingResponse } from "./incoming-response"; -import { OutgoingRequestMessage } from "./outgoing-request-message"; -/** - * A SIP message sent from a local client to a remote server. - * @remarks - * For the purpose of invoking a particular operation. - * https://tools.ietf.org/html/rfc3261#section-7.1 - * @public - */ -export interface OutgoingRequest { - /** Delegate providing custom handling of this outgoing request. */ - delegate?: OutgoingRequestDelegate; - /** The outgoing message. */ - readonly message: OutgoingRequestMessage; - /** - * Destroy request. - */ - dispose(): void; - /** - * Sends a CANCEL message targeting this request to the UAS. - * @param reason - Reason for canceling request. - * @param options - Request options bucket. - */ - cancel(reason?: string, options?: RequestOptions): void; -} -/** - * Delegate providing custom handling of outgoing requests. - * @public - */ -export interface OutgoingRequestDelegate { - /** - * Received a 2xx positive final response to this request. - * @param response - Incoming response. - */ - onAccept?(response: IncomingResponse): void; - /** - * Received a 1xx provisional response to this request. Excluding 100 responses. - * @param response - Incoming response. - */ - onProgress?(response: IncomingResponse): void; - /** - * Received a 3xx negative final response to this request. - * @param response - Incoming response. - */ - onRedirect?(response: IncomingResponse): void; - /** - * Received a 4xx, 5xx, or 6xx negative final response to this request. - * @param response - Incoming response. - */ - onReject?(response: IncomingResponse): void; - /** - * Received a 100 provisional response. - * @param response - Incoming response. - */ - onTrying?(response: IncomingResponse): void; -} -/** - * Request options bucket. - * @public - */ -export interface RequestOptions { - /** Extra headers to include in the message. */ - extraHeaders?: Array; - /** Body to include in the message. */ - body?: Body; -} -//# sourceMappingURL=outgoing-request.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/outgoing-request.d.ts.map b/lib/core/messages/outgoing-request.d.ts.map deleted file mode 100644 index 35d2e0d88..000000000 --- a/lib/core/messages/outgoing-request.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outgoing-request.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-request.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,mEAAmE;IACnE,QAAQ,CAAC,EAAE,uBAAuB,CAAC;IAEnC,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,sBAAsB,CAAC;IAEzC;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;;;OAIG;IACH,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CACzD;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,UAAU,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,UAAU,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAAC;CAC7C;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,sCAAsC;IACtC,IAAI,CAAC,EAAE,IAAI,CAAC;CACb"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-request.js b/lib/core/messages/outgoing-request.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/messages/outgoing-response.d.ts b/lib/core/messages/outgoing-response.d.ts deleted file mode 100644 index cae196ed8..000000000 --- a/lib/core/messages/outgoing-response.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Body } from "./body"; -import { IncomingRequestMessage } from "./incoming-request-message"; -/** - * A SIP message sent from a local server to a remote client. - * @remarks - * For indicating the status of a request sent from the client to the server. - * https://tools.ietf.org/html/rfc3261#section-7.2 - * @public - */ -export interface OutgoingResponse { - /** The outgoing message. */ - readonly message: string; -} -/** - * Response options bucket. - * @public - */ -export interface ResponseOptions { - /** Status code of the response. */ - statusCode: number; - /** Reason phrase of the response. */ - reasonPhrase?: string; - /** To tag of the response. If not provided, one is generated. */ - toTag?: string; - /** User agent string for User-Agent header. */ - userAgent?: string; - /** Support options tags for Supported header. */ - supported?: Array; - /** Extra headers to include in the message. */ - extraHeaders?: Array; - /** Body to include in the message. */ - body?: Body; -} -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -export declare function constructOutgoingResponse(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse; -//# sourceMappingURL=outgoing-response.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/outgoing-response.d.ts.map b/lib/core/messages/outgoing-response.d.ts.map deleted file mode 100644 index 2e5601c2b..000000000 --- a/lib/core/messages/outgoing-response.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outgoing-response.d.ts","sourceRoot":"","sources":["../../../src/core/messages/outgoing-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAGpE;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4BAA4B;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,mCAAmC;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,qCAAqC;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,SAAS,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1B,+CAA+C;IAC/C,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,sCAAsC;IACtC,IAAI,CAAC,EAAE,IAAI,CAAC;CACb;AAED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,eAAe,GAAG,gBAAgB,CAgIrH"} \ No newline at end of file diff --git a/lib/core/messages/outgoing-response.js b/lib/core/messages/outgoing-response.js deleted file mode 100644 index c1fcb2009..000000000 --- a/lib/core/messages/outgoing-response.js +++ /dev/null @@ -1,126 +0,0 @@ -import { getReasonPhrase, newTag, utf8Length } from "./utils"; -/** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @internal - */ -export function constructOutgoingResponse(message, options) { - const CRLF = "\r\n"; - if (options.statusCode < 100 || options.statusCode > 699) { - throw new TypeError("Invalid statusCode: " + options.statusCode); - } - const reasonPhrase = options.reasonPhrase ? options.reasonPhrase : getReasonPhrase(options.statusCode); - // SIP responses are distinguished from requests by having a Status-Line - // as their start-line. A Status-Line consists of the protocol version - // followed by a numeric Status-Code and its associated textual phrase, - // with each element separated by a single SP character. - // https://tools.ietf.org/html/rfc3261#section-7.2 - let response = "SIP/2.0 " + options.statusCode + " " + reasonPhrase + CRLF; - // One largely non-method-specific guideline for the generation of - // responses is that UASs SHOULD NOT issue a provisional response for a - // non-INVITE request. Rather, UASs SHOULD generate a final response to - // a non-INVITE request as soon as possible. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode >= 100 && options.statusCode < 200) { - // TODO - } - // When a 100 (Trying) response is generated, any Timestamp header field - // present in the request MUST be copied into this 100 (Trying) - // response. If there is a delay in generating the response, the UAS - // SHOULD add a delay value into the Timestamp value in the response. - // This value MUST contain the difference between the time of sending of - // the response and receipt of the request, measured in seconds. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.1 - if (options.statusCode === 100) { - // TODO - } - // The From field of the response MUST equal the From header field of - // the request. The Call-ID header field of the response MUST equal the - // Call-ID header field of the request. The CSeq header field of the - // response MUST equal the CSeq field of the request. The Via header - // field values in the response MUST equal the Via header field values - // in the request and MUST maintain the same ordering. - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - const fromHeader = "From: " + message.getHeader("From") + CRLF; - const callIdHeader = "Call-ID: " + message.callId + CRLF; - const cSeqHeader = "CSeq: " + message.cseq + " " + message.method + CRLF; - const viaHeaders = message.getHeaders("via").reduce((previous, current) => { - return previous + "Via: " + current + CRLF; - }, ""); - // If a request contained a To tag in the request, the To header field - // in the response MUST equal that of the request. However, if the To - // header field in the request did not contain a tag, the URI in the To - // header field in the response MUST equal the URI in the To header - // field; additionally, the UAS MUST add a tag to the To header field in - // the response (with the exception of the 100 (Trying) response, in - // which a tag MAY be present). This serves to identify the UAS that is - // responding, possibly resulting in a component of a dialog ID. The - // same tag MUST be used for all responses to that request, both final - // and provisional (again excepting the 100 (Trying)). - // https://tools.ietf.org/html/rfc3261#section-8.2.6.2 - let toHeader = "To: " + message.getHeader("to"); - if (options.statusCode > 100 && !message.parseHeader("to").hasParam("tag")) { - let toTag = options.toTag; - if (!toTag) { - // Stateless UAS Behavior... - // o To header tags MUST be generated for responses in a stateless - // manner - in a manner that will generate the same tag for the - // same request consistently. For information on tag construction - // see Section 19.3. - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - toTag = newTag(); // FIXME: newTag() currently generates random tags - } - toHeader += ";tag=" + toTag; - } - toHeader += CRLF; - // FIXME: TODO: needs review... moved to InviteUserAgentServer (as it is specific to that) - // let recordRouteHeaders = ""; - // if (request.method === C.INVITE && statusCode > 100 && statusCode <= 200) { - // recordRouteHeaders = request.getHeaders("record-route").reduce((previous, current) => { - // return previous + "Record-Route: " + current + CRLF; - // }, ""); - // } - // FIXME: TODO: needs review... - let supportedHeader = ""; - if (options.supported) { - supportedHeader = "Supported: " + options.supported.join(", ") + CRLF; - } - // FIXME: TODO: needs review... - let userAgentHeader = ""; - if (options.userAgent) { - userAgentHeader = "User-Agent: " + options.userAgent + CRLF; - } - let extensionHeaders = ""; - if (options.extraHeaders) { - extensionHeaders = options.extraHeaders.reduce((previous, current) => { - return previous + current.trim() + CRLF; - }, ""); - } - // The relative order of header fields with different field names is not - // significant. However, it is RECOMMENDED that header fields which are - // needed for proxy processing (Via, Route, Record-Route, Proxy-Require, - // Max-Forwards, and Proxy-Authorization, for example) appear towards - // the top of the message to facilitate rapid parsing. - // https://tools.ietf.org/html/rfc3261#section-7.3.1 - // response += recordRouteHeaders; - response += viaHeaders; - response += fromHeader; - response += toHeader; - response += cSeqHeader; - response += callIdHeader; - response += supportedHeader; - response += userAgentHeader; - response += extensionHeaders; - if (options.body) { - response += "Content-Type: " + options.body.contentType + CRLF; - response += "Content-Length: " + utf8Length(options.body.content) + CRLF + CRLF; - response += options.body.content; - } - else { - response += "Content-Length: " + 0 + CRLF + CRLF; - } - return { message: response }; -} diff --git a/lib/core/messages/parser.d.ts b/lib/core/messages/parser.d.ts deleted file mode 100644 index af603be99..000000000 --- a/lib/core/messages/parser.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Logger } from "../log/logger"; -import { IncomingRequestMessage } from "./incoming-request-message"; -import { IncomingResponseMessage } from "./incoming-response-message"; -/** - * Extract and parse every header of a SIP message. - * @internal - */ -export declare namespace Parser { - function getHeader(data: any, headerStart: number): number; - function parseHeader(message: IncomingRequestMessage | IncomingResponseMessage, data: any, headerStart: number, headerEnd: number): boolean | { - error: string; - }; - function parseMessage(data: string, logger: Logger): IncomingRequestMessage | IncomingResponseMessage | undefined; -} -//# sourceMappingURL=parser.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/parser.d.ts.map b/lib/core/messages/parser.d.ts.map deleted file mode 100644 index 5279a9f5c..000000000 --- a/lib/core/messages/parser.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../src/core/messages/parser.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAEtE;;;GAGG;AACH,yBAAiB,MAAM,CAAC;IAEtB,SAAgB,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAkChE;IAED,SAAgB,WAAW,CACzB,OAAO,EAAE,sBAAsB,GAAG,uBAAuB,EAEzD,IAAI,EAAE,GAAG,EACT,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,GAChB,OAAO,GAAG;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAwI7B;IAED,SAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,sBAAsB,GAAG,uBAAuB,GAAG,SAAS,CAmE9D;CACF"} \ No newline at end of file diff --git a/lib/core/messages/parser.js b/lib/core/messages/parser.js deleted file mode 100644 index 34ff67de3..000000000 --- a/lib/core/messages/parser.js +++ /dev/null @@ -1,241 +0,0 @@ -/* eslint-disable no-inner-declarations */ -/* eslint-disable @typescript-eslint/no-namespace */ -import { Grammar } from "../../grammar"; -import { IncomingRequestMessage } from "./incoming-request-message"; -import { IncomingResponseMessage } from "./incoming-response-message"; -/** - * Extract and parse every header of a SIP message. - * @internal - */ -export var Parser; -(function (Parser) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function getHeader(data, headerStart) { - // 'start' position of the header. - let start = headerStart; - // 'end' position of the header. - let end = 0; - // 'partial end' position of the header. - let partialEnd = 0; - // End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - while (end === 0) { - // Partial End of Header. - partialEnd = data.indexOf("\r\n", start); - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && - data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } - else { - end = partialEnd; - } - } - return end; - } - Parser.getHeader = getHeader; - function parseHeader(message, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, headerStart, headerEnd) { - const hcolonIndex = data.indexOf(":", headerStart); - const headerName = data.substring(headerStart, hcolonIndex).trim(); - const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let parsed; - // If header-field is well-known, parse it. - switch (headerName.toLowerCase()) { - case "via": - case "v": - message.addHeader("via", headerValue); - if (message.getHeaders("via").length === 1) { - parsed = message.parseHeader("Via"); - if (parsed) { - message.via = parsed; - message.viaBranch = parsed.branch; - } - } - else { - parsed = 0; - } - break; - case "from": - case "f": - message.setHeader("from", headerValue); - parsed = message.parseHeader("from"); - if (parsed) { - message.from = parsed; - message.fromTag = parsed.getParam("tag"); - } - break; - case "to": - case "t": - message.setHeader("to", headerValue); - parsed = message.parseHeader("to"); - if (parsed) { - message.to = parsed; - message.toTag = parsed.getParam("tag"); - } - break; - case "record-route": - parsed = Grammar.parse(headerValue, "Record_Route"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach((header) => { - message.addHeader("record-route", headerValue.substring(header.position, header.offset)); - message.headers["Record-Route"][message.getHeaders("record-route").length - 1].parsed = header.parsed; - }); - break; - case "call-id": - case "i": - message.setHeader("call-id", headerValue); - parsed = message.parseHeader("call-id"); - if (parsed) { - message.callId = headerValue; - } - break; - case "contact": - case "m": - parsed = Grammar.parse(headerValue, "Contact"); - if (parsed === -1) { - parsed = undefined; - break; - } - if (!(parsed instanceof Array)) { - parsed = undefined; - break; - } - parsed.forEach((header) => { - message.addHeader("contact", headerValue.substring(header.position, header.offset)); - message.headers.Contact[message.getHeaders("contact").length - 1].parsed = header.parsed; - }); - break; - case "content-length": - case "l": - message.setHeader("content-length", headerValue); - parsed = message.parseHeader("content-length"); - break; - case "content-type": - case "c": - message.setHeader("content-type", headerValue); - parsed = message.parseHeader("content-type"); - break; - case "cseq": - message.setHeader("cseq", headerValue); - parsed = message.parseHeader("cseq"); - if (parsed) { - message.cseq = parsed.value; - } - if (message instanceof IncomingResponseMessage) { - message.method = parsed.method; - } - break; - case "max-forwards": - message.setHeader("max-forwards", headerValue); - parsed = message.parseHeader("max-forwards"); - break; - case "www-authenticate": - message.setHeader("www-authenticate", headerValue); - parsed = message.parseHeader("www-authenticate"); - break; - case "proxy-authenticate": - message.setHeader("proxy-authenticate", headerValue); - parsed = message.parseHeader("proxy-authenticate"); - break; - case "refer-to": - case "r": - message.setHeader("refer-to", headerValue); - parsed = message.parseHeader("refer-to"); - if (parsed) { - message.referTo = parsed; - } - break; - default: - // Do not parse this header. - message.addHeader(headerName.toLowerCase(), headerValue); - parsed = 0; - } - if (parsed === undefined) { - return { - error: "error parsing header '" + headerName + "'" - }; - } - else { - return true; - } - } - Parser.parseHeader = parseHeader; - function parseMessage(data, logger) { - let headerStart = 0; - let headerEnd = data.indexOf("\r\n"); - if (headerEnd === -1) { - logger.warn("no CRLF found, not a SIP message, discarded"); - return; - } - // Parse first line. Check if it is a Request or a Reply. - const firstLine = data.substring(0, headerEnd); - const parsed = Grammar.parse(firstLine, "Request_Response"); - let message; - if (parsed === -1) { - logger.warn('error parsing first line of SIP message: "' + firstLine + '"'); - return; - } - else if (!parsed.status_code) { - message = new IncomingRequestMessage(); - message.method = parsed.method; - message.ruri = parsed.uri; - } - else { - message = new IncomingResponseMessage(); - message.statusCode = parsed.status_code; - message.reasonPhrase = parsed.reason_phrase; - } - message.data = data; - headerStart = headerEnd + 2; - // Loop over every line in data. Detect the end of each header and parse - // it or simply add to the headers collection. - let bodyStart; - // eslint-disable-next-line no-constant-condition - while (true) { - headerEnd = getHeader(data, headerStart); - // The SIP message has normally finished. - if (headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - else if (headerEnd === -1) { - // data.indexOf returned -1 due to a malformed message. - logger.error("malformed message"); - return; - } - const parsedHeader = parseHeader(message, data, headerStart, headerEnd); - if (parsedHeader !== true) { - logger.error(parsed.error); - return; - } - headerStart = headerEnd + 2; - } - // RFC3261 18.3. - // If there are additional bytes in the transport packet - // beyond the end of the body, they MUST be discarded. - if (message.hasHeader("content-length")) { - message.body = data.substr(bodyStart, Number(message.getHeader("content-length"))); - } - else { - message.body = data.substring(bodyStart); - } - return message; - } - Parser.parseMessage = parseMessage; -})(Parser || (Parser = {})); diff --git a/lib/core/messages/utils.d.ts b/lib/core/messages/utils.d.ts deleted file mode 100644 index 11b08deff..000000000 --- a/lib/core/messages/utils.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @param size - - * @param base - - * @internal - */ -export declare function createRandomToken(size: number, base?: number): string; -/** - * @internal - */ -export declare function getReasonPhrase(code: number): string; -/** - * @internal - */ -export declare function newTag(): string; -/** - * @param str - - * @internal - */ -export declare function headerize(str: string): string; -/** - * @param str - - * @internal - */ -export declare function utf8Length(str: string): number; -//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/lib/core/messages/utils.d.ts.map b/lib/core/messages/utils.d.ts.map deleted file mode 100644 index d646f66dd..000000000 --- a/lib/core/messages/utils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/messages/utils.ts"],"names":[],"mappings":"AA+EA;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,SAAK,GAAG,MAAM,CAOjE;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED;;GAEG;AACH,wBAAgB,MAAM,IAAI,MAAM,CAE/B;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAwB7C;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE9C"} \ No newline at end of file diff --git a/lib/core/messages/utils.js b/lib/core/messages/utils.js deleted file mode 100644 index 1838a9308..000000000 --- a/lib/core/messages/utils.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * @internal - */ -const REASON_PHRASE = { - 100: "Trying", - 180: "Ringing", - 181: "Call Is Being Forwarded", - 182: "Queued", - 183: "Session Progress", - 199: "Early Dialog Terminated", - 200: "OK", - 202: "Accepted", - 204: "No Notification", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Moved Temporarily", - 305: "Use Proxy", - 380: "Alternative Service", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 410: "Gone", - 412: "Conditional Request Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Unsupported URI Scheme", - 417: "Unknown Resource-Priority", - 420: "Bad Extension", - 421: "Extension Required", - 422: "Session Interval Too Small", - 423: "Interval Too Brief", - 428: "Use Identity Header", - 429: "Provide Referrer Identity", - 430: "Flow Failed", - 433: "Anonymity Disallowed", - 436: "Bad Identity-Info", - 437: "Unsupported Certificate", - 438: "Invalid Identity Header", - 439: "First Hop Lacks Outbound Support", - 440: "Max-Breadth Exceeded", - 469: "Bad Info Package", - 470: "Consent Needed", - 478: "Unresolvable Destination", - 480: "Temporarily Unavailable", - 481: "Call/Transaction Does Not Exist", - 482: "Loop Detected", - 483: "Too Many Hops", - 484: "Address Incomplete", - 485: "Ambiguous", - 486: "Busy Here", - 487: "Request Terminated", - 488: "Not Acceptable Here", - 489: "Bad Event", - 491: "Request Pending", - 493: "Undecipherable", - 494: "Security Agreement Required", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Server Time-out", - 505: "Version Not Supported", - 513: "Message Too Large", - 580: "Precondition Failure", - 600: "Busy Everywhere", - 603: "Decline", - 604: "Does Not Exist Anywhere", - 606: "Not Acceptable" -}; -/** - * @param size - - * @param base - - * @internal - */ -export function createRandomToken(size, base = 32) { - let token = ""; - for (let i = 0; i < size; i++) { - const r = Math.floor(Math.random() * base); - token += r.toString(base); - } - return token; -} -/** - * @internal - */ -export function getReasonPhrase(code) { - return REASON_PHRASE[code] || ""; -} -/** - * @internal - */ -export function newTag() { - return createRandomToken(10); -} -/** - * @param str - - * @internal - */ -export function headerize(str) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const exceptions = { - "Call-Id": "Call-ID", - Cseq: "CSeq", - "Min-Se": "Min-SE", - Rack: "RAck", - Rseq: "RSeq", - "Www-Authenticate": "WWW-Authenticate" - }; - const name = str.toLowerCase().replace(/_/g, "-").split("-"); - const parts = name.length; - let hname = ""; - for (let part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -} -/** - * @param str - - * @internal - */ -export function utf8Length(str) { - return encodeURIComponent(str).replace(/%[A-F\d]{2}/g, "U").length; -} diff --git a/lib/core/session/index.d.ts b/lib/core/session/index.d.ts deleted file mode 100644 index 27ebc6836..000000000 --- a/lib/core/session/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./session"; -export * from "./session-delegate"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/session/index.d.ts.map b/lib/core/session/index.d.ts.map deleted file mode 100644 index e32c4cc66..000000000 --- a/lib/core/session/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/session/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC"} \ No newline at end of file diff --git a/lib/core/session/index.js b/lib/core/session/index.js deleted file mode 100644 index 765f8ba7f..000000000 --- a/lib/core/session/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./session"; -export * from "./session-delegate"; diff --git a/lib/core/session/session-delegate.d.ts b/lib/core/session/session-delegate.d.ts deleted file mode 100644 index c58b48d62..000000000 --- a/lib/core/session/session-delegate.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { IncomingAckRequest, IncomingByeRequest, IncomingInfoRequest, IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingPrackRequest, IncomingReferRequest } from "../messages"; -/** - * Session delegate. - * @public - */ -export interface SessionDelegate { - /** - * Receive ACK request. - * @param request - Incoming ACK request. - * @returns - * The callback MUST return a promise if it asynchronously handles answers. - * For example, an ACK with an answer (offer in the 200 Ok) may require - * asynchronous processing in which case the callback MUST return a Promise - * which resolves when the answer handling is complete. - * @privateRemarks - * Unlike INVITE handling where we can rely on the generation of a response - * to indicate when offer/answer processing has been completed, ACK handling - * requires some indication from the handler that answer processing is complete - * so that we can avoid some race conditions (see comments in code for more details). - * Having the handler return a Promise provides said indication. - */ - onAck?(request: IncomingAckRequest): Promise | void; - /** - * Timeout waiting for ACK request. - * If no handler is provided the Session will terminated with a BYE. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - */ - onAckTimeout?(): void; - /** - * Receive BYE request. - * https://tools.ietf.org/html/rfc3261#section-15.1.2 - * @param request - Incoming BYE request. - */ - onBye?(request: IncomingByeRequest): void; - /** - * Receive INFO request. - * @param request - Incoming INFO request. - */ - onInfo?(request: IncomingInfoRequest): void; - /** - * Receive re-INVITE request. - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @param request - Incoming INVITE request. - */ - onInvite?(request: IncomingInviteRequest): void; - /** - * Receive MESSAGE request. - * https://tools.ietf.org/html/rfc3428#section-7 - * @param request - Incoming MESSAGE request. - */ - onMessage?(request: IncomingMessageRequest): void; - /** - * Receive NOTIFY request. - * https://tools.ietf.org/html/rfc6665#section-4.1.3 - * @param request - Incoming NOTIFY request. - */ - onNotify?(request: IncomingNotifyRequest): void; - /** - * Receive PRACK request. - * https://tools.ietf.org/html/rfc3262#section-3 - * @param request - Incoming PRACK request. - */ - onPrack?(request: IncomingPrackRequest): void; - /** - * Receive REFER request. - * https://tools.ietf.org/html/rfc3515#section-2.4.2 - * @param request - Incoming REFER request. - */ - onRefer?(request: IncomingReferRequest): void; -} -//# sourceMappingURL=session-delegate.d.ts.map \ No newline at end of file diff --git a/lib/core/session/session-delegate.d.ts.map b/lib/core/session/session-delegate.d.ts.map deleted file mode 100644 index 6593f0ab4..000000000 --- a/lib/core/session/session-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-delegate.d.ts","sourceRoot":"","sources":["../../../src/core/session/session-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAE1D;;;;OAIG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;IAEtB;;;;OAIG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAE1C;;;OAGG;IACH,MAAM,CAAC,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAE5C;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;;OAIG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAElD;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;;OAIG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAE9C;;;;OAIG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;CAC/C"} \ No newline at end of file diff --git a/lib/core/session/session-delegate.js b/lib/core/session/session-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/session/session.d.ts b/lib/core/session/session.d.ts deleted file mode 100644 index bd6a67ccd..000000000 --- a/lib/core/session/session.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { Body, OutgoingByeRequest, OutgoingInfoRequest, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, OutgoingNotifyRequest, OutgoingPrackRequest, OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions, URI } from "../messages"; -import { SessionDelegate } from "./session-delegate"; -/** - * Session. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -export interface Session { - /** Session delegate. */ - delegate: SessionDelegate | undefined; - /** The session id. Equal to callId + localTag + remoteTag. */ - readonly id: string; - /** Call Id. */ - readonly callId: string; - /** Local Tag. */ - readonly localTag: string; - /** Local URI. */ - readonly localURI: URI; - /** Remote Tag. */ - readonly remoteTag: string; - /** Remote Target. */ - readonly remoteTarget: URI; - /** Remote URI. */ - readonly remoteURI: URI; - /** Session state. */ - readonly sessionState: SessionState; - /** Current state of the offer/answer exchange. */ - readonly signalingState: SignalingState; - /** The current answer if signalingState is stable. Otherwise undefined. */ - readonly answer: Body | undefined; - /** The current offer if signalingState is not initial or closed. Otherwise undefined. */ - readonly offer: Body | undefined; - /** - * Destroy session. - */ - dispose(): void; - /** - * Send a BYE request. - * Terminating a session. - * https://tools.ietf.org/html/rfc3261#section-15 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest; - /** - * Send an INFO request. - * Exchange information during a session. - * https://tools.ietf.org/html/rfc6086#section-4.2.1 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest; - /** - * Send re-INVITE request. - * Modifying a session. - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest; - /** - * Send MESSAGE request. - * Deliver a message during a session. - * https://tools.ietf.org/html/rfc3428#section-4 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - message(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingMessageRequest; - /** - * Send NOTIFY request. - * Inform referrer of transfer progress. - * The use of this is limited to the implicit creation of subscription by REFER (historical). - * Otherwise, notifiers MUST NOT create subscriptions except upon receipt of a SUBSCRIBE request. - * https://tools.ietf.org/html/rfc3515#section-3.7 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest; - /** - * Send PRACK request. - * Acknowledge a reliable provisional response. - * https://tools.ietf.org/html/rfc3262#section-4 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest; - /** - * Send REFER request. - * Transfer a session. - * https://tools.ietf.org/html/rfc3515#section-2.4.1 - * @param delegate - Request delegate. - * @param options - Options bucket. - */ - refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest; -} -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -export declare enum SessionState { - Initial = "Initial", - Early = "Early", - AckWait = "AckWait", - Confirmed = "Confirmed", - Terminated = "Terminated" -} -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -export declare enum SignalingState { - Initial = "Initial", - HaveLocalOffer = "HaveLocalOffer", - HaveRemoteOffer = "HaveRemoteOffer", - Stable = "Stable", - Closed = "Closed" -} -//# sourceMappingURL=session.d.ts.map \ No newline at end of file diff --git a/lib/core/session/session.d.ts.map b/lib/core/session/session.d.ts.map deleted file mode 100644 index 01a0e41e6..000000000 --- a/lib/core/session/session.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/core/session/session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,6BAA6B,EAC7B,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACvB,cAAc,EACd,GAAG,EACJ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,WAAW,OAAO;IACtB,wBAAwB;IACxB,QAAQ,EAAE,eAAe,GAAG,SAAS,CAAC;IACtC,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,eAAe;IACf,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iBAAiB;IACjB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,iBAAiB;IACjB,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC;IACvB,kBAAkB;IAClB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,qBAAqB;IACrB,QAAQ,CAAC,YAAY,EAAE,GAAG,CAAC;IAC3B,kBAAkB;IAClB,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC;IACxB,qBAAqB;IACrB,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC;IACpC,kDAAkD;IAClD,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE,IAAI,GAAG,SAAS,CAAC;IAClC,yFAAyF;IACzF,QAAQ,CAAC,KAAK,EAAE,IAAI,GAAG,SAAS,CAAC;IAEjC;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;;;;;OAMG;IACH,GAAG,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,kBAAkB,CAAC;IAEtF;;;;;;OAMG;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,mBAAmB,CAAC;IAExF;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,CAAC,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB,CAAC;IAElG;;;;;;OAMG;IACH,OAAO,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,sBAAsB,CAAC;IAE9F;;;;;;;;OAQG;IACH,MAAM,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,qBAAqB,CAAC;IAE5F;;;;;;OAMG;IACH,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB,CAAC;IAE1F;;;;;;OAMG;IACH,KAAK,CAAC,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,oBAAoB,CAAC;CAC3F;AAED;;;;;GAKG;AACH,oBAAY,YAAY;IACtB,OAAO,YAAY;IACnB,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,UAAU,eAAe;CAC1B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,cAAc,mBAAmB;IACjC,eAAe,oBAAoB;IACnC,MAAM,WAAW;IACjB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/lib/core/session/session.js b/lib/core/session/session.js deleted file mode 100644 index 688c65a7c..000000000 --- a/lib/core/session/session.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Session state. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-13 - * @public - */ -export var SessionState; -(function (SessionState) { - SessionState["Initial"] = "Initial"; - SessionState["Early"] = "Early"; - SessionState["AckWait"] = "AckWait"; - SessionState["Confirmed"] = "Confirmed"; - SessionState["Terminated"] = "Terminated"; -})(SessionState || (SessionState = {})); -/** - * Offer/Answer state. - * @remarks - * ```txt - * Offer Answer RFC Ini Est Early - * ------------------------------------------------------------------- - * 1. INVITE Req. 2xx INVITE Resp. RFC 3261 Y Y N - * 2. 2xx INVITE Resp. ACK Req. RFC 3261 Y Y N - * 3. INVITE Req. 1xx-rel INVITE Resp. RFC 3262 Y Y N - * 4. 1xx-rel INVITE Resp. PRACK Req. RFC 3262 Y Y N - * 5. PRACK Req. 200 PRACK Resp. RFC 3262 N Y Y - * 6. UPDATE Req. 2xx UPDATE Resp. RFC 3311 N Y Y - * - * Table 1: Summary of SIP Usage of the Offer/Answer Model - * ``` - * https://tools.ietf.org/html/rfc6337#section-2.2 - * @public - */ -export var SignalingState; -(function (SignalingState) { - SignalingState["Initial"] = "Initial"; - SignalingState["HaveLocalOffer"] = "HaveLocalOffer"; - SignalingState["HaveRemoteOffer"] = "HaveRemoteOffer"; - SignalingState["Stable"] = "Stable"; - SignalingState["Closed"] = "Closed"; -})(SignalingState || (SignalingState = {})); diff --git a/lib/core/subscription/index.d.ts b/lib/core/subscription/index.d.ts deleted file mode 100644 index 1c22343d6..000000000 --- a/lib/core/subscription/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./subscription"; -export * from "./subscription-delegate"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/subscription/index.d.ts.map b/lib/core/subscription/index.d.ts.map deleted file mode 100644 index 8ddb57378..000000000 --- a/lib/core/subscription/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,yBAAyB,CAAC"} \ No newline at end of file diff --git a/lib/core/subscription/index.js b/lib/core/subscription/index.js deleted file mode 100644 index 28f539cf8..000000000 --- a/lib/core/subscription/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./subscription"; -export * from "./subscription-delegate"; diff --git a/lib/core/subscription/subscription-delegate.d.ts b/lib/core/subscription/subscription-delegate.d.ts deleted file mode 100644 index 33bd060f2..000000000 --- a/lib/core/subscription/subscription-delegate.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { IncomingNotifyRequest, OutgoingSubscribeRequest } from "../messages"; -/** - * Subscription delegate. - * @public - */ -export interface SubscriptionDelegate { - /** - * Receive NOTIFY request. This includes in dialog NOTIFY requests only. - * Thus the first NOTIFY (the subscription creating NOTIFY) will not be provided. - * https://tools.ietf.org/html/rfc6665#section-4.1.3 - * @param request - Incoming NOTIFY request. - */ - onNotify?(request: IncomingNotifyRequest): void; - /** - * Sent a SUBSCRIBE request. This includes "auto refresh" in dialog SUBSCRIBE requests only. - * Thus SUBSCRIBE requests triggered by calls to `refresh()` or `subscribe()` will not be provided. - * Thus the first SUBSCRIBE (the subscription creating SUBSCRIBE) will not be provided. - * @param request - Outgoing SUBSCRIBE request. - */ - onRefresh?(request: OutgoingSubscribeRequest): void; - /** - * Subscription termination. This includes non-NOTIFY termination causes only. - * Thus this will not be called if a NOTIFY is the cause of termination. - * https://tools.ietf.org/html/rfc6665#section-4.4.1 - */ - onTerminated?(): void; -} -//# sourceMappingURL=subscription-delegate.d.ts.map \ No newline at end of file diff --git a/lib/core/subscription/subscription-delegate.d.ts.map b/lib/core/subscription/subscription-delegate.d.ts.map deleted file mode 100644 index 7dae89514..000000000 --- a/lib/core/subscription/subscription-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription-delegate.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/subscription-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAE9E;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;;OAKG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;;;OAKG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI,CAAC;IAEpD;;;;OAIG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;CACvB"} \ No newline at end of file diff --git a/lib/core/subscription/subscription-delegate.js b/lib/core/subscription/subscription-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/subscription/subscription.d.ts b/lib/core/subscription/subscription.d.ts deleted file mode 100644 index e05f64883..000000000 --- a/lib/core/subscription/subscription.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, RequestOptions } from "../messages"; -import { SubscriptionDelegate } from "./subscription-delegate"; -/** - * Subscription. - * @remarks - * https://tools.ietf.org/html/rfc6665 - * @public - */ -export interface Subscription { - /** Subscription delegate. */ - delegate: SubscriptionDelegate | undefined; - /** The subscription id. */ - readonly id: string; - /** Subscription expires. Number of seconds until the subscription expires. */ - readonly subscriptionExpires: number; - /** Subscription state. */ - readonly subscriptionState: SubscriptionState; - /** If true, refresh subscription prior to expiration. Default is false. */ - autoRefresh: boolean; - /** - * Destroy subscription. - */ - dispose(): void; - /** - * Send re-SUBSCRIBE request. - * Refreshing a subscription and unsubscribing. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - * @param delegate - Request delegate. - * @param options - Options bucket - */ - subscribe(delegate?: OutgoingSubscribeRequestDelegate, options?: RequestOptions): OutgoingSubscribeRequest; - /** - * 4.1.2.2. Refreshing of Subscriptions - * https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - */ - refresh(): OutgoingSubscribeRequest; - /** - * 4.1.2.3. Unsubscribing - * https://tools.ietf.org/html/rfc6665#section-4.1.2.3 - */ - unsubscribe(): OutgoingSubscribeRequest; -} -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -export declare enum SubscriptionState { - Initial = "Initial", - NotifyWait = "NotifyWait", - Pending = "Pending", - Active = "Active", - Terminated = "Terminated" -} -//# sourceMappingURL=subscription.d.ts.map \ No newline at end of file diff --git a/lib/core/subscription/subscription.d.ts.map b/lib/core/subscription/subscription.d.ts.map deleted file mode 100644 index 9bef75cc1..000000000 --- a/lib/core/subscription/subscription.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../../src/core/subscription/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,gCAAgC,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACzG,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B,6BAA6B;IAC7B,QAAQ,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAC3C,2BAA2B;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,0BAA0B;IAC1B,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAC9C,2EAA2E;IAC3E,WAAW,EAAE,OAAO,CAAC;IAErB;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;;;;;OAMG;IACH,SAAS,CAAC,QAAQ,CAAC,EAAE,gCAAgC,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,wBAAwB,CAAC;IAE3G;;;OAGG;IACH,OAAO,IAAI,wBAAwB,CAAC;IAEpC;;;OAGG;IACH,WAAW,IAAI,wBAAwB,CAAC;CACzC;AAED;;;;;GAKG;AACH,oBAAY,iBAAiB;IAC3B,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,UAAU,eAAe;CAC1B"} \ No newline at end of file diff --git a/lib/core/subscription/subscription.js b/lib/core/subscription/subscription.js deleted file mode 100644 index 4d7281d0f..000000000 --- a/lib/core/subscription/subscription.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Subscription state. - * @remarks - * https://tools.ietf.org/html/rfc6665#section-4.1.2 - * @public - */ -export var SubscriptionState; -(function (SubscriptionState) { - SubscriptionState["Initial"] = "Initial"; - SubscriptionState["NotifyWait"] = "NotifyWait"; - SubscriptionState["Pending"] = "Pending"; - SubscriptionState["Active"] = "Active"; - SubscriptionState["Terminated"] = "Terminated"; -})(SubscriptionState || (SubscriptionState = {})); diff --git a/lib/core/timers.d.ts b/lib/core/timers.d.ts deleted file mode 100644 index 70dda6301..000000000 --- a/lib/core/timers.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Timers. - * @public - */ -export declare const Timers: { - T1: number; - T2: number; - T4: number; - TIMER_B: number; - TIMER_D: number; - TIMER_F: number; - TIMER_H: number; - TIMER_I: number; - TIMER_J: number; - TIMER_K: number; - TIMER_L: number; - TIMER_M: number; - TIMER_N: number; - PROVISIONAL_RESPONSE_INTERVAL: number; -}; -//# sourceMappingURL=timers.d.ts.map \ No newline at end of file diff --git a/lib/core/timers.d.ts.map b/lib/core/timers.d.ts.map deleted file mode 100644 index a1d612df2..000000000 --- a/lib/core/timers.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"timers.d.ts","sourceRoot":"","sources":["../../src/core/timers.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;CAelB,CAAC"} \ No newline at end of file diff --git a/lib/core/timers.js b/lib/core/timers.js deleted file mode 100644 index 6f1cd7d0f..000000000 --- a/lib/core/timers.js +++ /dev/null @@ -1,23 +0,0 @@ -const T1 = 500; -const T2 = 4000; -const T4 = 5000; -/** - * Timers. - * @public - */ -export const Timers = { - T1, - T2, - T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T4, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - TIMER_N: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; diff --git a/lib/core/transactions/client-transaction.d.ts b/lib/core/transactions/client-transaction.d.ts deleted file mode 100644 index 5ea1d1451..000000000 --- a/lib/core/transactions/client-transaction.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { IncomingResponseMessage, OutgoingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { Transaction } from "./transaction"; -import { TransactionState } from "./transaction-state"; -import { ClientTransactionUser } from "./transaction-user"; -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -export declare abstract class ClientTransaction extends Transaction { - private _request; - protected user: ClientTransactionUser; - protected constructor(_request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser, state: TransactionState, loggerCategory: string); - private static makeId; - /** The outgoing request the transaction handling. */ - get request(): OutgoingRequestMessage; - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - protected onRequestTimeout(): void; - /** - * Receive incoming responses from the transport which match this transaction. - * Responses will be delivered to the transaction user as necessary. - * @param response - The incoming response. - */ - abstract receiveResponse(response: IncomingResponseMessage): void; -} -//# sourceMappingURL=client-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/client-transaction.d.ts.map b/lib/core/transactions/client-transaction.d.ts.map deleted file mode 100644 index 5504a19c3..000000000 --- a/lib/core/transactions/client-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"client-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/client-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;;;;;;;;GAcG;AACH,8BAAsB,iBAAkB,SAAQ,WAAW;IAEvD,OAAO,CAAC,QAAQ;IAEhB,SAAS,CAAC,IAAI,EAAE,qBAAqB;IAHvC,SAAS,aACC,QAAQ,EAAE,sBAAsB,EACxC,SAAS,EAAE,SAAS,EACV,IAAI,EAAE,qBAAqB,EACrC,KAAK,EAAE,gBAAgB,EACvB,cAAc,EAAE,MAAM;IAYxB,OAAO,CAAC,MAAM,CAAC,MAAM;IAWrB,qDAAqD;IACrD,IAAI,OAAO,IAAI,sBAAsB,CAEpC;IAED;;;;;;;;;OASG;IACH,SAAS,CAAC,gBAAgB,IAAI,IAAI;IAMlC;;;;OAIG;aACa,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;CACzE"} \ No newline at end of file diff --git a/lib/core/transactions/client-transaction.js b/lib/core/transactions/client-transaction.js deleted file mode 100644 index 75e012bce..000000000 --- a/lib/core/transactions/client-transaction.js +++ /dev/null @@ -1,60 +0,0 @@ -import { Transaction } from "./transaction"; -/** - * Client Transaction. - * @remarks - * The client transaction provides its functionality through the - * maintenance of a state machine. - * - * The TU communicates with the client transaction through a simple - * interface. When the TU wishes to initiate a new transaction, it - * creates a client transaction and passes it the SIP request to send - * and an IP address, port, and transport to which to send it. The - * client transaction begins execution of its state machine. Valid - * responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - * @public - */ -export class ClientTransaction extends Transaction { - constructor(_request, transport, user, state, loggerCategory) { - super(transport, user, ClientTransaction.makeId(_request), state, loggerCategory); - this._request = _request; - this.user = user; - // The Via header field indicates the transport used for the transaction - // and identifies the location where the response is to be sent. A Via - // header field value is added only after the transport that will be - // used to reach the next hop has been selected (which may involve the - // usage of the procedures in [4]). - // https://tools.ietf.org/html/rfc3261#section-8.1.1.7 - _request.setViaHeader(this.id, transport.protocol); - } - static makeId(request) { - if (request.method === "CANCEL") { - if (!request.branch) { - throw new Error("Outgoing CANCEL request without a branch."); - } - return request.branch; - } - else { - return "z9hG4bK" + Math.floor(Math.random() * 10000000); - } - } - /** The outgoing request the transaction handling. */ - get request() { - return this._request; - } - /** - * A 408 to non-INVITE will always arrive too late to be useful ([3]), - * The client already has full knowledge of the timeout. The only - * information this message would convey is whether or not the server - * believed the transaction timed out. However, with the current design - * of the NIT, a client cannot do anything with this knowledge. Thus, - * the 408 is simply wasting network resources and contributes to the - * response bombardment illustrated in [3]. - * https://tools.ietf.org/html/rfc4320#section-4.1 - */ - onRequestTimeout() { - if (this.user.onRequestTimeout) { - this.user.onRequestTimeout(); - } - } -} diff --git a/lib/core/transactions/index.d.ts b/lib/core/transactions/index.d.ts deleted file mode 100644 index 96371a98d..000000000 --- a/lib/core/transactions/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from "./client-transaction"; -export * from "./invite-client-transaction"; -export * from "./invite-server-transaction"; -export * from "./non-invite-client-transaction"; -export * from "./non-invite-server-transaction"; -export * from "./invite-client-transaction"; -export * from "./server-transaction"; -export * from "./transaction-state"; -export * from "./transaction-user"; -export * from "./transaction"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/index.d.ts.map b/lib/core/transactions/index.d.ts.map deleted file mode 100644 index 5df90caf9..000000000 --- a/lib/core/transactions/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,iCAAiC,CAAC;AAChD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/lib/core/transactions/index.js b/lib/core/transactions/index.js deleted file mode 100644 index c4f66d3f7..000000000 --- a/lib/core/transactions/index.js +++ /dev/null @@ -1,10 +0,0 @@ -export * from "./client-transaction"; -export * from "./invite-client-transaction"; -export * from "./invite-server-transaction"; -export * from "./non-invite-client-transaction"; -export * from "./non-invite-server-transaction"; -export * from "./invite-client-transaction"; -export * from "./server-transaction"; -export * from "./transaction-state"; -export * from "./transaction-user"; -export * from "./transaction"; diff --git a/lib/core/transactions/invite-client-transaction.d.ts b/lib/core/transactions/invite-client-transaction.d.ts deleted file mode 100644 index 9cf9e00e8..000000000 --- a/lib/core/transactions/invite-client-transaction.d.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { TransportError } from "../exceptions"; -import { IncomingResponseMessage, OutgoingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ClientTransaction } from "./client-transaction"; -import { ClientTransactionUser } from "./transaction-user"; -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -export declare class InviteClientTransaction extends ClientTransaction { - private B; - private D; - private M; - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - private ackRetransmissionCache; - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - get kind(): string; - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - ackResponse(ack: OutgoingRequestMessage): void; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response: IncomingResponseMessage): void; - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - protected onTransportError(error: TransportError): void; - /** For logging. */ - protected typeToString(): string; - private ack; - /** - * Execute a state transition. - * @param newState - New state. - */ - private stateTransition; - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - private timerA; - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - private timerB; - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - private timerD; - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - private timerM; -} -//# sourceMappingURL=invite-client-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/invite-client-transaction.d.ts.map b/lib/core/transactions/invite-client-transaction.d.ts.map deleted file mode 100644 index 48d0bf0b5..000000000 --- a/lib/core/transactions/invite-client-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-client-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/invite-client-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,iBAAiB;IAC5D,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;OAKG;IACH,OAAO,CAAC,sBAAsB,CAA8D;IAE5F;;;;;;;;;;OAUG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAoB9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAgBtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;;;;;;;;;;;;;;OAgBG;IACI,WAAW,CAAC,GAAG,EAAE,sBAAsB,GAAG,IAAI;IAarD;;;OAGG;IACI,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA8K/D;;;;;;;OAOG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IAOvD,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC,OAAO,CAAC,GAAG;IAwDX;;;OAGG;IACH,OAAO,CAAC,eAAe;IA4EvB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,MAAM;IAId;;;;;OAKG;IACH,OAAO,CAAC,MAAM;IAQd;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAOd;;;;OAIG;IACH,OAAO,CAAC,MAAM;CAMf"} \ No newline at end of file diff --git a/lib/core/transactions/invite-client-transaction.js b/lib/core/transactions/invite-client-transaction.js deleted file mode 100644 index 97c12e52b..000000000 --- a/lib/core/transactions/invite-client-transaction.js +++ /dev/null @@ -1,467 +0,0 @@ -import { Timers } from "../timers"; -import { ClientTransaction } from "./client-transaction"; -import { TransactionState } from "./transaction-state"; -/** - * INVITE Client Transaction. - * @remarks - * The INVITE transaction consists of a three-way handshake. The client - * transaction sends an INVITE, the server transaction sends responses, - * and the client transaction sends an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @public - */ -export class InviteClientTransaction extends ClientTransaction { - /** - * Constructor. - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.1 - * @param request - The outgoing INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, TransactionState.Calling, "sip.transaction.ict"); - /** - * Map of 2xx to-tag to ACK. - * If value is not undefined, value is the ACK which was sent. - * If key exists but value is undefined, a 2xx was received but the ACK not yet sent. - * Otherwise, a 2xx was not (yet) received for this transaction. - */ - this.ackRetransmissionCache = new Map(); - // FIXME: Timer A for unreliable transport not implemented - // - // If an unreliable transport is being used, the client transaction - // MUST start timer A with a value of T1. If a reliable transport is being used, - // the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). - // For any transport, the client transaction MUST start timer B with a value - // of 64*T1 seconds (Timer B controls transaction timeouts). - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - // - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - this.B = setTimeout(() => this.timerB(), Timers.TIMER_B); - this.send(request.toString()).catch((error) => { - this.logTransportError(error, "Failed to send initial outgoing request."); - }); - } - /** - * Destructor. - */ - dispose() { - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (this.D) { - clearTimeout(this.D); - this.D = undefined; - } - if (this.M) { - clearTimeout(this.M); - this.M = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "ict"; - } - /** - * ACK a 2xx final response. - * - * The transaction includes the ACK only if the final response was not a 2xx response (the - * transaction will generate and send the ACK to the transport automagically). If the - * final response was a 2xx, the ACK is not considered part of the transaction (the - * transaction user needs to generate and send the ACK). - * - * This library is not strictly RFC compliant with regard to ACK handling for 2xx final - * responses. Specifically, retransmissions of ACKs to a 2xx final responses is handled - * by the transaction layer (instead of the UAC core). The "standard" approach is for - * the UAC core to receive all 2xx responses and manage sending ACK retransmissions to - * the transport directly. Herein the transaction layer manages sending ACKs to 2xx responses - * and any retransmissions of those ACKs as needed. - * - * @param ack - The outgoing ACK request. - */ - ackResponse(ack) { - const toTag = ack.toTag; - if (!toTag) { - throw new Error("To tag undefined."); - } - const id = "z9hG4bK" + Math.floor(Math.random() * 10000000); - ack.setViaHeader(id, this.transport.protocol); - this.ackRetransmissionCache.set(toTag, ack); // Add to ACK retransmission cache - this.send(ack.toString()).catch((error) => { - this.logTransportError(error, "Failed to send ACK to 2xx response."); - }); - } - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response) { - const statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case TransactionState.Calling: - // If the client transaction receives a provisional response while in - // the "Calling" state, it transitions to the "Proceeding" state. In the - // "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or - // "Proceeding" states, the client transaction MUST transition to - // the "Accepted" state... The 2xx response MUST be passed up to the TU. - // The client transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case TransactionState.Proceeding: - // In the "Proceeding" state, the client transaction SHOULD NOT retransmit the - // request any longer. Furthermore, the provisional response MUST be - // passed to the TU. Any further provisional responses MUST be passed - // up to the TU while in the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When a 2xx response is received while in either the "Calling" or "Proceeding" states, - // the client transaction MUST transition to the "Accepted" state... - // The 2xx response MUST be passed up to the TU. The client - // transaction MUST NOT generate an ACK to the 2xx response -- its - // handling is delegated to the TU. A UAC core will send an ACK to - // the 2xx response using a new transaction. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - this.stateTransition(TransactionState.Accepted); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // When in either the "Calling" or "Proceeding" states, reception of - // a response with status code from 300-699 MUST cause the client - // transaction to transition to "Completed". The client transaction - // MUST pass the received response up to the TU, and the client - // transaction MUST generate an ACK request, even if the transport is - // reliable (guidelines for constructing the ACK from the response - // are given in Section 17.1.1.3), and then pass the ACK to the - // transport layer for transmission. The ACK MUST be sent to the - // same address, port, and transport to which the original request was sent. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.stateTransition(TransactionState.Completed); - this.ack(response); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case TransactionState.Accepted: - // The purpose of the "Accepted" state is to allow the client - // transaction to continue to exist to receive, and pass to the TU, - // any retransmissions of the 2xx response and any additional 2xx - // responses from other branches of the INVITE if it forked - // downstream. Timer M reflects the amount of time that the - // transaction user will wait for such messages. - // - // Any 2xx responses that match this client transaction and that are - // received while in the "Accepted" state MUST be passed up to the - // TU. The client transaction MUST NOT generate an ACK to the 2xx - // response. The client transaction takes no further action. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 200 && statusCode <= 299) { - // NOTE: This implementation herein is intentionally not RFC compliant. - // While the first 2xx response for a given branch is passed up to the TU, - // retransmissions of 2xx responses are absorbed and the ACK associated - // with the original response is resent. This approach is taken because - // our current transaction users are not currently in a good position to - // deal with 2xx retransmission. This SHOULD NOT cause any compliance issues - ;) - // - // If we don't have a cache hit, pass the response to the TU. - if (!this.ackRetransmissionCache.has(response.toTag)) { - this.ackRetransmissionCache.set(response.toTag, undefined); // Prime the ACK cache - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If we have a cache hit, try pulling the ACK from cache and retransmitting it. - const ack = this.ackRetransmissionCache.get(response.toTag); - if (ack) { - this.send(ack.toString()).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of ACK to 2xx response."); - }); - return; - } - // If an ACK was not found in cache then we have received a retransmitted 2xx - // response before the TU responded to the original response (we don't have an ACK yet). - // So discard this response under the assumption that the TU will eventually - // get us a ACK for the original response. - return; - } - break; - case TransactionState.Completed: - // Any retransmissions of a response with status code 300-699 that - // are received while in the "Completed" state MUST cause the ACK to - // be re-passed to the transport layer for retransmission, but the - // newly received response MUST NOT be passed up to the TU. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (statusCode >= 300 && statusCode <= 699) { - this.ack(response); - return; - } - break; - case TransactionState.Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - // Any response received that does not match an existing client - // transaction state machine is simply dropped. (Implementations are, - // of course, free to log or do other implementation-specific things - // with such responses, but the implementer should be sure to consider - // the impact of large numbers of malicious stray responses.) - // https://tools.ietf.org/html/rfc6026#section-7.2 - const message = `Received unexpected ${statusCode} response while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * The client transaction SHOULD inform the TU that a transport failure - * has occurred, and the client transaction SHOULD transition directly - * to the "Terminated" state. The TU will handle the failover - * mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - The error. - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(TransactionState.Terminated, true); - } - /** For logging. */ - typeToString() { - return "INVITE client transaction"; - } - ack(response) { - // The ACK request constructed by the client transaction MUST contain - // values for the Call-ID, From, and Request-URI that are equal to the - // values of those header fields in the request passed to the transport - // by the client transaction (call this the "original request"). The To - // header field in the ACK MUST equal the To header field in the - // response being acknowledged, and therefore will usually differ from - // the To header field in the original request by the addition of the - // tag parameter. The ACK MUST contain a single Via header field, and - // this MUST be equal to the top Via header field of the original - // request. The CSeq header field in the ACK MUST contain the same - // value for the sequence number as was present in the original request, - // but the method parameter MUST be equal to "ACK". - // - // If the INVITE request whose response is being acknowledged had Route - // header fields, those header fields MUST appear in the ACK. This is - // to ensure that the ACK can be routed properly through any downstream - // stateless proxies. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.3 - const ruri = this.request.ruri; - const callId = this.request.callId; - const cseq = this.request.cseq; - const from = this.request.getHeader("from"); - const to = response.getHeader("to"); - const via = this.request.getHeader("via"); - const route = this.request.getHeader("route"); - if (!from) { - throw new Error("From undefined."); - } - if (!to) { - throw new Error("To undefined."); - } - if (!via) { - throw new Error("Via undefined."); - } - let ack = `ACK ${ruri} SIP/2.0\r\n`; - if (route) { - ack += `Route: ${route}\r\n`; - } - ack += `Via: ${via}\r\n`; - ack += `To: ${to}\r\n`; - ack += `From: ${from}\r\n`; - ack += `Call-ID: ${callId}\r\n`; - ack += `CSeq: ${cseq} ACK\r\n`; - ack += `Max-Forwards: 70\r\n`; - ack += `Content-Length: 0\r\n\r\n`; - // TOOO: "User-Agent" header - this.send(ack).catch((error) => { - this.logTransportError(error, "Failed to send ACK to non-2xx response."); - }); - return; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case TransactionState.Calling: - invalidStateTransition(); - break; - case TransactionState.Proceeding: - if (this.state !== TransactionState.Calling) { - invalidStateTransition(); - } - break; - case TransactionState.Accepted: - case TransactionState.Completed: - if (this.state !== TransactionState.Calling && this.state !== TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case TransactionState.Terminated: - if (this.state !== TransactionState.Calling && - this.state !== TransactionState.Accepted && - this.state !== TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // While not spelled out in the RFC, Timer B is the maximum amount of time that a sender - // will wait for an INVITE message to be acknowledged (a SIP response message is received). - // So Timer B should be cleared when the transaction state proceeds from "Calling". - if (this.B) { - clearTimeout(this.B); - this.B = undefined; - } - if (newState === TransactionState.Proceeding) { - // Timers have no effect on "Proceeding" state. - // In the "Proceeding" state, the client transaction - // SHOULD NOT retransmit the request any longer. - // https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - } - // The client transaction MUST start Timer D when it enters the "Completed" state - // for any reason, with a value of at least 32 seconds for unreliable transports, - // and a value of zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === TransactionState.Completed) { - this.D = setTimeout(() => this.timerD(), Timers.TIMER_D); - } - // The client transaction MUST transition to the "Accepted" state, - // and Timer M MUST be started with a value of 64*T1. - // https://tools.ietf.org/html/rfc6026#section-8.4 - if (newState === TransactionState.Accepted) { - this.M = setTimeout(() => this.timerM(), Timers.TIMER_M); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * When timer A fires, the client transaction MUST retransmit the - * request by passing it to the transport layer, and MUST reset the - * timer with a value of 2*T1. - * When timer A fires 2*T1 seconds later, the request MUST be - * retransmitted again (assuming the client transaction is still in this - * state). This process MUST continue so that the request is - * retransmitted with intervals that double after each transmission. - * These retransmissions SHOULD only be done while the client - * transaction is in the "Calling" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - timerA() { - // TODO - } - /** - * If the client transaction is still in the "Calling" state when timer - * B fires, the client transaction SHOULD inform the TU that a timeout - * has occurred. The client transaction MUST NOT generate an ACK. - * https://tools.ietf.org/html/rfc3261#section-17.1.1.2 - */ - timerB() { - this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`); - if (this.state === TransactionState.Calling) { - this.onRequestTimeout(); - this.stateTransition(TransactionState.Terminated); - } - } - /** - * If Timer D fires while the client transaction is in the "Completed" state, - * the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - timerD() { - this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`); - if (this.state === TransactionState.Completed) { - this.stateTransition(TransactionState.Terminated); - } - } - /** - * If Timer M fires while the client transaction is in the "Accepted" - * state, the client transaction MUST move to the "Terminated" state. - * https://tools.ietf.org/html/rfc6026#section-8.4 - */ - timerM() { - this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`); - if (this.state === TransactionState.Accepted) { - this.stateTransition(TransactionState.Terminated); - } - } -} diff --git a/lib/core/transactions/invite-server-transaction.d.ts b/lib/core/transactions/invite-server-transaction.d.ts deleted file mode 100644 index 8298f77f9..000000000 --- a/lib/core/transactions/invite-server-transaction.d.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { IncomingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ServerTransaction } from "./server-transaction"; -import { ServerTransactionUser } from "./transaction-user"; -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -export declare class InviteServerTransaction extends ServerTransaction { - private lastFinalResponse; - private lastProvisionalResponse; - private H; - private I; - private L; - /** - * FIXME: This should not be here. It should be in the UAS. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * - * An INVITE transaction can go on for extended durations when the - * user is placed on hold, or when interworking with PSTN systems - * which allow communications to take place without answering the - * call. The latter is common in Interactive Voice Response (IVR) - * systems. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - */ - private progressExtensionTimer; - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - get kind(): string; - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request: IncomingRequestMessage): void; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - receiveResponse(statusCode: number, response: string): void; - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - retransmitAcceptedResponse(): void; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - protected onTransportError(error: Error): void; - /** For logging. */ - protected typeToString(): string; - /** - * Execute a state transition. - * @param newState - New state. - */ - private stateTransition; - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - private startProgressExtensionTimer; - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - private stopProgressExtensionTimer; - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - private timerG; - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - private timerH; - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - private timerI; - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - private timerL; -} -//# sourceMappingURL=invite-server-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/invite-server-transaction.d.ts.map b/lib/core/transactions/invite-server-transaction.d.ts.map deleted file mode 100644 index 618d11f32..000000000 --- a/lib/core/transactions/invite-server-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-server-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/invite-server-transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAK,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAExD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;GAKG;AACH,qBAAa,uBAAwB,SAAQ,iBAAiB;IAC5D,OAAO,CAAC,iBAAiB,CAAqB;IAC9C,OAAO,CAAC,uBAAuB,CAAqB;IACpD,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,CAAC,sBAAsB,CAAqB;IAEnD;;;;;;;;;OASG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAI9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAiBtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;OAGG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAsE5D;;;;OAIG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAgFlE;;OAEG;IACI,0BAA0B,IAAI,IAAI;IAQzC;;;;;OAKG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAM9C,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC;;;OAGG;IACH,OAAO,CAAC,eAAe;IA4EvB;;;OAGG;IACH,OAAO,CAAC,2BAA2B;IAenC;;;OAGG;IACH,OAAO,CAAC,0BAA0B;IAOlC;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,MAAM;IAId;;;;;OAKG;IACH,OAAO,CAAC,MAAM;IAQd;;;OAGG;IACH,OAAO,CAAC,MAAM;IAKd;;;;;;;;OAQG;IACH,OAAO,CAAC,MAAM;CAMf"} \ No newline at end of file diff --git a/lib/core/transactions/invite-server-transaction.js b/lib/core/transactions/invite-server-transaction.js deleted file mode 100644 index 277e1b417..000000000 --- a/lib/core/transactions/invite-server-transaction.js +++ /dev/null @@ -1,376 +0,0 @@ -import { C } from "../messages"; -import { Timers } from "../timers"; -import { ServerTransaction } from "./server-transaction"; -import { TransactionState } from "./transaction-state"; -/** - * INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @public - */ -export class InviteServerTransaction extends ServerTransaction { - /** - * Constructor. - * Upon construction, a "100 Trying" reply will be immediately sent. - * After construction the transaction will be in the "proceeding" state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - * @param request - Incoming INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, TransactionState.Proceeding, "sip.transaction.ist"); - } - /** - * Destructor. - */ - dispose() { - this.stopProgressExtensionTimer(); - if (this.H) { - clearTimeout(this.H); - this.H = undefined; - } - if (this.I) { - clearTimeout(this.I); - this.I = undefined; - } - if (this.L) { - clearTimeout(this.L); - this.L = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "ist"; - } - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request) { - switch (this.state) { - case TransactionState.Proceeding: - // If a request retransmission is received while in the "Proceeding" state, the most - // recent provisional response that was received from the TU MUST be passed to the - // transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === C.INVITE) { - if (this.lastProvisionalResponse) { - this.send(this.lastProvisionalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - } - return; - } - break; - case TransactionState.Accepted: - // While in the "Accepted" state, any retransmissions of the INVITE - // received will match this transaction state machine and will be - // absorbed by the machine without changing its state. These - // retransmissions are not passed onto the TU. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (request.method === C.INVITE) { - return; - } - break; - case TransactionState.Completed: - // Furthermore, while in the "Completed" state, if a request retransmission is - // received, the server SHOULD pass the response to the transport for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === C.INVITE) { - if (!this.lastFinalResponse) { - throw new Error("Last final response undefined."); - } - this.send(this.lastFinalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of final response."); - }); - return; - } - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === C.ACK) { - this.stateTransition(TransactionState.Confirmed); - return; - } - break; - case TransactionState.Confirmed: - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (request.method === C.INVITE || request.method === C.ACK) { - return; - } - break; - case TransactionState.Terminated: - // For good measure absorb any additional messages that arrive (should not happen). - if (request.method === C.INVITE || request.method === C.ACK) { - return; - } - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `INVITE server transaction received unexpected ${request.method} request while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. - * @param response - Response. - */ - receiveResponse(statusCode, response) { - if (statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case TransactionState.Proceeding: - // The TU passes any number of provisional responses to the server - // transaction. So long as the server transaction is in the - // "Proceeding" state, each of these MUST be passed to the transport - // layer for transmission. They are not sent reliably by the - // transaction layer (they are not retransmitted by it) and do not cause - // a change in the state of the server transaction. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 100 && statusCode <= 199) { - this.lastProvisionalResponse = response; - // Start the progress extension timer only for a non-100 provisional response. - if (statusCode > 100) { - this.startProgressExtensionTimer(); // FIXME: remove - } - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 1xx response."); - }); - return; - } - // If, while in the "Proceeding" state, the TU passes a 2xx response - // to the server transaction, the server transaction MUST pass this - // response to the transport layer for transmission. It is not - // retransmitted by the server transaction; retransmissions of 2xx - // responses are handled by the TU. The server transaction MUST then - // transition to the "Accepted" state. - // https://tools.ietf.org/html/rfc6026#section-8.5 - if (statusCode >= 200 && statusCode <= 299) { - this.lastFinalResponse = response; - this.stateTransition(TransactionState.Accepted); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - // While in the "Proceeding" state, if the TU passes a response with - // status code from 300 to 699 to the server transaction, the response - // MUST be passed to the transport layer for transmission, and the state - // machine MUST enter the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (statusCode >= 300 && statusCode <= 699) { - this.lastFinalResponse = response; - this.stateTransition(TransactionState.Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send non-2xx final response."); - }); - return; - } - break; - case TransactionState.Accepted: - // While in the "Accepted" state, if the TU passes a 2xx response, - // the server transaction MUST pass the response to the transport layer for transmission. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (statusCode >= 200 && statusCode <= 299) { - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - return; - } - break; - case TransactionState.Completed: - break; - case TransactionState.Confirmed: - break; - case TransactionState.Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; - this.logger.error(message); - throw new Error(message); - } - /** - * Retransmit the last 2xx response. This is a noop if not in the "accepted" state. - */ - retransmitAcceptedResponse() { - if (this.state === TransactionState.Accepted && this.lastFinalResponse) { - this.send(this.lastFinalResponse).catch((error) => { - this.logTransportError(error, "Failed to send 2xx response."); - }); - } - } - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and MUST remain in the current state. - * https://tools.ietf.org/html/rfc6026#section-8.8 - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - } - /** For logging. */ - typeToString() { - return "INVITE server transaction"; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case TransactionState.Proceeding: - invalidStateTransition(); - break; - case TransactionState.Accepted: - case TransactionState.Completed: - if (this.state !== TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case TransactionState.Confirmed: - if (this.state !== TransactionState.Completed) { - invalidStateTransition(); - } - break; - case TransactionState.Terminated: - if (this.state !== TransactionState.Accepted && - this.state !== TransactionState.Completed && - this.state !== TransactionState.Confirmed) { - invalidStateTransition(); - } - break; - default: - invalidStateTransition(); - } - // On any state transition, stop resending provisional responses - this.stopProgressExtensionTimer(); - // The purpose of the "Accepted" state is to absorb retransmissions of an accepted INVITE request. - // Any such retransmissions are absorbed entirely within the server transaction. - // They are not passed up to the TU since any downstream UAS cores that accepted the request have - // taken responsibility for reliability and will already retransmit their 2xx responses if necessary. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === TransactionState.Accepted) { - this.L = setTimeout(() => this.timerL(), Timers.TIMER_L); - } - // When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. - // Timer H determines when the server transaction abandons retransmitting the response. - // If an ACK is received while the server transaction is in the "Completed" state, - // the server transaction MUST transition to the "Confirmed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === TransactionState.Completed) { - // FIXME: Missing timer G for unreliable transports. - this.H = setTimeout(() => this.timerH(), Timers.TIMER_H); - } - // The purpose of the "Confirmed" state is to absorb any additional ACK messages that arrive, - // triggered from retransmissions of the final response. When this state is entered, timer I - // is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable - // transports. Once timer I fires, the server MUST transition to the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.1 - if (newState === TransactionState.Confirmed) { - // FIXME: This timer is not getting set correctly for unreliable transports. - this.I = setTimeout(() => this.timerI(), Timers.TIMER_I); - } - // Once the transaction is in the "Terminated" state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc6026#section-8.7 - if (newState === TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * FIXME: UAS Provisional Retransmission Timer. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - startProgressExtensionTimer() { - // Start the progress extension timer only for the first non-100 provisional response. - if (this.progressExtensionTimer === undefined) { - this.progressExtensionTimer = setInterval(() => { - this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`); - if (!this.lastProvisionalResponse) { - throw new Error("Last provisional response undefined."); - } - this.send(this.lastProvisionalResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - }, Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - } - /** - * FIXME: UAS Provisional Retransmission Timer id. See RFC 3261 Section 13.3.1.1 - * This is in the wrong place. This is not a transaction level thing. It's a UAS level thing. - */ - stopProgressExtensionTimer() { - if (this.progressExtensionTimer !== undefined) { - clearInterval(this.progressExtensionTimer); - this.progressExtensionTimer = undefined; - } - } - /** - * While in the "Proceeding" state, if the TU passes a response with status code - * from 300 to 699 to the server transaction, the response MUST be passed to the - * transport layer for transmission, and the state machine MUST enter the "Completed" state. - * For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for - * reliable transports. If timer G fires, the response is passed to the transport layer once - * more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, - * when timer G fires, the response is passed to the transport again for transmission, and - * timer G is reset with a value that doubles, unless that value exceeds T2, in which case - * it is reset with the value of T2. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerG() { - // TODO - } - /** - * If timer H fires while in the "Completed" state, it implies that the ACK was never received. - * In this case, the server transaction MUST transition to the "Terminated" state, and MUST - * indicate to the TU that a transaction failure has occurred. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerH() { - this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`); - if (this.state === TransactionState.Completed) { - this.logger.warn("ACK to negative final response was never received, terminating transaction."); - this.stateTransition(TransactionState.Terminated); - } - } - /** - * Once timer I fires, the server MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.1 - */ - timerI() { - this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`); - this.stateTransition(TransactionState.Terminated); - } - /** - * When Timer L fires and the state machine is in the "Accepted" state, the machine MUST - * transition to the "Terminated" state. Once the transaction is in the "Terminated" state, - * it MUST be destroyed immediately. Timer L reflects the amount of time the server - * transaction could receive 2xx responses for retransmission from the - * TU while it is waiting to receive an ACK. - * https://tools.ietf.org/html/rfc6026#section-7.1 - * https://tools.ietf.org/html/rfc6026#section-8.7 - */ - timerL() { - this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`); - if (this.state === TransactionState.Accepted) { - this.stateTransition(TransactionState.Terminated); - } - } -} diff --git a/lib/core/transactions/non-invite-client-transaction.d.ts b/lib/core/transactions/non-invite-client-transaction.d.ts deleted file mode 100644 index 4450a067b..000000000 --- a/lib/core/transactions/non-invite-client-transaction.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { IncomingResponseMessage, OutgoingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ClientTransaction } from "./client-transaction"; -import { ClientTransactionUser } from "./transaction-user"; -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -export declare class NonInviteClientTransaction extends ClientTransaction { - private F; - private K; - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - get kind(): string; - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response: IncomingResponseMessage): void; - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the fail over mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Transport error - */ - protected onTransportError(error: Error): void; - /** For logging. */ - protected typeToString(): string; - /** - * Execute a state transition. - * @param newState - New state. - */ - private stateTransition; - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - private timerF; - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - private timerK; -} -//# sourceMappingURL=non-invite-client-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/non-invite-client-transaction.d.ts.map b/lib/core/transactions/non-invite-client-transaction.d.ts.map deleted file mode 100644 index 2231bc53e..000000000 --- a/lib/core/transactions/non-invite-client-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"non-invite-client-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/non-invite-client-transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE9E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;GAOG;AACH,qBAAa,0BAA2B,SAAQ,iBAAiB;IAC/D,OAAO,CAAC,CAAC,CAAqB;IAC9B,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;;;;;;OAUG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAe9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAYtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;OAGG;IACI,eAAe,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI;IA8E/D;;;;;;OAMG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAO9C,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC;;;OAGG;IACH,OAAO,CAAC,eAAe;IA2DvB;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM;IAQd;;;;OAIG;IACH,OAAO,CAAC,MAAM;CAKf"} \ No newline at end of file diff --git a/lib/core/transactions/non-invite-client-transaction.js b/lib/core/transactions/non-invite-client-transaction.js deleted file mode 100644 index cddff137a..000000000 --- a/lib/core/transactions/non-invite-client-transaction.js +++ /dev/null @@ -1,233 +0,0 @@ -import { Timers } from "../timers"; -import { ClientTransaction } from "./client-transaction"; -import { TransactionState } from "./transaction-state"; -/** - * Non-INVITE Client Transaction. - * @remarks - * Non-INVITE transactions do not make use of ACK. - * They are simple request-response interactions. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @public - */ -export class NonInviteClientTransaction extends ClientTransaction { - /** - * Constructor - * Upon construction, the outgoing request's Via header is updated by calling `setViaHeader`. - * Then `toString` is called on the outgoing request and the message is sent via the transport. - * After construction the transaction will be in the "calling" state and the transaction id - * will equal the branch parameter set in the Via header of the outgoing request. - * https://tools.ietf.org/html/rfc3261#section-17.1.2 - * @param request - The outgoing Non-INVITE request. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, TransactionState.Trying, "sip.transaction.nict"); - // FIXME: Timer E for unreliable transports not implemented. - // - // The "Trying" state is entered when the TU initiates a new client - // transaction with a request. When entering this state, the client - // transaction SHOULD set timer F to fire in 64*T1 seconds. The request - // MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - this.F = setTimeout(() => this.timerF(), Timers.TIMER_F); - this.send(request.toString()).catch((error) => { - this.logTransportError(error, "Failed to send initial outgoing request."); - }); - } - /** - * Destructor. - */ - dispose() { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - if (this.K) { - clearTimeout(this.K); - this.K = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "nict"; - } - /** - * Handler for incoming responses from the transport which match this transaction. - * @param response - The incoming response. - */ - receiveResponse(response) { - const statusCode = response.statusCode; - if (!statusCode || statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - switch (this.state) { - case TransactionState.Trying: - // If a provisional response is received while in the "Trying" state, the - // response MUST be passed to the TU, and then the client transaction - // SHOULD move to the "Proceeding" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - this.stateTransition(TransactionState.Proceeding); - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - // If a final response (status codes 200-699) is received while in the - // "Trying" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case TransactionState.Proceeding: - // If a provisional response is received while in the "Proceeding" state, - // the response MUST be passed to the TU. (From Figure 6) - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 100 && statusCode <= 199) { - if (this.user.receiveResponse) { - return this.user.receiveResponse(response); - } - } - // If a final response (status codes 200-699) is received while in the - // "Proceeding" state, the response MUST be passed to the TU, and the - // client transaction MUST transition to the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(TransactionState.Completed); - if (statusCode === 408) { - this.onRequestTimeout(); - return; - } - if (this.user.receiveResponse) { - this.user.receiveResponse(response); - } - return; - } - break; - case TransactionState.Completed: - // The "Completed" state exists to buffer any additional response - // retransmissions that may be received (which is why the client - // transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - return; - case TransactionState.Terminated: - // For good measure just absorb additional response retransmissions. - return; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `Non-INVITE client transaction received unexpected ${statusCode} response while in state ${this.state}.`; - this.logger.warn(message); - return; - } - /** - * The client transaction SHOULD inform the TU that a transport failure has occurred, - * and the client transaction SHOULD transition directly to the "Terminated" state. - * The TU will handle the fail over mechanisms described in [4]. - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * @param error - Transport error - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(TransactionState.Terminated, true); - } - /** For logging. */ - typeToString() { - return "non-INVITE client transaction"; - } - /** - * Execute a state transition. - * @param newState - New state. - */ - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case TransactionState.Trying: - invalidStateTransition(); - break; - case TransactionState.Proceeding: - if (this.state !== TransactionState.Trying) { - invalidStateTransition(); - } - break; - case TransactionState.Completed: - if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case TransactionState.Terminated: - if (this.state !== TransactionState.Trying && - this.state !== TransactionState.Proceeding && - this.state !== TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // Once the client transaction enters the "Completed" state, it MUST set - // Timer K to fire in T4 seconds for unreliable transports, and zero - // seconds for reliable transports The "Completed" state exists to - // buffer any additional response retransmissions that may be received - // (which is why the client transaction remains there only for unreliable transports). - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === TransactionState.Completed) { - if (this.F) { - clearTimeout(this.F); - this.F = undefined; - } - this.K = setTimeout(() => this.timerK(), Timers.TIMER_K); - } - // Once the transaction is in the terminated state, it MUST be destroyed immediately. - // https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - if (newState === TransactionState.Terminated) { - this.dispose(); - } - // Update state. - this.setState(newState); - } - /** - * If Timer F fires while the client transaction is still in the - * "Trying" state, the client transaction SHOULD inform the TU about the - * timeout, and then it SHOULD enter the "Terminated" state. - * If timer F fires while in the "Proceeding" state, the TU MUST be informed of - * a timeout, and the client transaction MUST transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - timerF() { - this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`); - if (this.state === TransactionState.Trying || this.state === TransactionState.Proceeding) { - this.onRequestTimeout(); - this.stateTransition(TransactionState.Terminated); - } - } - /** - * If Timer K fires while in this (COMPLETED) state, the client transaction - * MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - timerK() { - if (this.state === TransactionState.Completed) { - this.stateTransition(TransactionState.Terminated); - } - } -} diff --git a/lib/core/transactions/non-invite-server-transaction.d.ts b/lib/core/transactions/non-invite-server-transaction.d.ts deleted file mode 100644 index 884974d9e..000000000 --- a/lib/core/transactions/non-invite-server-transaction.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { IncomingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { ServerTransaction } from "./server-transaction"; -import { ServerTransactionUser } from "./transaction-user"; -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -export declare class NonInviteServerTransaction extends ServerTransaction { - private lastResponse; - private J; - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser); - /** - * Destructor. - */ - dispose(): void; - /** Transaction kind. Deprecated. */ - get kind(): string; - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - receiveRequest(request: IncomingRequestMessage): void; - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - receiveResponse(statusCode: number, response: string): void; - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - protected onTransportError(error: Error): void; - /** For logging. */ - protected typeToString(): string; - private stateTransition; - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - private timerJ; -} -//# sourceMappingURL=non-invite-server-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/non-invite-server-transaction.d.ts.map b/lib/core/transactions/non-invite-server-transaction.d.ts.map deleted file mode 100644 index efbbcfef9..000000000 --- a/lib/core/transactions/non-invite-server-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"non-invite-server-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/non-invite-server-transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;GAKG;AACH,qBAAa,0BAA2B,SAAQ,iBAAiB;IAC/D,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,CAAC,CAAqB;IAE9B;;;;;;;;OAQG;gBACS,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB;IAI9F;;OAEG;IACI,OAAO,IAAI,IAAI;IAQtB,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;OAGG;IAEI,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAoC5D;;;;OAIG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAuElE;;;;;OAKG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAO9C,mBAAmB;IACnB,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC,OAAO,CAAC,eAAe;IA+CvB;;;;OAIG;IACH,OAAO,CAAC,MAAM;CAMf"} \ No newline at end of file diff --git a/lib/core/transactions/non-invite-server-transaction.js b/lib/core/transactions/non-invite-server-transaction.js deleted file mode 100644 index f591e69ad..000000000 --- a/lib/core/transactions/non-invite-server-transaction.js +++ /dev/null @@ -1,218 +0,0 @@ -import { Timers } from "../timers"; -import { ServerTransaction } from "./server-transaction"; -import { TransactionState } from "./transaction-state"; -/** - * Non-INVITE Server Transaction. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @public - */ -export class NonInviteServerTransaction extends ServerTransaction { - /** - * Constructor. - * After construction the transaction will be in the "trying": state and the transaction - * `id` will equal the branch parameter set in the Via header of the incoming request. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - * @param request - Incoming Non-INVITE request from the transport. - * @param transport - The transport. - * @param user - The transaction user. - */ - constructor(request, transport, user) { - super(request, transport, user, TransactionState.Trying, "sip.transaction.nist"); - } - /** - * Destructor. - */ - dispose() { - if (this.J) { - clearTimeout(this.J); - this.J = undefined; - } - super.dispose(); - } - /** Transaction kind. Deprecated. */ - get kind() { - return "nist"; - } - /** - * Receive requests from transport matching this transaction. - * @param request - Request matching this transaction. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - receiveRequest(request) { - switch (this.state) { - case TransactionState.Trying: - // Once in the "Trying" state, any further request retransmissions are discarded. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - break; - case TransactionState.Proceeding: - // If a retransmission of the request is received while in the "Proceeding" state, - // the most recently sent provisional response MUST be passed to the transport layer for retransmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of provisional response."); - }); - break; - case TransactionState.Completed: - // While in the "Completed" state, the server transaction MUST pass the final response to the transport - // layer for retransmission whenever a retransmission of the request is received. Any other final responses - // passed by the TU to the server transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (!this.lastResponse) { - throw new Error("Last response undefined."); - } - this.send(this.lastResponse).catch((error) => { - this.logTransportError(error, "Failed to send retransmission of final response."); - }); - break; - case TransactionState.Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - } - /** - * Receive responses from TU for this transaction. - * @param statusCode - Status code of response. 101-199 not allowed per RFC 4320. - * @param response - Response to send. - */ - receiveResponse(statusCode, response) { - if (statusCode < 100 || statusCode > 699) { - throw new Error(`Invalid status code ${statusCode}`); - } - // An SIP element MUST NOT send any provisional response with a - // Status-Code other than 100 to a non-INVITE request. - // An SIP element MUST NOT respond to a non-INVITE request with a - // Status-Code of 100 over any unreliable transport, such as UDP, - // before the amount of time it takes a client transaction's Timer E to be reset to T2. - // An SIP element MAY respond to a non-INVITE request with a - // Status-Code of 100 over a reliable transport at any time. - // https://tools.ietf.org/html/rfc4320#section-4.1 - if (statusCode > 100 && statusCode <= 199) { - throw new Error("Provisional response other than 100 not allowed."); - } - switch (this.state) { - case TransactionState.Trying: - // While in the "Trying" state, if the TU passes a provisional response - // to the server transaction, the server transaction MUST enter the "Proceeding" state. - // The response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 100 && statusCode < 200) { - this.stateTransition(TransactionState.Proceeding); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send provisional response."); - }); - return; - } - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(TransactionState.Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case TransactionState.Proceeding: - // Any further provisional responses that are received from the TU while - // in the "Proceeding" state MUST be passed to the transport layer for transmission. - // If the TU passes a final response (status codes 200-699) to the server while in - // the "Proceeding" state, the transaction MUST enter the "Completed" state, and - // the response MUST be passed to the transport layer for transmission. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - this.lastResponse = response; - if (statusCode >= 200 && statusCode <= 699) { - this.stateTransition(TransactionState.Completed); - this.send(response).catch((error) => { - this.logTransportError(error, "Failed to send final response."); - }); - return; - } - break; - case TransactionState.Completed: - // Any other final responses passed by the TU to the server - // transaction MUST be discarded while in the "Completed" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - return; - case TransactionState.Terminated: - break; - default: - throw new Error(`Invalid state ${this.state}`); - } - const message = `Non-INVITE server transaction received unexpected ${statusCode} response from TU while in state ${this.state}.`; - this.logger.error(message); - throw new Error(message); - } - /** - * First, the procedures in [4] are followed, which attempt to deliver the response to a backup. - * If those should all fail, based on the definition of failure in [4], the server transaction SHOULD - * inform the TU that a failure has occurred, and SHOULD transition to the terminated state. - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - */ - onTransportError(error) { - if (this.user.onTransportError) { - this.user.onTransportError(error); - } - this.stateTransition(TransactionState.Terminated, true); - } - /** For logging. */ - typeToString() { - return "non-INVITE server transaction"; - } - stateTransition(newState, dueToTransportError = false) { - // Assert valid state transitions. - const invalidStateTransition = () => { - throw new Error(`Invalid state transition from ${this.state} to ${newState}`); - }; - switch (newState) { - case TransactionState.Trying: - invalidStateTransition(); - break; - case TransactionState.Proceeding: - if (this.state !== TransactionState.Trying) { - invalidStateTransition(); - } - break; - case TransactionState.Completed: - if (this.state !== TransactionState.Trying && this.state !== TransactionState.Proceeding) { - invalidStateTransition(); - } - break; - case TransactionState.Terminated: - if (this.state !== TransactionState.Proceeding && this.state !== TransactionState.Completed) { - if (!dueToTransportError) { - invalidStateTransition(); - } - } - break; - default: - invalidStateTransition(); - } - // When the server transaction enters the "Completed" state, it MUST set Timer J to fire - // in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === TransactionState.Completed) { - this.J = setTimeout(() => this.timerJ(), Timers.TIMER_J); - } - // The server transaction MUST be destroyed the instant it enters the "Terminated" state. - // https://tools.ietf.org/html/rfc3261#section-17.2.2 - if (newState === TransactionState.Terminated) { - this.dispose(); - } - this.setState(newState); - } - /** - * The server transaction remains in this state until Timer J fires, - * at which point it MUST transition to the "Terminated" state. - * https://tools.ietf.org/html/rfc3261#section-17.2.2 - */ - timerJ() { - this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`); - if (this.state === TransactionState.Completed) { - this.stateTransition(TransactionState.Terminated); - } - } -} diff --git a/lib/core/transactions/server-transaction.d.ts b/lib/core/transactions/server-transaction.d.ts deleted file mode 100644 index d28757edf..000000000 --- a/lib/core/transactions/server-transaction.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { IncomingRequestMessage } from "../messages"; -import { Transport } from "../transport"; -import { Transaction } from "./transaction"; -import { TransactionState } from "./transaction-state"; -import { ServerTransactionUser } from "./transaction-user"; -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -export declare abstract class ServerTransaction extends Transaction { - private _request; - protected user: ServerTransactionUser; - protected constructor(_request: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser, state: TransactionState, loggerCategory: string); - /** The incoming request the transaction handling. */ - get request(): IncomingRequestMessage; - /** - * Receive incoming requests from the transport which match this transaction. - * @param request - The incoming request. - */ - abstract receiveRequest(request: IncomingRequestMessage): void; - /** - * Receive outgoing responses to this request from the transaction user. - * Responses will be delivered to the transport as necessary. - * @param statusCode - Response status code. - * @param response - Response. - */ - abstract receiveResponse(statusCode: number, response: string): void; -} -//# sourceMappingURL=server-transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/server-transaction.d.ts.map b/lib/core/transactions/server-transaction.d.ts.map deleted file mode 100644 index aeff54873..000000000 --- a/lib/core/transactions/server-transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"server-transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/server-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;;;;;;;GAUG;AACH,8BAAsB,iBAAkB,SAAQ,WAAW;IAEvD,OAAO,CAAC,QAAQ;IAEhB,SAAS,CAAC,IAAI,EAAE,qBAAqB;IAHvC,SAAS,aACC,QAAQ,EAAE,sBAAsB,EACxC,SAAS,EAAE,SAAS,EACV,IAAI,EAAE,qBAAqB,EACrC,KAAK,EAAE,gBAAgB,EACvB,cAAc,EAAE,MAAM;IAKxB,qDAAqD;IACrD,IAAI,OAAO,IAAI,sBAAsB,CAEpC;IAED;;;OAGG;aACa,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAErE;;;;;OAKG;aACa,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;CAC5E"} \ No newline at end of file diff --git a/lib/core/transactions/server-transaction.js b/lib/core/transactions/server-transaction.js deleted file mode 100644 index 729c26cbb..000000000 --- a/lib/core/transactions/server-transaction.js +++ /dev/null @@ -1,23 +0,0 @@ -import { Transaction } from "./transaction"; -/** - * Server Transaction. - * @remarks - * The server transaction is responsible for the delivery of requests to - * the TU and the reliable transmission of responses. It accomplishes - * this through a state machine. Server transactions are created by the - * core when a request is received, and transaction handling is desired - * for that request (this is not always the case). - * https://tools.ietf.org/html/rfc3261#section-17.2 - * @public - */ -export class ServerTransaction extends Transaction { - constructor(_request, transport, user, state, loggerCategory) { - super(transport, user, _request.viaBranch, state, loggerCategory); - this._request = _request; - this.user = user; - } - /** The incoming request the transaction handling. */ - get request() { - return this._request; - } -} diff --git a/lib/core/transactions/transaction-state.d.ts b/lib/core/transactions/transaction-state.d.ts deleted file mode 100644 index 7b8e5165b..000000000 --- a/lib/core/transactions/transaction-state.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Transaction state. - * @public - */ -export declare enum TransactionState { - Accepted = "Accepted", - Calling = "Calling", - Completed = "Completed", - Confirmed = "Confirmed", - Proceeding = "Proceeding", - Terminated = "Terminated", - Trying = "Trying" -} -//# sourceMappingURL=transaction-state.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/transaction-state.d.ts.map b/lib/core/transactions/transaction-state.d.ts.map deleted file mode 100644 index 6cb37738a..000000000 --- a/lib/core/transactions/transaction-state.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction-state.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction-state.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,gBAAgB;IAC1B,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,SAAS,cAAc;IACvB,SAAS,cAAc;IACvB,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/lib/core/transactions/transaction-state.js b/lib/core/transactions/transaction-state.js deleted file mode 100644 index c940b2dc5..000000000 --- a/lib/core/transactions/transaction-state.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Transaction state. - * @public - */ -export var TransactionState; -(function (TransactionState) { - TransactionState["Accepted"] = "Accepted"; - TransactionState["Calling"] = "Calling"; - TransactionState["Completed"] = "Completed"; - TransactionState["Confirmed"] = "Confirmed"; - TransactionState["Proceeding"] = "Proceeding"; - TransactionState["Terminated"] = "Terminated"; - TransactionState["Trying"] = "Trying"; -})(TransactionState || (TransactionState = {})); diff --git a/lib/core/transactions/transaction-user.d.ts b/lib/core/transactions/transaction-user.d.ts deleted file mode 100644 index 4cfcb99d6..000000000 --- a/lib/core/transactions/transaction-user.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { TransportError } from "../exceptions"; -import { LoggerFactory } from "../log"; -import { IncomingResponseMessage } from "../messages"; -import { TransactionState } from "./transaction-state"; -/** - * Transaction User (TU). - * @remarks - * The layer of protocol processing that resides above the transaction layer. - * Transaction users include the UAC core, UAS core, and proxy core. - * https://tools.ietf.org/html/rfc3261#section-5 - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export interface TransactionUser { - /** - * Logger factory. - */ - loggerFactory: LoggerFactory; - /** - * Callback for notification of transaction state changes. - * - * Not called when transaction is constructed, so there is - * no notification of entering the initial transaction state. - * Otherwise, called once for each transaction state change. - * State changes adhere to the following RFCs. - * https://tools.ietf.org/html/rfc3261#section-17 - * https://tools.ietf.org/html/rfc6026 - */ - onStateChange?: (newState: TransactionState) => void; - /** - * Callback for notification of a transport error. - * - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * https://tools.ietf.org/html/rfc3261#section-17.1.4 - * https://tools.ietf.org/html/rfc3261#section-17.2.4 - * https://tools.ietf.org/html/rfc6026 - */ - onTransportError?: (error: TransportError) => void; -} -/** - * UAC Core Transaction User. - * @public - */ -export interface ClientTransactionUser extends TransactionUser { - /** - * Callback for request timeout error. - * - * When a timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * TU MUST be informed of a timeout. - * https://tools.ietf.org/html/rfc3261#section-17.1.2.2 - */ - onRequestTimeout?: () => void; - /** - * Callback for delegation of valid response handling. - * - * Valid responses are passed up to the TU from the client transaction. - * https://tools.ietf.org/html/rfc3261#section-17.1 - */ - receiveResponse?: (response: IncomingResponseMessage) => void; -} -/** - * UAS Core Transaction User. - * @public - */ -export interface ServerTransactionUser extends TransactionUser { -} -//# sourceMappingURL=transaction-user.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/transaction-user.d.ts.map b/lib/core/transactions/transaction-user.d.ts.map deleted file mode 100644 index 4d661ceb1..000000000 --- a/lib/core/transactions/transaction-user.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction-user.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction-user.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;;;;;;GAQG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAErD;;;;;;;;;;;OAWG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;CACpD;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;IAE9B;;;;;OAKG;IACH,eAAe,CAAC,EAAE,CAAC,QAAQ,EAAE,uBAAuB,KAAK,IAAI,CAAC;CAC/D;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;CAI7D"} \ No newline at end of file diff --git a/lib/core/transactions/transaction-user.js b/lib/core/transactions/transaction-user.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/transactions/transaction.d.ts b/lib/core/transactions/transaction.d.ts deleted file mode 100644 index 74d3b91e6..000000000 --- a/lib/core/transactions/transaction.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { TransportError } from "../exceptions"; -import { Logger } from "../log"; -import { Transport } from "../transport"; -import { TransactionState } from "./transaction-state"; -import { TransactionUser } from "./transaction-user"; -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -export declare abstract class Transaction { - private _transport; - private _user; - private _id; - private _state; - protected logger: Logger; - private listeners; - protected constructor(_transport: Transport, _user: TransactionUser, _id: string, _state: TransactionState, loggerCategory: string); - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - dispose(): void; - /** Transaction id. */ - get id(): string; - /** Transaction kind. Deprecated. */ - get kind(): string; - /** Transaction state. */ - get state(): TransactionState; - /** Transaction transport. */ - get transport(): Transport; - /** - * Sets up a function that will be called whenever the transaction state changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addStateChangeListener(listener: () => void, options?: { - once?: boolean; - }): void; - /** - * This is currently public so tests may spy on it. - * @internal - */ - notifyStateChangeListeners(): void; - /** - * Removes a listener previously registered with addStateListener. - * @param listener - Callback function. - */ - removeStateChangeListener(listener: () => void): void; - protected logTransportError(error: TransportError, message: string): void; - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - protected send(message: string): Promise; - protected setState(state: TransactionState): void; - protected typeToString(): string; - protected abstract onTransportError(error: TransportError): void; -} -//# sourceMappingURL=transaction.d.ts.map \ No newline at end of file diff --git a/lib/core/transactions/transaction.d.ts.map b/lib/core/transactions/transaction.d.ts.map deleted file mode 100644 index d84eb4926..000000000 --- a/lib/core/transactions/transaction.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../../src/core/transactions/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;;;;;;;;;;;;GAcG;AACH,8BAAsB,WAAW;IAM7B,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,KAAK;IACb,OAAO,CAAC,GAAG;IACX,OAAO,CAAC,MAAM;IARhB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,OAAO,CAAC,SAAS,CAA2B;IAE5C,SAAS,aACC,UAAU,EAAE,SAAS,EACrB,KAAK,EAAE,eAAe,EACtB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,gBAAgB,EAChC,cAAc,EAAE,MAAM;IAMxB;;;;;;;;;OASG;IACI,OAAO,IAAI,IAAI;IAItB,sBAAsB;IACtB,IAAI,EAAE,IAAI,MAAM,CAEf;IAED,oCAAoC;IACpC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,yBAAyB;IACzB,IAAI,KAAK,IAAI,gBAAgB,CAE5B;IAED,6BAA6B;IAC7B,IAAI,SAAS,IAAI,SAAS,CAEzB;IAED;;;;;;OAMG;IACI,sBAAsB,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;IAQvF;;;OAGG;IACI,0BAA0B,IAAI,IAAI;IAIzC;;;OAGG;IACI,yBAAyB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAI5D,SAAS,CAAC,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAMzE;;;;;OAKG;IACH,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB9C,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IASjD,SAAS,CAAC,YAAY,IAAI,MAAM;IAIhC,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;CACjE"} \ No newline at end of file diff --git a/lib/core/transactions/transaction.js b/lib/core/transactions/transaction.js deleted file mode 100644 index 542461c0f..000000000 --- a/lib/core/transactions/transaction.js +++ /dev/null @@ -1,126 +0,0 @@ -import { TransportError } from "../exceptions"; -/** - * Transaction. - * @remarks - * SIP is a transactional protocol: interactions between components take - * place in a series of independent message exchanges. Specifically, a - * SIP transaction consists of a single request and any responses to - * that request, which include zero or more provisional responses and - * one or more final responses. In the case of a transaction where the - * request was an INVITE (known as an INVITE transaction), the - * transaction also includes the ACK only if the final response was not - * a 2xx response. If the response was a 2xx, the ACK is not considered - * part of the transaction. - * https://tools.ietf.org/html/rfc3261#section-17 - * @public - */ -export class Transaction { - constructor(_transport, _user, _id, _state, loggerCategory) { - this._transport = _transport; - this._user = _user; - this._id = _id; - this._state = _state; - this.listeners = new Array(); - this.logger = _user.loggerFactory.getLogger(loggerCategory, _id); - this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`); - } - /** - * Destructor. - * Once the transaction is in the "terminated" state, it is destroyed - * immediately and there is no need to call `dispose`. However, if a - * transaction needs to be ended prematurely, the transaction user may - * do so by calling this method (for example, perhaps the UA is shutting down). - * No state transition will occur upon calling this method, all outstanding - * transmission timers will be cancelled, and use of the transaction after - * calling `dispose` is undefined. - */ - dispose() { - this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`); - } - /** Transaction id. */ - get id() { - return this._id; - } - /** Transaction kind. Deprecated. */ - get kind() { - throw new Error("Invalid kind."); - } - /** Transaction state. */ - get state() { - return this._state; - } - /** Transaction transport. */ - get transport() { - return this._transport; - } - /** - * Sets up a function that will be called whenever the transaction state changes. - * @param listener - Callback function. - * @param options - An options object that specifies characteristics about the listener. - * If once true, indicates that the listener should be invoked at most once after being added. - * If once true, the listener would be automatically removed when invoked. - */ - addStateChangeListener(listener, options) { - const onceWrapper = () => { - this.removeStateChangeListener(onceWrapper); - listener(); - }; - (options === null || options === void 0 ? void 0 : options.once) === true ? this.listeners.push(onceWrapper) : this.listeners.push(listener); - } - /** - * This is currently public so tests may spy on it. - * @internal - */ - notifyStateChangeListeners() { - this.listeners.slice().forEach((listener) => listener()); - } - /** - * Removes a listener previously registered with addStateListener. - * @param listener - Callback function. - */ - removeStateChangeListener(listener) { - this.listeners = this.listeners.filter((l) => l !== listener); - } - logTransportError(error, message) { - this.logger.error(error.message); - this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`); - this.logger.error(message); - } - /** - * Pass message to transport for transmission. If transport fails, - * the transaction user is notified by callback to onTransportError(). - * @returns - * Rejects with `TransportError` if transport fails. - */ - send(message) { - return this.transport.send(message).catch((error) => { - // If the transport rejects, it SHOULD reject with a TransportError. - // But the transport may be external code, so we are careful - // make sure we convert it to a TransportError if need be. - if (error instanceof TransportError) { - this.onTransportError(error); - throw error; - } - let transportError; - if (error && typeof error.message === "string") { - transportError = new TransportError(error.message); - } - else { - transportError = new TransportError(); - } - this.onTransportError(transportError); - throw transportError; - }); - } - setState(state) { - this.logger.debug(`State change to "${state}" on ${this.typeToString()} with id ${this.id}.`); - this._state = state; - if (this._user.onStateChange) { - this._user.onStateChange(state); - } - this.notifyStateChangeListeners(); - } - typeToString() { - return "UnknownType"; - } -} diff --git a/lib/core/transport.d.ts b/lib/core/transport.d.ts deleted file mode 100644 index ded0095d3..000000000 --- a/lib/core/transport.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Transport layer interface expected by the user agent core. - * - * @remarks - * The transport layer is responsible for the actual transmission of - * requests and responses over network transports. This includes - * determination of the connection to use for a request or response in - * the case of connection-oriented transports. - * https://tools.ietf.org/html/rfc3261#section-18 - * - * @public - */ -export interface Transport { - /** - * The transport protocol. - * - * @remarks - * Formatted as defined for the Via header sent-protocol transport. - * https://tools.ietf.org/html/rfc3261#section-20.42 - */ - readonly protocol: string; - /** - * Send a message. - * - * @remarks - * Resolves once message is sent. Otherwise rejects with an Error. - * - * @param message - Message to send. - */ - send(message: string): Promise; -} -//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/lib/core/transport.d.ts.map b/lib/core/transport.d.ts.map deleted file mode 100644 index 1a50dd250..000000000 --- a/lib/core/transport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/core/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,SAAS;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B;;;;;;;OAOG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC"} \ No newline at end of file diff --git a/lib/core/transport.js b/lib/core/transport.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/user-agent-core/allowed-methods.d.ts b/lib/core/user-agent-core/allowed-methods.d.ts deleted file mode 100644 index 25b377a6d..000000000 --- a/lib/core/user-agent-core/allowed-methods.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * FIXME: TODO: Should be configurable/variable. - */ -export declare const AllowedMethods: string[]; -//# sourceMappingURL=allowed-methods.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/allowed-methods.d.ts.map b/lib/core/user-agent-core/allowed-methods.d.ts.map deleted file mode 100644 index 236310557..000000000 --- a/lib/core/user-agent-core/allowed-methods.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"allowed-methods.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/allowed-methods.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,cAAc,UAa1B,CAAC"} \ No newline at end of file diff --git a/lib/core/user-agent-core/allowed-methods.js b/lib/core/user-agent-core/allowed-methods.js deleted file mode 100644 index 9667b54dc..000000000 --- a/lib/core/user-agent-core/allowed-methods.js +++ /dev/null @@ -1,18 +0,0 @@ -import { C } from "../messages"; -/** - * FIXME: TODO: Should be configurable/variable. - */ -export const AllowedMethods = [ - C.ACK, - C.BYE, - C.CANCEL, - C.INFO, - C.INVITE, - C.MESSAGE, - C.NOTIFY, - C.OPTIONS, - C.PRACK, - C.REFER, - C.REGISTER, - C.SUBSCRIBE -]; diff --git a/lib/core/user-agent-core/index.d.ts b/lib/core/user-agent-core/index.d.ts deleted file mode 100644 index 1dd187fa5..000000000 --- a/lib/core/user-agent-core/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./user-agent-core"; -export * from "./user-agent-core-configuration"; -export * from "./user-agent-core-delegate"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/index.d.ts.map b/lib/core/user-agent-core/index.d.ts.map deleted file mode 100644 index 3251b93f2..000000000 --- a/lib/core/user-agent-core/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC"} \ No newline at end of file diff --git a/lib/core/user-agent-core/index.js b/lib/core/user-agent-core/index.js deleted file mode 100644 index 189fc40b8..000000000 --- a/lib/core/user-agent-core/index.js +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./user-agent-core"; -export * from "./user-agent-core-configuration"; -export * from "./user-agent-core-delegate"; diff --git a/lib/core/user-agent-core/user-agent-core-configuration.d.ts b/lib/core/user-agent-core/user-agent-core-configuration.d.ts deleted file mode 100644 index 0a890a30f..000000000 --- a/lib/core/user-agent-core/user-agent-core-configuration.d.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { LoggerFactory } from "../log"; -import { DigestAuthentication, URI } from "../messages"; -import { Transport } from "../transport"; -/** - * Contact. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - * This is ported from UA.contact. - * FIXME: TODO: This is not a great rep for Contact - * and is used in a kinda hacky way herein. - * @public - */ -export interface Contact { - pubGruu: URI | undefined; - tempGruu: URI | undefined; - uri: URI; - toString: (options?: { - anonymous?: boolean; - outbound?: boolean; - }) => string; -} -/** - * User Agent Core configuration. - * @public - */ -export interface UserAgentCoreConfiguration { - /** - * Address-of-Record (AOR). - * @remarks - * https://tools.ietf.org/html/rfc3261#section-6 - */ - aor: URI; - /** - * Contact. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - */ - contact: Contact; - /** - * From header display name. - */ - displayName: string; - /** - * Logger factory. - */ - loggerFactory: LoggerFactory; - /** - * Force Via header field transport to TCP. - */ - hackViaTcp: boolean; - /** - * Preloaded route set. - */ - routeSet: Array; - /** - * Unique instance id. - */ - sipjsId: string; - /** - * Option tags of supported SIP extensions. - */ - supportedOptionTags: Array; - /** - * Option tags of supported SIP extensions. - * Used in responses. - * @remarks - * FIXME: Make this go away. - */ - supportedOptionTagsResponse: Array; - /** - * User-Agent header field value. - * @remarks - * https://tools.ietf.org/html/rfc3261#section-20.41 - */ - userAgentHeaderFieldValue: string | undefined; - /** - * Force use of "rport" Via header field parameter. - * @remarks - * https://www.ietf.org/rfc/rfc3581.txt - */ - viaForceRport: boolean; - /** - * Via header field host name or network address. - * @remarks - * The Via header field indicates the path taken by the request so far - * and indicates the path that should be followed in routing responses. - */ - viaHost: string; - /** - * DEPRECATED - * Authentication factory function. - */ - authenticationFactory(): DigestAuthentication | undefined; - /** - * DEPRECATED: This is a hack to get around `Transport` - * requiring the `UA` to start for construction. - */ - transportAccessor(): Transport | undefined; -} -//# sourceMappingURL=user-agent-core-configuration.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map b/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map deleted file mode 100644 index d734d54da..000000000 --- a/lib/core/user-agent-core/user-agent-core-configuration.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-core-configuration.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/user-agent-core-configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;;GAQG;AACH,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,GAAG,GAAG,SAAS,CAAC;IACzB,QAAQ,EAAE,GAAG,GAAG,SAAS,CAAC;IAC1B,GAAG,EAAE,GAAG,CAAC;IACT,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,MAAM,CAAC;CAC7E;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;OAIG;IACH,GAAG,EAAE,GAAG,CAAC;IAET;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAExB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,mBAAmB,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;;OAKG;IACH,2BAA2B,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE3C;;;;OAIG;IACH,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAE9C;;;;OAIG;IACH,aAAa,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,qBAAqB,IAAI,oBAAoB,GAAG,SAAS,CAAC;IAE1D;;;OAGG;IACH,iBAAiB,IAAI,SAAS,GAAG,SAAS,CAAC;CAC5C"} \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-configuration.js b/lib/core/user-agent-core/user-agent-core-configuration.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/user-agent-core/user-agent-core-delegate.d.ts b/lib/core/user-agent-core/user-agent-core-delegate.d.ts deleted file mode 100644 index 598f7776f..000000000 --- a/lib/core/user-agent-core/user-agent-core-delegate.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { IncomingInviteRequest, IncomingMessageRequest, IncomingNotifyRequest, IncomingReferRequest, IncomingRegisterRequest, IncomingSubscribeRequest } from "../messages"; -/** - * User Agent Core delegate. - * @public - */ -export interface UserAgentCoreDelegate { - /** - * Receive INVITE request. - * @param request - Incoming INVITE request. - */ - onInvite?(request: IncomingInviteRequest): void; - /** - * Receive MESSAGE request. - * @param request - Incoming MESSAGE request. - */ - onMessage?(request: IncomingMessageRequest): void; - /** - * DEPRECATED. Receive NOTIFY request. - * @param message - Incoming NOTIFY request. - */ - onNotify?(request: IncomingNotifyRequest): void; - /** - * Receive REFER request. - * @param request - Incoming REFER request. - */ - onRefer?(request: IncomingReferRequest): void; - /** - * Receive REGISTER request. - * @param request - Incoming REGISTER request. - */ - onRegister?(request: IncomingRegisterRequest): void; - /** - * Receive SUBSCRIBE request. - * @param request - Incoming SUBSCRIBE request. - */ - onSubscribe?(request: IncomingSubscribeRequest): void; -} -//# sourceMappingURL=user-agent-core-delegate.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map b/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map deleted file mode 100644 index e7d8950bd..000000000 --- a/lib/core/user-agent-core/user-agent-core-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-core-delegate.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/user-agent-core-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,wBAAwB,EACzB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;OAGG;IACH,SAAS,CAAC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAElD;;;OAGG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAEhD;;;OAGG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,UAAU,CAAC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAEpD;;;OAGG;IACH,WAAW,CAAC,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI,CAAC;CACvD"} \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core-delegate.js b/lib/core/user-agent-core/user-agent-core-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/core/user-agent-core/user-agent-core.d.ts b/lib/core/user-agent-core/user-agent-core.d.ts deleted file mode 100644 index 791db205e..000000000 --- a/lib/core/user-agent-core/user-agent-core.d.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { Dialog } from "../dialogs"; -import { LoggerFactory } from "../log"; -import { Body, IncomingRequestMessage, IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingMessageRequest, OutgoingPublishRequest, OutgoingRegisterRequest, OutgoingRequest, OutgoingRequestDelegate, OutgoingRequestMessage, OutgoingRequestMessageOptions, OutgoingResponse, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate, ResponseOptions, URI } from "../messages"; -import { Transport } from "../transport"; -import { SubscribeUserAgentClient, UserAgentClient, UserAgentServer } from "../user-agents"; -import { UserAgentCoreConfiguration } from "./user-agent-core-configuration"; -import { UserAgentCoreDelegate } from "./user-agent-core-delegate"; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export declare class UserAgentCore { - /** Configuration. */ - configuration: UserAgentCoreConfiguration; - /** Delegate. */ - delegate: UserAgentCoreDelegate; - /** Dialogs. */ - dialogs: Map; - /** Subscribers. */ - subscribers: Map; - /** UACs. */ - userAgentClients: Map; - /** UASs. */ - userAgentServers: Map; - private logger; - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - constructor(configuration: UserAgentCoreConfiguration, delegate?: UserAgentCoreDelegate); - /** Destructor. */ - dispose(): void; - /** Reset. */ - reset(): void; - /** Logger factory. */ - get loggerFactory(): LoggerFactory; - /** Transport. */ - get transport(): Transport; - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - invite(request: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate): OutgoingInviteRequest; - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - message(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingMessageRequest; - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - publish(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingPublishRequest; - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - register(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRegisterRequest; - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - subscribe(request: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate): OutgoingSubscribeRequest; - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - request(request: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate): OutgoingRequest; - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - makeOutgoingRequestMessage(method: string, requestURI: URI, fromURI: URI, toURI: URI, options: OutgoingRequestMessageOptions, extraHeaders?: Array, body?: Body): OutgoingRequestMessage; - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - receiveIncomingRequestFromTransport(message: IncomingRequestMessage): void; - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - receiveIncomingResponseFromTransport(message: IncomingResponseMessage): void; - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - replyStateless(message: IncomingRequestMessage, options: ResponseOptions): OutgoingResponse; - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - private receiveRequestFromTransport; - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - private receiveRequest; - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - private receiveInsideDialogRequest; - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - private receiveOutsideDialogRequest; - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - private receiveResponseFromTransport; -} -//# sourceMappingURL=user-agent-core.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core.d.ts.map b/lib/core/user-agent-core/user-agent-core.d.ts.map deleted file mode 100644 index f341f1b00..000000000 --- a/lib/core/user-agent-core/user-agent-core.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-core.d.ts","sourceRoot":"","sources":["../../../src/core/user-agent-core/user-agent-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAU,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EACL,IAAI,EAGJ,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,uBAAuB,EACvB,eAAe,EACf,uBAAuB,EACvB,sBAAsB,EACtB,6BAA6B,EAC7B,gBAAgB,EAChB,wBAAwB,EACxB,gCAAgC,EAChC,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAUL,wBAAwB,EAExB,eAAe,EACf,eAAe,EAChB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAOnE;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,aAAa;IACxB,qBAAqB;IACd,aAAa,EAAE,0BAA0B,CAAC;IACjD,gBAAgB;IACT,QAAQ,EAAE,qBAAqB,CAAC;IACvC,eAAe;IACR,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,mBAAmB;IACZ,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;IAC1D,YAAY;IACL,gBAAgB,+BAAsC;IAC7D,YAAY;IACL,gBAAgB,+BAAsC;IAE7D,OAAO,CAAC,MAAM,CAAS;IAEvB;;;;OAIG;gBACS,aAAa,EAAE,0BAA0B,EAAE,QAAQ,GAAE,qBAA0B;IAQ3F,kBAAkB;IACX,OAAO,IAAI,IAAI;IAItB,aAAa;IACN,KAAK,IAAI,IAAI;IAWpB,sBAAsB;IACtB,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,iBAAiB;IACjB,IAAI,SAAS,IAAI,SAAS,CAMzB;IAED;;;;OAIG;IACI,MAAM,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,6BAA6B,GAAG,qBAAqB;IAI/G;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,sBAAsB;IAI3G;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,sBAAsB;IAI3G;;;;OAIG;IACI,QAAQ,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,uBAAuB;IAI7G;;;;OAIG;IACI,SAAS,CACd,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,gCAAgC,GAC1C,wBAAwB;IAI3B;;;;OAIG;IACI,OAAO,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,GAAG,eAAe;IAIpG;;;;;;;;;OASG;IACI,0BAA0B,CAC/B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,GAAG,EACf,OAAO,EAAE,GAAG,EACZ,KAAK,EAAE,GAAG,EACV,OAAO,EAAE,6BAA6B,EACtC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAC5B,IAAI,CAAC,EAAE,IAAI,GACV,sBAAsB;IAqCzB;;;OAGG;IACI,mCAAmC,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAIjF;;;OAGG;IACI,oCAAoC,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAInF;;;;;;;;;;;;;;;OAeG;IACI,cAAc,CAAC,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,eAAe,GAAG,gBAAgB;IAmBlG;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,2BAA2B;IA4HnC;;;;;;;;OAQG;IACH,OAAO,CAAC,cAAc;IAgJtB;;;;;;;;;OASG;IACH,OAAO,CAAC,0BAA0B;IAqIlC;;;;;OAKG;IACH,OAAO,CAAC,2BAA2B;IA6GnC;;;;;;;;OAQG;IACH,OAAO,CAAC,4BAA4B;CA0DrC"} \ No newline at end of file diff --git a/lib/core/user-agent-core/user-agent-core.js b/lib/core/user-agent-core/user-agent-core.js deleted file mode 100644 index 18b4257ae..000000000 --- a/lib/core/user-agent-core/user-agent-core.js +++ /dev/null @@ -1,782 +0,0 @@ -import { C, constructOutgoingResponse, OutgoingRequestMessage } from "../messages"; -import { InviteServerTransaction, NonInviteClientTransaction, TransactionState } from "../transactions"; -import { InviteUserAgentClient, InviteUserAgentServer, MessageUserAgentClient, MessageUserAgentServer, NotifyUserAgentServer, PublishUserAgentClient, ReferUserAgentServer, RegisterUserAgentClient, RegisterUserAgentServer, SubscribeUserAgentClient, SubscribeUserAgentServer, UserAgentClient } from "../user-agents"; -import { AllowedMethods } from "./allowed-methods"; -/** - * This is ported from UA.C.ACCEPTED_BODY_TYPES. - * FIXME: TODO: Should be configurable/variable. - */ -const acceptedBodyTypes = ["application/sdp", "application/dtmf-relay"]; -/** - * User Agent Core. - * @remarks - * Core designates the functions specific to a particular type - * of SIP entity, i.e., specific to either a stateful or stateless - * proxy, a user agent or registrar. All cores, except those for - * the stateless proxy, are transaction users. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAC Core: The set of processing functions required of a UAC that - * reside above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * - * UAS Core: The set of processing functions required at a UAS that - * resides above the transaction and transport layers. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export class UserAgentCore { - /** - * Constructor. - * @param configuration - Configuration. - * @param delegate - Delegate. - */ - constructor(configuration, delegate = {}) { - /** UACs. */ - this.userAgentClients = new Map(); - /** UASs. */ - this.userAgentServers = new Map(); - this.configuration = configuration; - this.delegate = delegate; - this.dialogs = new Map(); - this.subscribers = new Map(); - this.logger = configuration.loggerFactory.getLogger("sip.user-agent-core"); - } - /** Destructor. */ - dispose() { - this.reset(); - } - /** Reset. */ - reset() { - this.dialogs.forEach((dialog) => dialog.dispose()); - this.dialogs.clear(); - this.subscribers.forEach((subscriber) => subscriber.dispose()); - this.subscribers.clear(); - this.userAgentClients.forEach((uac) => uac.dispose()); - this.userAgentClients.clear(); - this.userAgentServers.forEach((uac) => uac.dispose()); - this.userAgentServers.clear(); - } - /** Logger factory. */ - get loggerFactory() { - return this.configuration.loggerFactory; - } - /** Transport. */ - get transport() { - const transport = this.configuration.transportAccessor(); - if (!transport) { - throw new Error("Transport undefined."); - } - return transport; - } - /** - * Send INVITE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - invite(request, delegate) { - return new InviteUserAgentClient(this, request, delegate); - } - /** - * Send MESSAGE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - message(request, delegate) { - return new MessageUserAgentClient(this, request, delegate); - } - /** - * Send PUBLISH. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - publish(request, delegate) { - return new PublishUserAgentClient(this, request, delegate); - } - /** - * Send REGISTER. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - register(request, delegate) { - return new RegisterUserAgentClient(this, request, delegate); - } - /** - * Send SUBSCRIBE. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - subscribe(request, delegate) { - return new SubscribeUserAgentClient(this, request, delegate); - } - /** - * Send a request. - * @param request - Outgoing request. - * @param delegate - Request delegate. - */ - request(request, delegate) { - return new UserAgentClient(NonInviteClientTransaction, this, request, delegate); - } - /** - * Outgoing request message factory function. - * @param method - Method. - * @param requestURI - Request-URI. - * @param fromURI - From URI. - * @param toURI - To URI. - * @param options - Request options. - * @param extraHeaders - Extra headers to add. - * @param body - Message body. - */ - makeOutgoingRequestMessage(method, requestURI, fromURI, toURI, options, extraHeaders, body) { - // default values from user agent configuration - const callIdPrefix = this.configuration.sipjsId; - const fromDisplayName = this.configuration.displayName; - const forceRport = this.configuration.viaForceRport; - const hackViaTcp = this.configuration.hackViaTcp; - const optionTags = this.configuration.supportedOptionTags.slice(); - if (method === C.REGISTER) { - optionTags.push("path", "gruu"); - } - if (method === C.INVITE && (this.configuration.contact.pubGruu || this.configuration.contact.tempGruu)) { - optionTags.push("gruu"); - } - const routeSet = this.configuration.routeSet; - const userAgentString = this.configuration.userAgentHeaderFieldValue; - const viaHost = this.configuration.viaHost; - const defaultOptions = { - callIdPrefix, - forceRport, - fromDisplayName, - hackViaTcp, - optionTags, - routeSet, - userAgentString, - viaHost - }; - // merge provided options with default options - const requestOptions = Object.assign(Object.assign({}, defaultOptions), options); - return new OutgoingRequestMessage(method, requestURI, fromURI, toURI, requestOptions, extraHeaders, body); - } - /** - * Handle an incoming request message from the transport. - * @param message - Incoming request message from transport layer. - */ - receiveIncomingRequestFromTransport(message) { - this.receiveRequestFromTransport(message); - } - /** - * Handle an incoming response message from the transport. - * @param message - Incoming response message from transport layer. - */ - receiveIncomingResponseFromTransport(message) { - this.receiveResponseFromTransport(message); - } - /** - * A stateless UAS is a UAS that does not maintain transaction state. - * It replies to requests normally, but discards any state that would - * ordinarily be retained by a UAS after a response has been sent. If a - * stateless UAS receives a retransmission of a request, it regenerates - * the response and re-sends it, just as if it were replying to the first - * instance of the request. A UAS cannot be stateless unless the request - * processing for that method would always result in the same response - * if the requests are identical. This rules out stateless registrars, - * for example. Stateless UASs do not use a transaction layer; they - * receive requests directly from the transport layer and send responses - * directly to the transport layer. - * https://tools.ietf.org/html/rfc3261#section-8.2.7 - * @param message - Incoming request message to reply to. - * @param statusCode - Status code to reply with. - */ - replyStateless(message, options) { - const userAgent = this.configuration.userAgentHeaderFieldValue; - const supported = this.configuration.supportedOptionTagsResponse; - options = Object.assign(Object.assign({}, options), { userAgent, supported }); - const response = constructOutgoingResponse(message, options); - this.transport.send(response.message).catch((error) => { - // If the transport rejects, it SHOULD reject with a TransportError. - // But the transport may be external code, so we are careful... - if (error instanceof Error) { - this.logger.error(error.message); - } - this.logger.error(`Transport error occurred sending stateless reply to ${message.method} request.`); - // TODO: Currently there is no hook to provide notification that a transport error occurred - // and throwing would result in an uncaught error (in promise), so we silently eat the error. - // Furthermore, silently eating stateless reply transport errors is arguably what we want to do here. - }); - return response; - } - /** - * In Section 18.2.1, replace the last paragraph with: - * - * Next, the server transport attempts to match the request to a - * server transaction. It does so using the matching rules described - * in Section 17.2.3. If a matching server transaction is found, the - * request is passed to that transaction for processing. If no match - * is found, the request is passed to the core, which may decide to - * construct a new server transaction for that request. - * https://tools.ietf.org/html/rfc6026#section-8.10 - * @param message - Incoming request message from transport layer. - */ - receiveRequestFromTransport(message) { - // When a request is received from the network by the server, it has to - // be matched to an existing transaction. This is accomplished in the - // following manner. - // - // The branch parameter in the topmost Via header field of the request - // is examined. If it is present and begins with the magic cookie - // "z9hG4bK", the request was generated by a client transaction - // compliant to this specification. Therefore, the branch parameter - // will be unique across all transactions sent by that client. The - // request matches a transaction if: - // - // 1. the branch parameter in the request is equal to the one in the - // top Via header field of the request that created the - // transaction, and - // - // 2. the sent-by value in the top Via of the request is equal to the - // one in the request that created the transaction, and - // - // 3. the method of the request matches the one that created the - // transaction, except for ACK, where the method of the request - // that created the transaction is INVITE. - // - // This matching rule applies to both INVITE and non-INVITE transactions - // alike. - // - // The sent-by value is used as part of the matching process because - // there could be accidental or malicious duplication of branch - // parameters from different clients. - // https://tools.ietf.org/html/rfc3261#section-17.2.3 - const transactionId = message.viaBranch; // FIXME: Currently only using rule 1... - const uas = this.userAgentServers.get(transactionId); - // When receiving an ACK that matches an existing INVITE server - // transaction and that does not contain a branch parameter containing - // the magic cookie defined in RFC 3261, the matching transaction MUST - // be checked to see if it is in the "Accepted" state. If it is, then - // the ACK must be passed directly to the transaction user instead of - // being absorbed by the transaction state machine. This is necessary - // as requests from RFC 2543 clients will not include a unique branch - // parameter, and the mechanisms for calculating the transaction ID from - // such a request will be the same for both INVITE and ACKs. - // https://tools.ietf.org/html/rfc6026#section-6 - // Any ACKs received from the network while in the "Accepted" state MUST be - // passed directly to the TU and not absorbed. - // https://tools.ietf.org/html/rfc6026#section-7.1 - if (message.method === C.ACK) { - if (uas && uas.transaction.state === TransactionState.Accepted) { - if (uas instanceof InviteUserAgentServer) { - // These are ACKs matching an INVITE server transaction. - // These should never happen with RFC 3261 compliant user agents - // (would be a broken ACK to negative final response or something) - // but is apparently how RFC 2543 user agents do things. - // We are not currently supporting this case. - // NOTE: Not backwards compatible with RFC 2543 (no support for strict-routing). - this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${transactionId}.`); - return; - } - } - } - // The CANCEL method requests that the TU at the server side cancel a - // pending transaction. The TU determines the transaction to be - // cancelled by taking the CANCEL request, and then assuming that the - // request method is anything but CANCEL or ACK and applying the - // transaction matching procedures of Section 17.2.3. The matching - // transaction is the one to be cancelled. - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (message.method === C.CANCEL) { - if (uas) { - // Regardless of the method of the original request, as long as the - // CANCEL matched an existing transaction, the UAS answers the CANCEL - // request itself with a 200 (OK) response. - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 200 }); - // If the transaction for the original request still exists, the behavior - // of the UAS on receiving a CANCEL request depends on whether it has already - // sent a final response for the original request. If it has, the CANCEL - // request has no effect on the processing of the original request, no - // effect on any session state, and no effect on the responses generated - // for the original request. If the UAS has not issued a final response - // for the original request, its behavior depends on the method of the - // original request. If the original request was an INVITE, the UAS - // SHOULD immediately respond to the INVITE with a 487 (Request - // Terminated). - // https://tools.ietf.org/html/rfc3261#section-9.2 - if (uas.transaction instanceof InviteServerTransaction && - uas.transaction.state === TransactionState.Proceeding) { - if (uas instanceof InviteUserAgentServer) { - uas.receiveCancel(message); - } - // A CANCEL request has no impact on the processing of - // transactions with any other method defined in this specification. - // https://tools.ietf.org/html/rfc3261#section-9.2 - } - } - else { - // If the UAS did not find a matching transaction for the CANCEL - // according to the procedure above, it SHOULD respond to the CANCEL - // with a 481 (Call Leg/Transaction Does Not Exist). - // https://tools.ietf.org/html/rfc3261#section-9.2 - this.replyStateless(message, { statusCode: 481 }); - } - return; - } - // If a matching server transaction is found, the request is passed to that - // transaction for processing. - // https://tools.ietf.org/html/rfc6026#section-8.10 - if (uas) { - uas.transaction.receiveRequest(message); - return; - } - // If no match is found, the request is passed to the core, which may decide to - // construct a new server transaction for that request. - // https://tools.ietf.org/html/rfc6026#section-8.10 - this.receiveRequest(message); - return; - } - /** - * UAC and UAS procedures depend strongly on two factors. First, based - * on whether the request or response is inside or outside of a dialog, - * and second, based on the method of a request. Dialogs are discussed - * thoroughly in Section 12; they represent a peer-to-peer relationship - * between user agents and are established by specific SIP methods, such - * as INVITE. - * @param message - Incoming request message. - */ - receiveRequest(message) { - // 8.2 UAS Behavior - // UASs SHOULD process the requests in the order of the steps that - // follow in this section (that is, starting with authentication, then - // inspecting the method, the header fields, and so on throughout the - // remainder of this section). - // https://tools.ietf.org/html/rfc3261#section-8.2 - // 8.2.1 Method Inspection - // Once a request is authenticated (or authentication is skipped), the - // UAS MUST inspect the method of the request. If the UAS recognizes - // but does not support the method of a request, it MUST generate a 405 - // (Method Not Allowed) response. Procedures for generating responses - // are described in Section 8.2.6. The UAS MUST also add an Allow - // header field to the 405 (Method Not Allowed) response. The Allow - // header field MUST list the set of methods supported by the UAS - // generating the message. - // https://tools.ietf.org/html/rfc3261#section-8.2.1 - if (!AllowedMethods.includes(message.method)) { - const allowHeader = "Allow: " + AllowedMethods.toString(); - this.replyStateless(message, { - statusCode: 405, - extraHeaders: [allowHeader] - }); - return; - } - // 8.2.2 Header Inspection - // https://tools.ietf.org/html/rfc3261#section-8.2.2 - if (!message.ruri) { - // FIXME: A request message should always have an ruri - throw new Error("Request-URI undefined."); - } - // 8.2.2.1 To and Request-URI - // If the Request-URI uses a scheme not supported by the UAS, it SHOULD - // reject the request with a 416 (Unsupported URI Scheme) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.ruri.scheme !== "sip") { - this.replyStateless(message, { statusCode: 416 }); - return; - } - // 8.2.2.1 To and Request-URI - // If the Request-URI does not identify an address that the - // UAS is willing to accept requests for, it SHOULD reject - // the request with a 404 (Not Found) response. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - const ruri = message.ruri; - const ruriMatches = (uri) => { - return !!uri && uri.user === ruri.user; - }; - if (!ruriMatches(this.configuration.aor) && - !(ruriMatches(this.configuration.contact.uri) || - ruriMatches(this.configuration.contact.pubGruu) || - ruriMatches(this.configuration.contact.tempGruu))) { - this.logger.warn("Request-URI does not point to us."); - if (message.method !== C.ACK) { - this.replyStateless(message, { statusCode: 404 }); - } - return; - } - // 8.2.2.1 To and Request-URI - // Other potential sources of received Request-URIs include - // the Contact header fields of requests and responses sent by the UA - // that establish or refresh dialogs. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.1 - if (message.method === C.INVITE) { - if (!message.hasHeader("Contact")) { - this.replyStateless(message, { - statusCode: 400, - reasonPhrase: "Missing Contact Header" - }); - return; - } - } - // 8.2.2.2 Merged Requests - // If the request has no tag in the To header field, the UAS core MUST - // check the request against ongoing transactions. If the From tag, - // Call-ID, and CSeq exactly match those associated with an ongoing - // transaction, but the request does not match that transaction (based - // on the matching rules in Section 17.2.3), the UAS core SHOULD - // generate a 482 (Loop Detected) response and pass it to the server - // transaction. - // - // The same request has arrived at the UAS more than once, following - // different paths, most likely due to forking. The UAS processes - // the first such request received and responds with a 482 (Loop - // Detected) to the rest of them. - // https://tools.ietf.org/html/rfc3261#section-8.2.2.2 - if (!message.toTag) { - const transactionId = message.viaBranch; - if (!this.userAgentServers.has(transactionId)) { - const mergedRequest = Array.from(this.userAgentServers.values()).some((uas) => uas.transaction.request.fromTag === message.fromTag && - uas.transaction.request.callId === message.callId && - uas.transaction.request.cseq === message.cseq); - if (mergedRequest) { - this.replyStateless(message, { statusCode: 482 }); - return; - } - } - } - // 8.2.2.3 Require - // https://tools.ietf.org/html/rfc3261#section-8.2.2.3 - // TODO - // 8.2.3 Content Processing - // https://tools.ietf.org/html/rfc3261#section-8.2.3 - // TODO - // 8.2.4 Applying Extensions - // https://tools.ietf.org/html/rfc3261#section-8.2.4 - // TODO - // 8.2.5 Processing the Request - // Assuming all of the checks in the previous subsections are passed, - // the UAS processing becomes method-specific. - // https://tools.ietf.org/html/rfc3261#section-8.2.5 - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // In that case, the UAS first applies the same processing rules for - // requests outside of a dialog, discussed in Section 8.2. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.toTag) { - this.receiveInsideDialogRequest(message); - } - else { - this.receiveOutsideDialogRequest(message); - } - return; - } - /** - * Once a dialog has been established between two UAs, either of them - * MAY initiate new transactions as needed within the dialog. The UA - * sending the request will take the UAC role for the transaction. The - * UA receiving the request will take the UAS role. Note that these may - * be different roles than the UAs held during the transaction that - * established the dialog. - * https://tools.ietf.org/html/rfc3261#section-12.2 - * @param message - Incoming request message. - */ - receiveInsideDialogRequest(message) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (message.method === C.NOTIFY) { - const event = message.parseHeader("Event"); - if (!event || !event.event) { - this.replyStateless(message, { statusCode: 489 }); - return; - } - // FIXME: Subscriber id should also matching on event id. - const subscriberId = message.callId + message.toTag + event.event; - const subscriber = this.subscribers.get(subscriberId); - if (subscriber) { - const uas = new NotifyUserAgentServer(this, message); - subscriber.onNotify(uas); - return; - } - } - // Requests sent within a dialog, as any other requests, are atomic. If - // a particular request is accepted by the UAS, all the state changes - // associated with it are performed. If the request is rejected, none - // of the state changes are performed. - // - // Note that some requests, such as INVITEs, affect several pieces of - // state. - // - // The UAS will receive the request from the transaction layer. If the - // request has a tag in the To header field, the UAS core computes the - // dialog identifier corresponding to the request and compares it with - // existing dialogs. If there is a match, this is a mid-dialog request. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - const dialogId = message.callId + message.toTag + message.fromTag; - const dialog = this.dialogs.get(dialogId); - if (dialog) { - // [Sip-implementors] Reg. SIP reinvite, UPDATE and OPTIONS - // You got the question right. - // - // And you got the right answer too. :-) - // - // Thanks, - // Paul - // - // Robert Sparks wrote: - // > So I've lost track of the question during the musing. - // > - // > I _think_ the fundamental question being asked is this: - // > - // > Is an endpoint required to reject (with a 481) an OPTIONS request that - // > arrives with at to-tag but does not match any existing dialog state. - // > (Assuming some earlier requirement hasn't forced another error code). Or - // > is it OK if it just sends - // > a 200 OK anyhow. - // > - // > My take on the collection of specs is that its _not_ ok for it to send - // > the 200 OK anyhow and that it is required to send - // > the 481. I base this primarily on these sentences from 11.2 in 3261: - // > - // > The response to an OPTIONS is constructed using the standard rules - // > for a SIP response as discussed in Section 8.2.6. The response code - // > chosen MUST be the same that would have been chosen had the request - // > been an INVITE. - // > - // > Did I miss the point of the question? - // > - // > On May 15, 2008, at 12:48 PM, Paul Kyzivat wrote: - // > - // >> [Including Robert in hopes of getting his insight on this.] - // https://lists.cs.columbia.edu/pipermail/sip-implementors/2008-May/019178.html - // - // Requests that do not change in any way the state of a dialog may be - // received within a dialog (for example, an OPTIONS request). They are - // processed as if they had been received outside the dialog. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - if (message.method === C.OPTIONS) { - const allowHeader = "Allow: " + AllowedMethods.toString(); - const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - return; - } - // Pass the incoming request to the dialog for further handling. - dialog.receiveRequest(message); - return; - } - // The most important behaviors of a stateless UAS are the following: - // ... - // o A stateless UAS MUST ignore ACK requests. - // ... - // https://tools.ietf.org/html/rfc3261#section-8.2.7 - if (message.method === C.ACK) { - // If a final response to an INVITE was sent statelessly, - // the corresponding ACK: - // - will not match an existing transaction - // - may have tag in the To header field - // - not not match any existing dialogs - // Absorb unmatched ACKs. - return; - } - // If the request has a tag in the To header field, but the dialog - // identifier does not match any existing dialogs, the UAS may have - // crashed and restarted, or it may have received a request for a - // different (possibly failed) UAS (the UASs can construct the To tags - // so that a UAS can identify that the tag was for a UAS for which it is - // providing recovery). Another possibility is that the incoming - // request has been simply mis-routed. Based on the To tag, the UAS MAY - // either accept or reject the request. Accepting the request for - // acceptable To tags provides robustness, so that dialogs can persist - // even through crashes. UAs wishing to support this capability must - // take into consideration some issues such as choosing monotonically - // increasing CSeq sequence numbers even across reboots, reconstructing - // the route set, and accepting out-of-range RTP timestamps and sequence - // numbers. - // - // If the UAS wishes to reject the request because it does not wish to - // recreate the dialog, it MUST respond to the request with a 481 - // (Call/Transaction Does Not Exist) status code and pass that to the - // server transaction. - // https://tools.ietf.org/html/rfc3261#section-12.2.2 - this.replyStateless(message, { statusCode: 481 }); - return; - } - /** - * Assuming all of the checks in the previous subsections are passed, - * the UAS processing becomes method-specific. - * https://tools.ietf.org/html/rfc3261#section-8.2.5 - * @param message - Incoming request message. - */ - receiveOutsideDialogRequest(message) { - switch (message.method) { - case C.ACK: - // Absorb stray out of dialog ACKs - break; - case C.BYE: - // If the BYE does not match an existing dialog, the UAS core SHOULD - // generate a 481 (Call/Transaction Does Not Exist) response and pass - // that to the server transaction. This rule means that a BYE sent - // without tags by a UAC will be rejected. - // https://tools.ietf.org/html/rfc3261#section-15.1.2 - this.replyStateless(message, { statusCode: 481 }); - break; - case C.CANCEL: - throw new Error(`Unexpected out of dialog request method ${message.method}.`); - break; - case C.INFO: - // Use of the INFO method does not constitute a separate dialog usage. - // INFO messages are always part of, and share the fate of, an invite - // dialog usage [RFC5057]. INFO messages cannot be sent as part of - // other dialog usages, or outside an existing dialog. - // https://tools.ietf.org/html/rfc6086#section-1 - this.replyStateless(message, { statusCode: 405 }); // Should never happen - break; - case C.INVITE: - // https://tools.ietf.org/html/rfc3261#section-13.3.1 - { - const uas = new InviteUserAgentServer(this, message); - this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject(); - } - break; - case C.MESSAGE: - // MESSAGE requests are discouraged inside a dialog. Implementations - // are restricted from creating a usage for the purpose of carrying a - // sequence of MESSAGE requests (though some implementations use it that - // way, against the standard recommendation). - // https://tools.ietf.org/html/rfc5057#section-5.3 - { - const uas = new MessageUserAgentServer(this, message); - this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept(); - } - break; - case C.NOTIFY: - // Obsoleted by: RFC 6665 - // If any non-SUBSCRIBE mechanisms are defined to create subscriptions, - // it is the responsibility of the parties defining those mechanisms to - // ensure that correlation of a NOTIFY message to the corresponding - // subscription is possible. Designers of such mechanisms are also - // warned to make a distinction between sending a NOTIFY message to a - // subscriber who is aware of the subscription, and sending a NOTIFY - // message to an unsuspecting node. The latter behavior is invalid, and - // MUST receive a "481 Subscription does not exist" response (unless - // some other 400- or 500-class error code is more applicable), as - // described in section 3.2.4. In other words, knowledge of a - // subscription must exist in both the subscriber and the notifier to be - // valid, even if installed via a non-SUBSCRIBE mechanism. - // https://tools.ietf.org/html/rfc3265#section-3.2 - // - // NOTIFY requests are sent to inform subscribers of changes in state to - // which the subscriber has a subscription. Subscriptions are created - // using the SUBSCRIBE method. In legacy implementations, it is - // possible that other means of subscription creation have been used. - // However, this specification does not allow the creation of - // subscriptions except through SUBSCRIBE requests and (for backwards- - // compatibility) REFER requests [RFC3515]. - // https://tools.ietf.org/html/rfc6665#section-3.2 - { - const uas = new NotifyUserAgentServer(this, message); - this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.reject({ statusCode: 405 }); - } - break; - case C.OPTIONS: - // https://tools.ietf.org/html/rfc3261#section-11.2 - { - const allowHeader = "Allow: " + AllowedMethods.toString(); - const acceptHeader = "Accept: " + acceptedBodyTypes.toString(); - this.replyStateless(message, { - statusCode: 200, - extraHeaders: [allowHeader, acceptHeader] - }); - } - break; - case C.REFER: - // https://tools.ietf.org/html/rfc3515#section-2.4.2 - { - const uas = new ReferUserAgentServer(this, message); - this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject({ statusCode: 405 }); - } - break; - case C.REGISTER: - // https://tools.ietf.org/html/rfc3261#section-10.3 - { - const uas = new RegisterUserAgentServer(this, message); - this.delegate.onRegister ? this.delegate.onRegister(uas) : uas.reject({ statusCode: 405 }); - } - break; - case C.SUBSCRIBE: - // https://tools.ietf.org/html/rfc6665#section-4.2 - { - const uas = new SubscribeUserAgentServer(this, message); - this.delegate.onSubscribe ? this.delegate.onSubscribe(uas) : uas.reject({ statusCode: 480 }); - } - break; - default: - throw new Error(`Unexpected out of dialog request method ${message.method}.`); - } - return; - } - /** - * Responses are first processed by the transport layer and then passed - * up to the transaction layer. The transaction layer performs its - * processing and then passes the response up to the TU. The majority - * of response processing in the TU is method specific. However, there - * are some general behaviors independent of the method. - * https://tools.ietf.org/html/rfc3261#section-8.1.3 - * @param message - Incoming response message from transport layer. - */ - receiveResponseFromTransport(message) { - // 8.1.3.1 Transaction Layer Errors - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // Handled by transaction layer callbacks. - // 8.1.3.2 Unrecognized Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - // TODO - // 8.1.3.3 Vias - // https://tools.ietf.org/html/rfc3261#section-8.1.3.3 - if (message.getHeaders("via").length > 1) { - this.logger.warn("More than one Via header field present in the response, dropping"); - return; - } - // 8.1.3.4 Processing 3xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.4 - // TODO - // 8.1.3.5 Processing 4xx Responses - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - // TODO - // When the transport layer in the client receives a response, it has to - // determine which client transaction will handle the response, so that - // the processing of Sections 17.1.1 and 17.1.2 can take place. The - // branch parameter in the top Via header field is used for this - // purpose. A response matches a client transaction under two - // conditions: - // - // 1. If the response has the same value of the branch parameter in - // the top Via header field as the branch parameter in the top - // Via header field of the request that created the transaction. - // - // 2. If the method parameter in the CSeq header field matches the - // method of the request that created the transaction. The - // method is needed since a CANCEL request constitutes a - // different transaction, but shares the same value of the branch - // parameter. - // https://tools.ietf.org/html/rfc3261#section-17.1.3 - const userAgentClientId = message.viaBranch + message.method; - const userAgentClient = this.userAgentClients.get(userAgentClientId); - // The client transport uses the matching procedures of Section - // 17.1.3 to attempt to match the response to an existing - // transaction. If there is a match, the response MUST be passed to - // that transaction. Otherwise, any element other than a stateless - // proxy MUST silently discard the response. - // https://tools.ietf.org/html/rfc6026#section-8.9 - if (userAgentClient) { - userAgentClient.transaction.receiveResponse(message); - } - else { - this.logger.warn(`Discarding unmatched ${message.statusCode} response to ${message.method} ${userAgentClientId}.`); - } - } -} diff --git a/lib/core/user-agents/bye-user-agent-client.d.ts b/lib/core/user-agents/bye-user-agent-client.d.ts deleted file mode 100644 index c0f22aa95..000000000 --- a/lib/core/user-agents/bye-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingByeRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * BYE UAC. - * @public - */ -export declare class ByeUserAgentClient extends UserAgentClient implements OutgoingByeRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=bye-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-client.d.ts.map b/lib/core/user-agents/bye-user-agent-client.d.ts.map deleted file mode 100644 index 3cc958863..000000000 --- a/lib/core/user-agents/bye-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/bye-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,kBAAkB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,eAAgB,YAAW,kBAAkB;gBACvE,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAKhG"} \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-client.js b/lib/core/user-agents/bye-user-agent-client.js deleted file mode 100644 index 8309a8027..000000000 --- a/lib/core/user-agents/bye-user-agent-client.js +++ /dev/null @@ -1,14 +0,0 @@ -import { C } from "../messages"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * BYE UAC. - * @public - */ -export class ByeUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.BYE, options); - super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); - dialog.dispose(); - } -} diff --git a/lib/core/user-agents/bye-user-agent-server.d.ts b/lib/core/user-agents/bye-user-agent-server.d.ts deleted file mode 100644 index 85a98258e..000000000 --- a/lib/core/user-agents/bye-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingByeRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * BYE UAS. - * @public - */ -export declare class ByeUserAgentServer extends UserAgentServer implements IncomingByeRequest { - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=bye-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-server.d.ts.map b/lib/core/user-agents/bye-user-agent-server.d.ts.map deleted file mode 100644 index c89c04774..000000000 --- a/lib/core/user-agents/bye-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bye-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/bye-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAElG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,eAAgB,YAAW,kBAAkB;gBACvE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGvG"} \ No newline at end of file diff --git a/lib/core/user-agents/bye-user-agent-server.js b/lib/core/user-agents/bye-user-agent-server.js deleted file mode 100644 index b0812dde8..000000000 --- a/lib/core/user-agents/bye-user-agent-server.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * BYE UAS. - * @public - */ -export class ByeUserAgentServer extends UserAgentServer { - constructor(dialog, message, delegate) { - super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/cancel-user-agent-client.d.ts b/lib/core/user-agents/cancel-user-agent-client.d.ts deleted file mode 100644 index e83c423f2..000000000 --- a/lib/core/user-agents/cancel-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingCancelRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * CANCEL UAC. - * @public - */ -export declare class CancelUserAgentClient extends UserAgentClient implements OutgoingCancelRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=cancel-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/cancel-user-agent-client.d.ts.map b/lib/core/user-agents/cancel-user-agent-client.d.ts.map deleted file mode 100644 index 20eb91265..000000000 --- a/lib/core/user-agents/cancel-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cancel-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/cancel-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;gBAC7E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ No newline at end of file diff --git a/lib/core/user-agents/cancel-user-agent-client.js b/lib/core/user-agents/cancel-user-agent-client.js deleted file mode 100644 index 58676c41f..000000000 --- a/lib/core/user-agents/cancel-user-agent-client.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * CANCEL UAC. - * @public - */ -export class CancelUserAgentClient extends UserAgentClient { - constructor(core, message, delegate) { - super(NonInviteClientTransaction, core, message, delegate); - } -} diff --git a/lib/core/user-agents/index.d.ts b/lib/core/user-agents/index.d.ts deleted file mode 100644 index ac74c459b..000000000 --- a/lib/core/user-agents/index.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -export * from "./bye-user-agent-client"; -export * from "./bye-user-agent-server"; -export * from "./cancel-user-agent-client"; -export * from "./info-user-agent-client"; -export * from "./info-user-agent-server"; -export * from "./invite-user-agent-client"; -export * from "./invite-user-agent-server"; -export * from "./message-user-agent-client"; -export * from "./message-user-agent-server"; -export * from "./notify-user-agent-client"; -export * from "./notify-user-agent-server"; -export * from "./publish-user-agent-client"; -export * from "./prack-user-agent-client"; -export * from "./prack-user-agent-server"; -export * from "./re-invite-user-agent-client"; -export * from "./re-invite-user-agent-server"; -export * from "./re-subscribe-user-agent-client"; -export * from "./re-subscribe-user-agent-server"; -export * from "./refer-user-agent-client"; -export * from "./refer-user-agent-server"; -export * from "./register-user-agent-client"; -export * from "./register-user-agent-server"; -export * from "./subscribe-user-agent-client"; -export * from "./subscribe-user-agent-server"; -export * from "./user-agent-client"; -export * from "./user-agent-server"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/index.d.ts.map b/lib/core/user-agents/index.d.ts.map deleted file mode 100644 index 816b4d781..000000000 --- a/lib/core/user-agents/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,kCAAkC,CAAC;AACjD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC"} \ No newline at end of file diff --git a/lib/core/user-agents/index.js b/lib/core/user-agents/index.js deleted file mode 100644 index 3a036707d..000000000 --- a/lib/core/user-agents/index.js +++ /dev/null @@ -1,26 +0,0 @@ -export * from "./bye-user-agent-client"; -export * from "./bye-user-agent-server"; -export * from "./cancel-user-agent-client"; -export * from "./info-user-agent-client"; -export * from "./info-user-agent-server"; -export * from "./invite-user-agent-client"; -export * from "./invite-user-agent-server"; -export * from "./message-user-agent-client"; -export * from "./message-user-agent-server"; -export * from "./notify-user-agent-client"; -export * from "./notify-user-agent-server"; -export * from "./publish-user-agent-client"; -export * from "./prack-user-agent-client"; -export * from "./prack-user-agent-server"; -export * from "./re-invite-user-agent-client"; -export * from "./re-invite-user-agent-server"; -export * from "./re-subscribe-user-agent-client"; -export * from "./re-subscribe-user-agent-server"; -export * from "./refer-user-agent-client"; -export * from "./refer-user-agent-server"; -export * from "./register-user-agent-client"; -export * from "./register-user-agent-server"; -export * from "./subscribe-user-agent-client"; -export * from "./subscribe-user-agent-server"; -export * from "./user-agent-client"; -export * from "./user-agent-server"; diff --git a/lib/core/user-agents/info-user-agent-client.d.ts b/lib/core/user-agents/info-user-agent-client.d.ts deleted file mode 100644 index 48bcafb3d..000000000 --- a/lib/core/user-agents/info-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingInfoRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * INFO UAC. - * @public - */ -export declare class InfoUserAgentClient extends UserAgentClient implements OutgoingInfoRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=info-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-client.d.ts.map b/lib/core/user-agents/info-user-agent-client.d.ts.map deleted file mode 100644 index 3e4c0f7da..000000000 --- a/lib/core/user-agents/info-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/info-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,mBAAmB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE9F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,eAAgB,YAAW,mBAAmB;gBACzE,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAIhG"} \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-client.js b/lib/core/user-agents/info-user-agent-client.js deleted file mode 100644 index 92e343ad8..000000000 --- a/lib/core/user-agents/info-user-agent-client.js +++ /dev/null @@ -1,13 +0,0 @@ -import { C } from "../messages"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * INFO UAC. - * @public - */ -export class InfoUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.INFO, options); - super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/info-user-agent-server.d.ts b/lib/core/user-agents/info-user-agent-server.d.ts deleted file mode 100644 index 1a15097b1..000000000 --- a/lib/core/user-agents/info-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingInfoRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * INFO UAS. - * @public - */ -export declare class InfoUserAgentServer extends UserAgentServer implements IncomingInfoRequest { - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=info-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-server.d.ts.map b/lib/core/user-agents/info-user-agent-server.d.ts.map deleted file mode 100644 index 3b93ee1ec..000000000 --- a/lib/core/user-agents/info-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"info-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/info-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEnG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,eAAgB,YAAW,mBAAmB;gBACzE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGvG"} \ No newline at end of file diff --git a/lib/core/user-agents/info-user-agent-server.js b/lib/core/user-agents/info-user-agent-server.js deleted file mode 100644 index 006c0d0b3..000000000 --- a/lib/core/user-agents/info-user-agent-server.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * INFO UAS. - * @public - */ -export class InfoUserAgentServer extends UserAgentServer { - constructor(dialog, message, delegate) { - super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/invite-user-agent-client.d.ts b/lib/core/user-agents/invite-user-agent-client.d.ts deleted file mode 100644 index 5e7d85852..000000000 --- a/lib/core/user-agents/invite-user-agent-client.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { TransportError } from "../exceptions"; -import { IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -export declare class InviteUserAgentClient extends UserAgentClient implements OutgoingInviteRequest { - delegate: OutgoingInviteRequestDelegate | undefined; - private confirmedDialogAcks; - private confirmedDialogs; - private earlyDialogs; - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingInviteRequestDelegate); - dispose(): void; - /** - * Special case for transport error while sending ACK. - * @param error - Transport error - */ - protected onTransportError(error: TransportError): void; - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - protected receiveResponse(message: IncomingResponseMessage): void; -} -//# sourceMappingURL=invite-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-client.d.ts.map b/lib/core/user-agents/invite-user-agent-client.d.ts.map deleted file mode 100644 index aeaedf91f..000000000 --- a/lib/core/user-agents/invite-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/invite-user-agent-client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EACL,uBAAuB,EAEvB,qBAAqB,EACrB,6BAA6B,EAE7B,sBAAsB,EAEvB,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;IAClF,QAAQ,EAAE,6BAA6B,GAAG,SAAS,CAAC;IAE3D,OAAO,CAAC,mBAAmB,CAAyC;IACpE,OAAO,CAAC,gBAAgB,CAAoC;IAC5D,OAAO,CAAC,YAAY,CAAoC;gBAE5C,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,6BAA6B;IAKnG,OAAO,IAAI,IAAI;IAgBtB;;;OAGG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IASvD;;;;;OAKG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CA0UlE"} \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-client.js b/lib/core/user-agents/invite-user-agent-client.js deleted file mode 100644 index 174505092..000000000 --- a/lib/core/user-agents/invite-user-agent-client.js +++ /dev/null @@ -1,362 +0,0 @@ -import { Dialog, SessionDialog } from "../dialogs"; -import { SignalingState } from "../session"; -import { InviteClientTransaction, TransactionState } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * INVITE UAC. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.2 UAC Processing - * https://tools.ietf.org/html/rfc3261#section-13.2 - * @public - */ -export class InviteUserAgentClient extends UserAgentClient { - constructor(core, message, delegate) { - super(InviteClientTransaction, core, message, delegate); - this.confirmedDialogAcks = new Map(); - this.confirmedDialogs = new Map(); - this.earlyDialogs = new Map(); - this.delegate = delegate; - } - dispose() { - // The UAC core considers the INVITE transaction completed 64*T1 seconds - // after the reception of the first 2xx response. At this point all the - // early dialogs that have not transitioned to established dialogs are - // terminated. Once the INVITE transaction is considered completed by - // the UAC core, no more new 2xx responses are expected to arrive. - // - // If, after acknowledging any 2xx response to an INVITE, the UAC does - // not want to continue with that dialog, then the UAC MUST terminate - // the dialog by sending a BYE request as described in Section 15. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - super.dispose(); - } - /** - * Special case for transport error while sending ACK. - * @param error - Transport error - */ - onTransportError(error) { - if (this.transaction.state === TransactionState.Calling) { - return super.onTransportError(error); - } - // If not in 'calling' state, the transport error occurred while sending an ACK. - this.logger.error(error.message); - this.logger.error("User agent client request transport error while sending ACK."); - } - /** - * Once the INVITE has been passed to the INVITE client transaction, the - * UAC waits for responses for the INVITE. - * https://tools.ietf.org/html/rfc3261#section-13.2.2 - * @param incomingResponse - Incoming response to INVITE request. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - return; - case /^1[0-9]{2}$/.test(statusCode): - // Zero, one or multiple provisional responses may arrive before one or - // more final responses are received. Provisional responses for an - // INVITE request can create "early dialogs". If a provisional response - // has a tag in the To field, and if the dialog ID of the response does - // not match an existing dialog, one is constructed using the procedures - // defined in Section 12.1.2. - // - // The early dialog will only be needed if the UAC needs to send a - // request to its peer within the dialog before the initial INVITE - // transaction completes. Header fields present in a provisional - // response are applicable as long as the dialog is in the early state - // (for example, an Allow header field in a provisional response - // contains the methods that can be used in the dialog while this is in - // the early state). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.1 - { - // Dialogs are created through the generation of non-failure responses - // to requests with specific methods. Within this specification, only - // 2xx and 101-199 responses with a To tag, where the request was - // INVITE, will establish a dialog. A dialog established by a non-final - // response to a request is in the "early" state and it is called an - // early dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1 - // Provisional without to tag, no dialog to create. - if (!message.toTag) { - this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping."); - return; - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - // Provisional without Contact header field, malformed response. - const contact = message.parseHeader("contact"); - if (!contact) { - this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping."); - return; - } - // Compute dialog state. - const dialogState = Dialog.initialDialogStateForUserAgentClient(this.message, message); - // Have existing early dialog or create a new one. - let earlyDialog = this.earlyDialogs.get(dialogState.id); - if (!earlyDialog) { - const transaction = this.transaction; - if (!(transaction instanceof InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - earlyDialog = new SessionDialog(transaction, this.core, dialogState); - this.earlyDialogs.set(earlyDialog.id, earlyDialog); - } - // Guard against out of order reliable provisional responses. - // Note that this is where the rseq tracking is done. - if (!earlyDialog.reliableSequenceGuard(message)) { - this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping."); - return; - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (earlyDialog.signalingState === SignalingState.Initial || - earlyDialog.signalingState === SignalingState.HaveLocalOffer) { - earlyDialog.signalingStateTransition(message); - } - // Pass response to delegate. - const session = earlyDialog; - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message, - session, - prack: (options) => { - const outgoingPrackRequest = session.prack(undefined, options); - return outgoingPrackRequest; - } - }); - } - } - return; - case /^2[0-9]{2}$/.test(statusCode): - // Multiple 2xx responses may arrive at the UAC for a single INVITE - // request due to a forking proxy. Each response is distinguished by - // the tag parameter in the To header field, and each represents a - // distinct dialog, with a distinct dialog identifier. - // - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - { - // Dialogs are created through the generation of non-failure responses - // to requests with specific methods. Within this specification, only - // 2xx and 101-199 responses with a To tag, where the request was - // INVITE, will establish a dialog. A dialog established by a non-final - // response to a request is in the "early" state and it is called an - // early dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1 - // Final without to tag, malformed response. - if (!message.toTag) { - this.logger.error("2xx INVITE response received without a to tag, dropping."); - return; - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - // Final without Contact header field, malformed response. - const contact = message.parseHeader("contact"); - if (!contact) { - this.logger.error("2xx INVITE response received without a Contact header field, dropping."); - return; - } - // Compute dialog state. - const dialogState = Dialog.initialDialogStateForUserAgentClient(this.message, message); - // NOTE: Currently our transaction layer is caching the 2xx ACKs and - // handling retransmissions of the ACK which is an approach which is - // not to spec. In any event, this block is intended to provide a to - // spec implementation of ACK retransmissions, but it should not be - // hit currently. - let dialog = this.confirmedDialogs.get(dialogState.id); - if (dialog) { - // Once the ACK has been constructed, the procedures of [4] are used to - // determine the destination address, port and transport. However, the - // request is passed to the transport layer directly for transmission, - // rather than a client transaction. This is because the UAC core - // handles retransmissions of the ACK, not the transaction layer. The - // ACK MUST be passed to the client transport every time a - // retransmission of the 2xx final response that triggered the ACK - // arrives. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - const outgoingAckRequest = this.confirmedDialogAcks.get(dialogState.id); - if (outgoingAckRequest) { - const transaction = this.transaction; - if (!(transaction instanceof InviteClientTransaction)) { - throw new Error("Client transaction not instance of InviteClientTransaction."); - } - transaction.ackResponse(outgoingAckRequest.message); - } - else { - // If still waiting for an ACK, drop the retransmission of the 2xx final response. - } - return; - } - // If the dialog identifier in the 2xx response matches the dialog - // identifier of an existing dialog, the dialog MUST be transitioned to - // the "confirmed" state, and the route set for the dialog MUST be - // recomputed based on the 2xx response using the procedures of Section - // 12.2.1.2. Otherwise, a new dialog in the "confirmed" state MUST be - // constructed using the procedures of Section 12.1.2. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - dialog = this.earlyDialogs.get(dialogState.id); - if (dialog) { - dialog.confirm(); - dialog.recomputeRouteSet(message); - this.earlyDialogs.delete(dialog.id); - this.confirmedDialogs.set(dialog.id, dialog); - } - else { - const transaction = this.transaction; - if (!(transaction instanceof InviteClientTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - dialog = new SessionDialog(transaction, this.core, dialogState); - this.confirmedDialogs.set(dialog.id, dialog); - } - // If the initial offer is in an INVITE, the answer MUST be in a - // reliable non-failure message from UAS back to UAC which is - // correlated to that INVITE. For this specification, that is - // only the final 2xx response to that INVITE. That same exact - // answer MAY also be placed in any provisional responses sent - // prior to the answer. The UAC MUST treat the first session - // description it receives as the answer, and MUST ignore any - // session descriptions in subsequent responses to the initial - // INVITE. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (dialog.signalingState === SignalingState.Initial || - dialog.signalingState === SignalingState.HaveLocalOffer) { - dialog.signalingStateTransition(message); - } - // Session Initiated! :) - const session = dialog; - // The UAC core MUST generate an ACK request for each 2xx received from - // the transaction layer. The header fields of the ACK are constructed - // in the same way as for any request sent within a dialog (see Section - // 12) with the exception of the CSeq and the header fields related to - // authentication. The sequence number of the CSeq header field MUST be - // the same as the INVITE being acknowledged, but the CSeq method MUST - // be ACK. The ACK MUST contain the same credentials as the INVITE. If - // the 2xx contains an offer (based on the rules above), the ACK MUST - // carry an answer in its body. If the offer in the 2xx response is not - // acceptable, the UAC core MUST generate a valid answer in the ACK and - // then send a BYE immediately. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.4 - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message, - session, - ack: (options) => { - const outgoingAckRequest = session.ack(options); - this.confirmedDialogAcks.set(session.id, outgoingAckRequest); - return outgoingAckRequest; - } - }); - } - else { - const outgoingAckRequest = session.ack(); - this.confirmedDialogAcks.set(session.id, outgoingAckRequest); - } - } - return; - case /^3[0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - // A 3xx response may contain one or more Contact header field values - // providing new addresses where the callee might be reachable. - // Depending on the status code of the 3xx response (see Section 21.3), - // the UAC MAY choose to try those new addresses. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.2 - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - return; - case /^[4-6][0-9]{2}$/.test(statusCode): - // 12.3 Termination of a Dialog - // - // Independent of the method, if a request outside of a dialog generates - // a non-2xx final response, any early dialogs created through - // provisional responses to that request are terminated. The mechanism - // for terminating confirmed dialogs is method specific. In this - // specification, the BYE method terminates a session and the dialog - // associated with it. See Section 15 for details. - // https://tools.ietf.org/html/rfc3261#section-12.3 - // All early dialogs are considered terminated upon reception of the - // non-2xx final response. - // - // After having received the non-2xx final response the UAC core - // considers the INVITE transaction completed. The INVITE client - // transaction handles the generation of ACKs for the response (see - // Section 17). - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - this.earlyDialogs.forEach((earlyDialog) => earlyDialog.dispose()); - this.earlyDialogs.clear(); - // A single non-2xx final response may be received for the INVITE. 4xx, - // 5xx and 6xx responses may contain a Contact header field value - // indicating the location where additional information about the error - // can be found. Subsequent final responses (which would only arrive - // under error conditions) MUST be ignored. - // https://tools.ietf.org/html/rfc3261#section-13.2.2.3 - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - return; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - throw new Error(`Executing what should be an unreachable code path receiving ${statusCode} response.`); - } -} diff --git a/lib/core/user-agents/invite-user-agent-server.d.ts b/lib/core/user-agents/invite-user-agent-server.d.ts deleted file mode 100644 index 54968462a..000000000 --- a/lib/core/user-agents/invite-user-agent-server.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { IncomingInviteRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, OutgoingResponseWithSession, ResponseOptions, URI } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -export declare class InviteUserAgentServer extends UserAgentServer implements IncomingInviteRequest { - protected core: UserAgentCore; - /** The confirmed dialog, if any. */ - private confirmedDialog; - /** The early dialog, if any. */ - private earlyDialog; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); - dispose(): void; - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - progress(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - reject(options?: ResponseOptions): OutgoingResponse; -} -//# sourceMappingURL=invite-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-server.d.ts.map b/lib/core/user-agents/invite-user-agent-server.d.ts.map deleted file mode 100644 index 4f0e086ac..000000000 --- a/lib/core/user-agents/invite-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"invite-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/invite-user-agent-server.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;IAM7E,SAAS,CAAC,IAAI,EAAE,aAAa;IALzC,oCAAoC;IACpC,OAAO,CAAC,eAAe,CAA4B;IACnD,gCAAgC;IAChC,OAAO,CAAC,WAAW,CAA4B;gBAEzB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;IAIvG,OAAO,IAAI,IAAI;IAOtB;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAsG1F;;;;;;;;;;;;;;;;;;;;;OAqBG;IACI,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAgE5F;;;;;;;;;;;OAWG;IACI,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAIvG;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;CAGhF"} \ No newline at end of file diff --git a/lib/core/user-agents/invite-user-agent-server.js b/lib/core/user-agents/invite-user-agent-server.js deleted file mode 100644 index 9ca0b6df3..000000000 --- a/lib/core/user-agents/invite-user-agent-server.js +++ /dev/null @@ -1,232 +0,0 @@ -import { Dialog, SessionDialog } from "../dialogs"; -import { TransactionStateError } from "../exceptions"; -import { SignalingState } from "../session"; -import { InviteServerTransaction } from "../transactions"; -import { AllowedMethods } from "../user-agent-core/allowed-methods"; -import { UserAgentServer } from "./user-agent-server"; -/** - * INVITE UAS. - * @remarks - * 13 Initiating a Session - * https://tools.ietf.org/html/rfc3261#section-13 - * 13.1 Overview - * https://tools.ietf.org/html/rfc3261#section-13.1 - * 13.3 UAS Processing - * https://tools.ietf.org/html/rfc3261#section-13.3 - * @public - */ -export class InviteUserAgentServer extends UserAgentServer { - constructor(core, message, delegate) { - super(InviteServerTransaction, core, message, delegate); - this.core = core; - } - dispose() { - if (this.earlyDialog) { - this.earlyDialog.dispose(); - } - super.dispose(); - } - /** - * 13.3.1.4 The INVITE is Accepted - * The UAS core generates a 2xx response. This response establishes a - * dialog, and therefore follows the procedures of Section 12.1.1 in - * addition to those of Section 8.2.6. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - * @param options - Accept options bucket. - */ - accept(options = { statusCode: 200 }) { - if (!this.acceptable) { - throw new TransactionStateError(`${this.message.method} not acceptable in state ${this.transaction.state}.`); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.confirmedDialog) { - if (this.earlyDialog) { - this.earlyDialog.confirm(); - this.confirmedDialog = this.earlyDialog; - this.earlyDialog = undefined; - } - else { - const transaction = this.transaction; - if (!(transaction instanceof InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - const state = Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag); - this.confirmedDialog = new SessionDialog(transaction, this.core, state); - } - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); - const contactHeader = `Contact: ${this.core.configuration.contact.toString()}`; - // A 2xx response to an INVITE SHOULD contain the Allow header field and - // the Supported header field, and MAY contain the Accept header field. - // Including these header fields allows the UAC to determine the - // features and extensions supported by the UAS for the duration of the - // call, without probing. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - // FIXME: TODO: This should not be hard coded. - const allowHeader = "Allow: " + AllowedMethods.toString(); - // FIXME: TODO: Supported header (see reply()) - // FIXME: TODO: Accept header - // If the INVITE request contained an offer, and the UAS had not yet - // sent an answer, the 2xx MUST contain an answer. If the INVITE did - // not contain an offer, the 2xx MUST contain an offer if the UAS had - // not yet sent an offer. - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!options.body) { - if (this.confirmedDialog.signalingState === SignalingState.Stable) { - options.body = this.confirmedDialog.answer; // resend the answer sent in provisional response - } - else if (this.confirmedDialog.signalingState === SignalingState.Initial || - this.confirmedDialog.signalingState === SignalingState.HaveRemoteOffer) { - throw new Error("Response must have a body."); - } - } - options.statusCode = options.statusCode || 200; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(allowHeader); - options.extraHeaders.push(contactHeader); - const response = super.accept(options); - const session = this.confirmedDialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.confirmedDialog.signalingState !== SignalingState.Stable) { - this.confirmedDialog.signalingStateTransition(options.body); - } - } - return result; - } - /** - * 13.3.1.1 Progress - * If the UAS is not able to answer the invitation immediately, it can - * choose to indicate some kind of progress to the UAC (for example, an - * indication that a phone is ringing). This is accomplished with a - * provisional response between 101 and 199. These provisional - * responses establish early dialogs and therefore follow the procedures - * of Section 12.1.1 in addition to those of Section 8.2.6. A UAS MAY - * send as many provisional responses as it likes. Each of these MUST - * indicate the same dialog ID. However, these will not be delivered - * reliably. - * - * If the UAS desires an extended period of time to answer the INVITE, - * it will need to ask for an "extension" in order to prevent proxies - * from canceling the transaction. A proxy has the option of canceling - * a transaction when there is a gap of 3 minutes between responses in a - * transaction. To prevent cancellation, the UAS MUST send a non-100 - * provisional response at every minute, to handle the possibility of - * lost provisional responses. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.1 - * @param options - Progress options bucket. - */ - progress(options = { statusCode: 180 }) { - if (!this.progressable) { - throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`); - } - // This response establishes a dialog... - // https://tools.ietf.org/html/rfc3261#section-13.3.1.4 - if (!this.earlyDialog) { - const transaction = this.transaction; - if (!(transaction instanceof InviteServerTransaction)) { - throw new Error("Transaction not instance of InviteClientTransaction."); - } - const state = Dialog.initialDialogStateForUserAgentServer(this.message, this.toTag, true); - this.earlyDialog = new SessionDialog(transaction, this.core, state); - } - // When a UAS responds to a request with a response that establishes a - // dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route - // header field values from the request into the response (including the - // URIs, URI parameters, and any Record-Route header field parameters, - // whether they are known or unknown to the UAS) and MUST maintain the - // order of those values. The UAS MUST add a Contact header field to - // the response. The Contact header field contains an address where the - // UAS would like to be contacted for subsequent requests in the dialog - // (which includes the ACK for a 2xx response in the case of an INVITE). - // Generally, the host portion of this URI is the IP address or FQDN of - // the host. The URI provided in the Contact header field MUST be a SIP - // or SIPS URI. If the request that initiated the dialog contained a - // SIPS URI in the Request-URI or in the top Record-Route header field - // value, if there was any, or the Contact header field if there was no - // Record-Route header field, the Contact header field in the response - // MUST be a SIPS URI. The URI SHOULD have global scope (that is, the - // same URI can be used in messages outside this dialog). The same way, - // the scope of the URI in the Contact header field of the INVITE is not - // limited to this dialog either. It can therefore be used in messages - // to the UAC even outside this dialog. - // https://tools.ietf.org/html/rfc3261#section-12.1.1 - const recordRouteHeader = this.message.getHeaders("record-route").map((header) => `Record-Route: ${header}`); - const contactHeader = `Contact: ${this.core.configuration.contact}`; - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(recordRouteHeader); - options.extraHeaders.push(contactHeader); - const response = super.progress(options); - const session = this.earlyDialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - // Once the UAS has sent or received an answer to the initial - // offer, it MUST NOT generate subsequent offers in any responses - // to the initial INVITE. This means that a UAS based on this - // specification alone can never generate subsequent offers until - // completion of the initial transaction. - // https://tools.ietf.org/html/rfc3261#section-13.2.1 - if (this.earlyDialog.signalingState !== SignalingState.Stable) { - this.earlyDialog.signalingStateTransition(options.body); - } - } - return result; - } - /** - * 13.3.1.2 The INVITE is Redirected - * If the UAS decides to redirect the call, a 3xx response is sent. A - * 300 (Multiple Choices), 301 (Moved Permanently) or 302 (Moved - * Temporarily) response SHOULD contain a Contact header field - * containing one or more URIs of new addresses to be tried. The - * response is passed to the INVITE server transaction, which will deal - * with its retransmissions. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.2 - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts, options = { statusCode: 302 }) { - return super.redirect(contacts, options); - } - /** - * 13.3.1.3 The INVITE is Rejected - * A common scenario occurs when the callee is currently not willing or - * able to take additional calls at this end system. A 486 (Busy Here) - * SHOULD be returned in such a scenario. - * https://tools.ietf.org/html/rfc3261#section-13.3.1.3 - * @param options - Reject options bucket. - */ - reject(options = { statusCode: 486 }) { - return super.reject(options); - } -} diff --git a/lib/core/user-agents/message-user-agent-client.d.ts b/lib/core/user-agents/message-user-agent-client.d.ts deleted file mode 100644 index e8ca14058..000000000 --- a/lib/core/user-agents/message-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingMessageRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * MESSAGE UAC. - * @public - */ -export declare class MessageUserAgentClient extends UserAgentClient implements OutgoingMessageRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=message-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-client.d.ts.map b/lib/core/user-agents/message-user-agent-client.d.ts.map deleted file mode 100644 index 0e10c72cd..000000000 --- a/lib/core/user-agents/message-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/message-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAgB,YAAW,sBAAsB;gBAC/E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-client.js b/lib/core/user-agents/message-user-agent-client.js deleted file mode 100644 index 1606220fd..000000000 --- a/lib/core/user-agents/message-user-agent-client.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * MESSAGE UAC. - * @public - */ -export class MessageUserAgentClient extends UserAgentClient { - constructor(core, message, delegate) { - super(NonInviteClientTransaction, core, message, delegate); - } -} diff --git a/lib/core/user-agents/message-user-agent-server.d.ts b/lib/core/user-agents/message-user-agent-server.d.ts deleted file mode 100644 index 21f3c6a02..000000000 --- a/lib/core/user-agents/message-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IncomingMessageRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * MESSAGE UAS. - * @public - */ -export declare class MessageUserAgentServer extends UserAgentServer implements IncomingMessageRequest { - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=message-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-server.d.ts.map b/lib/core/user-agents/message-user-agent-server.d.ts.map deleted file mode 100644 index 25c19c262..000000000 --- a/lib/core/user-agents/message-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"message-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/message-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAgB,YAAW,sBAAsB;gBAC/E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ No newline at end of file diff --git a/lib/core/user-agents/message-user-agent-server.js b/lib/core/user-agents/message-user-agent-server.js deleted file mode 100644 index 7c94c20b4..000000000 --- a/lib/core/user-agents/message-user-agent-server.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * MESSAGE UAS. - * @public - */ -export class MessageUserAgentServer extends UserAgentServer { - constructor(core, message, delegate) { - super(NonInviteServerTransaction, core, message, delegate); - } -} diff --git a/lib/core/user-agents/notify-user-agent-client.d.ts b/lib/core/user-agents/notify-user-agent-client.d.ts deleted file mode 100644 index 2bbd23eac..000000000 --- a/lib/core/user-agents/notify-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingNotifyRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * NOTIFY UAS. - * @public - */ -export declare class NotifyUserAgentClient extends UserAgentClient implements OutgoingNotifyRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=notify-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-client.d.ts.map b/lib/core/user-agents/notify-user-agent-client.d.ts.map deleted file mode 100644 index ada9a9754..000000000 --- a/lib/core/user-agents/notify-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notify-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/notify-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,qBAAqB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAEhG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;gBAC7E,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAIhG"} \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-client.js b/lib/core/user-agents/notify-user-agent-client.js deleted file mode 100644 index e29ff2ebf..000000000 --- a/lib/core/user-agents/notify-user-agent-client.js +++ /dev/null @@ -1,13 +0,0 @@ -import { C } from "../messages"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * NOTIFY UAS. - * @public - */ -export class NotifyUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.NOTIFY, options); - super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/notify-user-agent-server.d.ts b/lib/core/user-agents/notify-user-agent-server.d.ts deleted file mode 100644 index 9a22df7ca..000000000 --- a/lib/core/user-agents/notify-user-agent-server.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Dialog } from "../dialogs"; -import { IncomingNotifyRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * NOTIFY UAS. - * @public - */ -export declare class NotifyUserAgentServer extends UserAgentServer implements IncomingNotifyRequest { - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - constructor(dialogOrCore: Dialog | UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=notify-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-server.d.ts.map b/lib/core/user-agents/notify-user-agent-server.d.ts.map deleted file mode 100644 index 8bceaf25c..000000000 --- a/lib/core/user-agents/notify-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"notify-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/notify-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAOtD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,eAAgB,YAAW,qBAAqB;IACzF;;;;OAIG;gBAED,YAAY,EAAE,MAAM,GAAG,aAAa,EACpC,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAKrC"} \ No newline at end of file diff --git a/lib/core/user-agents/notify-user-agent-server.js b/lib/core/user-agents/notify-user-agent-server.js deleted file mode 100644 index b025c77c5..000000000 --- a/lib/core/user-agents/notify-user-agent-server.js +++ /dev/null @@ -1,21 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instanceOfDialog(object) { - return object.userAgentCore !== undefined; -} -/** - * NOTIFY UAS. - * @public - */ -export class NotifyUserAgentServer extends UserAgentServer { - /** - * NOTIFY UAS constructor. - * @param dialogOrCore - Dialog for in dialog NOTIFY, UserAgentCore for out of dialog NOTIFY (deprecated). - * @param message - Incoming NOTIFY request message. - */ - constructor(dialogOrCore, message, delegate) { - const userAgentCore = instanceOfDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; - super(NonInviteServerTransaction, userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/prack-user-agent-client.d.ts b/lib/core/user-agents/prack-user-agent-client.d.ts deleted file mode 100644 index b7dea252a..000000000 --- a/lib/core/user-agents/prack-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingPrackRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * PRACK UAC. - * @public - */ -export declare class PrackUserAgentClient extends UserAgentClient implements OutgoingPrackRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=prack-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-client.d.ts.map b/lib/core/user-agents/prack-user-agent-client.d.ts.map deleted file mode 100644 index 54c8effac..000000000 --- a/lib/core/user-agents/prack-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"prack-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/prack-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,oBAAoB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;gBAC3E,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAKhG"} \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-client.js b/lib/core/user-agents/prack-user-agent-client.js deleted file mode 100644 index e5477d456..000000000 --- a/lib/core/user-agents/prack-user-agent-client.js +++ /dev/null @@ -1,14 +0,0 @@ -import { C } from "../messages"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * PRACK UAC. - * @public - */ -export class PrackUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.PRACK, options); - super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); - dialog.signalingStateTransition(message); - } -} diff --git a/lib/core/user-agents/prack-user-agent-server.d.ts b/lib/core/user-agents/prack-user-agent-server.d.ts deleted file mode 100644 index ecc1fc075..000000000 --- a/lib/core/user-agents/prack-user-agent-server.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingPrackRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, ResponseOptions } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * PRACK UAS. - * @public - */ -export declare class PrackUserAgentServer extends UserAgentServer implements IncomingPrackRequest { - private dialog; - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponse; -} -//# sourceMappingURL=prack-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-server.d.ts.map b/lib/core/user-agents/prack-user-agent-server.d.ts.map deleted file mode 100644 index e222d765c..000000000 --- a/lib/core/user-agents/prack-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"prack-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/prack-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,eAAe,EAChB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;IACvF,OAAO,CAAC,MAAM,CAAgB;gBAElB,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;IAOtG;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;CAOhF"} \ No newline at end of file diff --git a/lib/core/user-agents/prack-user-agent-server.js b/lib/core/user-agents/prack-user-agent-server.js deleted file mode 100644 index 8fdf74919..000000000 --- a/lib/core/user-agents/prack-user-agent-server.js +++ /dev/null @@ -1,25 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * PRACK UAS. - * @public - */ -export class PrackUserAgentServer extends UserAgentServer { - constructor(dialog, message, delegate) { - super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); - // Update dialog signaling state with offer/answer in body - dialog.signalingStateTransition(message); - this.dialog = dialog; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options = { statusCode: 200 }) { - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - return super.accept(options); - } -} diff --git a/lib/core/user-agents/publish-user-agent-client.d.ts b/lib/core/user-agents/publish-user-agent-client.d.ts deleted file mode 100644 index d63bc4e8d..000000000 --- a/lib/core/user-agents/publish-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingPublishRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * PUBLISH UAC. - * @public - */ -export declare class PublishUserAgentClient extends UserAgentClient implements OutgoingPublishRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=publish-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/publish-user-agent-client.d.ts.map b/lib/core/user-agents/publish-user-agent-client.d.ts.map deleted file mode 100644 index 09255237d..000000000 --- a/lib/core/user-agents/publish-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"publish-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/publish-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAgB,YAAW,sBAAsB;gBAC/E,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ No newline at end of file diff --git a/lib/core/user-agents/publish-user-agent-client.js b/lib/core/user-agents/publish-user-agent-client.js deleted file mode 100644 index 13b21521a..000000000 --- a/lib/core/user-agents/publish-user-agent-client.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * PUBLISH UAC. - * @public - */ -export class PublishUserAgentClient extends UserAgentClient { - constructor(core, message, delegate) { - super(NonInviteClientTransaction, core, message, delegate); - } -} diff --git a/lib/core/user-agents/re-invite-user-agent-client.d.ts b/lib/core/user-agents/re-invite-user-agent-client.d.ts deleted file mode 100644 index bdb157024..000000000 --- a/lib/core/user-agents/re-invite-user-agent-client.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingResponseMessage, OutgoingInviteRequest, OutgoingInviteRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -export declare class ReInviteUserAgentClient extends UserAgentClient implements OutgoingInviteRequest { - delegate: OutgoingInviteRequestDelegate | undefined; - private dialog; - constructor(dialog: SessionDialog, delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions); - protected receiveResponse(message: IncomingResponseMessage): void; -} -//# sourceMappingURL=re-invite-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-client.d.ts.map b/lib/core/user-agents/re-invite-user-agent-client.d.ts.map deleted file mode 100644 index 29f9cee61..000000000 --- a/lib/core/user-agents/re-invite-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-invite-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-invite-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAEL,uBAAuB,EAEvB,qBAAqB,EACrB,6BAA6B,EAE7B,cAAc,EACf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,qBAAqB;IACpF,QAAQ,EAAE,6BAA6B,GAAG,SAAS,CAAC;IAE3D,OAAO,CAAC,MAAM,CAAgB;gBAElB,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc;IAUrG,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CAyFlE"} \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-client.js b/lib/core/user-agents/re-invite-user-agent-client.js deleted file mode 100644 index 23399896e..000000000 --- a/lib/core/user-agents/re-invite-user-agent-client.js +++ /dev/null @@ -1,108 +0,0 @@ -import { C } from "../messages"; -import { InviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * Re-INVITE UAC. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.1 UAC Behavior - * https://tools.ietf.org/html/rfc3261#section-14.1 - * @public - */ -export class ReInviteUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.INVITE, options); - super(InviteClientTransaction, dialog.userAgentCore, message, delegate); - this.delegate = delegate; - dialog.signalingStateTransition(message); - // FIXME: TODO: next line obviously needs to be improved... - dialog.reinviteUserAgentClient = this; // let the dialog know re-invite request sent - this.dialog = dialog; - } - receiveResponse(message) { - if (!this.authenticationGuard(message, this.dialog)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ - message, - session: this.dialog, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - prack: (options) => { - throw new Error("Unimplemented."); - } - }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(message); - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ - message, - session: this.dialog, - ack: (options) => { - const outgoingAckRequest = this.dialog.ack(options); - return outgoingAckRequest; - } - }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentClient = undefined; // ACK was handled by transaction - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - else { - // If a UA receives a non-2xx final response to a re-INVITE, the session - // parameters MUST remain unchanged, as if no re-INVITE had been issued. - // Note that, as stated in Section 12.2.1.2, if the non-2xx final - // response is a 481 (Call/Transaction Does Not Exist), or a 408 - // (Request Timeout), or no response at all is received for the re- - // INVITE (that is, a timeout is returned by the INVITE client - // transaction), the UAC will terminate the dialog. - // - // If a UAC receives a 491 response to a re-INVITE, it SHOULD start a - // timer with a value T chosen as follows: - // - // 1. If the UAC is the owner of the Call-ID of the dialog ID - // (meaning it generated the value), T has a randomly chosen value - // between 2.1 and 4 seconds in units of 10 ms. - // - // 2. If the UAC is not the owner of the Call-ID of the dialog ID, T - // has a randomly chosen value of between 0 and 2 seconds in units - // of 10 ms. - // - // When the timer fires, the UAC SHOULD attempt the re-INVITE once more, - // if it still desires for that session modification to take place. For - // example, if the call was already hung up with a BYE, the re-INVITE - // would not take place. - // https://tools.ietf.org/html/rfc3261#section-14.1 - // FIXME: TODO: The above. - } - break; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - } -} diff --git a/lib/core/user-agents/re-invite-user-agent-server.d.ts b/lib/core/user-agents/re-invite-user-agent-server.d.ts deleted file mode 100644 index 8083bb671..000000000 --- a/lib/core/user-agents/re-invite-user-agent-server.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingInviteRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, OutgoingResponseWithSession, ResponseOptions, URI } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -export declare class ReInviteUserAgentServer extends UserAgentServer implements IncomingInviteRequest { - private dialog; - constructor(dialog: SessionDialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - progress(options?: ResponseOptions): OutgoingResponseWithSession; - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - reject(options?: ResponseOptions): OutgoingResponse; -} -//# sourceMappingURL=re-invite-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-server.d.ts.map b/lib/core/user-agents/re-invite-user-agent-server.d.ts.map deleted file mode 100644 index 08deb75fb..000000000 --- a/lib/core/user-agents/re-invite-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-invite-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-invite-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,qBAAqB;IAC3F,OAAO,CAAC,MAAM,CAAgB;gBAElB,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;IAMtG;;;OAGG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IA8B1F;;;OAGG;IACI,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,2BAA2B;IAc5F;;;;OAIG;IAEI,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAMvG;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;CAKhF"} \ No newline at end of file diff --git a/lib/core/user-agents/re-invite-user-agent-server.js b/lib/core/user-agents/re-invite-user-agent-server.js deleted file mode 100644 index afac1c31a..000000000 --- a/lib/core/user-agents/re-invite-user-agent-server.js +++ /dev/null @@ -1,86 +0,0 @@ -import { InviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * Re-INVITE UAS. - * @remarks - * 14 Modifying an Existing Session - * https://tools.ietf.org/html/rfc3261#section-14 - * 14.2 UAS Behavior - * https://tools.ietf.org/html/rfc3261#section-14.2 - * @public - */ -export class ReInviteUserAgentServer extends UserAgentServer { - constructor(dialog, message, delegate) { - super(InviteServerTransaction, dialog.userAgentCore, message, delegate); - dialog.reinviteUserAgentServer = this; - this.dialog = dialog; - } - /** - * Update the dialog signaling state on a 2xx response. - * @param options - Options bucket. - */ - accept(options = { statusCode: 200 }) { - // FIXME: The next two lines SHOULD go away, but I suppose it's technically harmless... - // These are here because some versions of SIP.js prior to 0.13.8 set the route set - // of all in dialog ACKs based on the Record-Route headers in the associated 2xx - // response. While this worked for dialog forming 2xx responses, it was technically - // broken for re-INVITE ACKS as it only worked if the UAS populated the Record-Route - // headers in the re-INVITE 2xx response (which is not required and a waste of bandwidth - // as the should be ignored if present in re-INVITE ACKS) and the UAS populated - // the Record-Route headers with the correct values (would be weird not too, but...). - // Anyway, for now the technically useless Record-Route headers are being added - // to maintain "backwards compatibility" with the older broken versions of SIP.js. - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders = options.extraHeaders.concat(this.dialog.routeSet.map((route) => `Record-Route: ${route}`)); - // Send and return the response - const response = super.accept(options); - const session = this.dialog; - const result = Object.assign(Object.assign({}, response), { session }); - if (options.body) { - // Update dialog signaling state with offer/answer in body - this.dialog.signalingStateTransition(options.body); - } - // Update dialog - this.dialog.reConfirm(); - return result; - } - /** - * Update the dialog signaling state on a 1xx response. - * @param options - Progress options bucket. - */ - progress(options = { statusCode: 180 }) { - // Send and return the response - const response = super.progress(options); - const session = this.dialog; - const result = Object.assign(Object.assign({}, response), { session }); - // Update dialog signaling state - if (options.body) { - this.dialog.signalingStateTransition(options.body); - } - return result; - } - /** - * TODO: Not Yet Supported - * @param contacts - Contacts to redirect to. - * @param options - Redirect options bucket. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - redirect(contacts, options = { statusCode: 302 }) { - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - throw new Error("Unimplemented."); - } - /** - * 3.1 Background on Re-INVITE Handling by UASs - * An error response to a re-INVITE has the following semantics. As - * specified in Section 12.2.2 of RFC 3261 [RFC3261], if a re-INVITE is - * rejected, no state changes are performed. - * https://tools.ietf.org/html/rfc6141#section-3.1 - * @param options - Reject options bucket. - */ - reject(options = { statusCode: 488 }) { - this.dialog.signalingStateRollback(); - this.dialog.reinviteUserAgentServer = undefined; // ACK will be handled by transaction - return super.reject(options); - } -} diff --git a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts b/lib/core/user-agents/re-subscribe-user-agent-client.d.ts deleted file mode 100644 index 75183c74c..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SubscriptionDialog } from "../dialogs"; -import { IncomingResponseMessage, OutgoingRequestDelegate, OutgoingSubscribeRequest, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * Re-SUBSCRIBE UAC. - * @public - */ -export declare class ReSubscribeUserAgentClient extends UserAgentClient implements OutgoingSubscribeRequest { - private dialog; - constructor(dialog: SubscriptionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); - waitNotifyStop(): void; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - protected receiveResponse(message: IncomingResponseMessage): void; -} -//# sourceMappingURL=re-subscribe-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map b/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map deleted file mode 100644 index 9a65ba290..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-subscribe-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-subscribe-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAEL,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,cAAc,EACf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,eAAgB,YAAW,wBAAwB;IACjG,OAAO,CAAC,MAAM,CAAqB;gBAEvB,MAAM,EAAE,kBAAkB,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;IAM7F,cAAc,IAAI,IAAI;IAK7B;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;CA4ClE"} \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-client.js b/lib/core/user-agents/re-subscribe-user-agent-client.js deleted file mode 100644 index 15807215c..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-client.js +++ /dev/null @@ -1,65 +0,0 @@ -import { C } from "../messages"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * Re-SUBSCRIBE UAC. - * @public - */ -export class ReSubscribeUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.SUBSCRIBE, options); - super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); - this.dialog = dialog; - } - waitNotifyStop() { - // TODO: Placeholder. Not utilized currently. - return; - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - const expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - const subscriptionExpiresReceived = Number(expires); - if (this.dialog.subscriptionExpires > subscriptionExpiresReceived) { - this.dialog.subscriptionExpires = subscriptionExpiresReceived; - } - } - } - if (message.statusCode && message.statusCode >= 400 && message.statusCode < 700) { - // If a SUBSCRIBE request to refresh a subscription receives a 404, 405, - // 410, 416, 480-485, 489, 501, or 604 response, the subscriber MUST - // consider the subscription terminated. (See [RFC5057] for further - // details and notes about the effect of error codes on dialogs and - // usages within dialog, such as subscriptions). If the subscriber - // wishes to re-subscribe to the state, he does so by composing an - // unrelated initial SUBSCRIBE request with a freshly generated Call-ID - // and a new, unique "From" tag (see Section 4.1.2.1). - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - const errorCodes = [404, 405, 410, 416, 480, 481, 482, 483, 484, 485, 489, 501, 604]; - if (errorCodes.includes(message.statusCode)) { - this.dialog.terminate(); - } - // If a SUBSCRIBE request to refresh a subscription fails with any error - // code other than those listed above, the original subscription is - // still considered valid for the duration of the most recently known - // "Expires" value as negotiated by the most recent successful SUBSCRIBE - // transaction, or as communicated by a NOTIFY request in its - // "Subscription-State" header field "expires" parameter. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.2 - } - super.receiveResponse(message); - } -} diff --git a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts b/lib/core/user-agents/re-subscribe-user-agent-server.d.ts deleted file mode 100644 index 0a11912a4..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Dialog } from "../dialogs"; -import { IncomingRequestDelegate, IncomingRequestMessage, IncomingSubscribeRequest } from "../messages"; -import { UserAgentServer } from "./user-agent-server"; -/** - * Re-SUBSCRIBE UAS. - * @public - */ -export declare class ReSubscribeUserAgentServer extends UserAgentServer implements IncomingSubscribeRequest { - constructor(dialog: Dialog, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=re-subscribe-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map b/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map deleted file mode 100644 index 7400f6a4d..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"re-subscribe-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/re-subscribe-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAExG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,eAAgB,YAAW,wBAAwB;gBACrF,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGhG"} \ No newline at end of file diff --git a/lib/core/user-agents/re-subscribe-user-agent-server.js b/lib/core/user-agents/re-subscribe-user-agent-server.js deleted file mode 100644 index e97ae98e1..000000000 --- a/lib/core/user-agents/re-subscribe-user-agent-server.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * Re-SUBSCRIBE UAS. - * @public - */ -export class ReSubscribeUserAgentServer extends UserAgentServer { - constructor(dialog, message, delegate) { - super(NonInviteServerTransaction, dialog.userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/refer-user-agent-client.d.ts b/lib/core/user-agents/refer-user-agent-client.d.ts deleted file mode 100644 index 92e14d6f7..000000000 --- a/lib/core/user-agents/refer-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { OutgoingReferRequest, OutgoingRequestDelegate, RequestOptions } from "../messages"; -import { UserAgentClient } from "./user-agent-client"; -/** - * REFER UAC. - * @public - */ -export declare class ReferUserAgentClient extends UserAgentClient implements OutgoingReferRequest { - constructor(dialog: SessionDialog, delegate?: OutgoingRequestDelegate, options?: RequestOptions); -} -//# sourceMappingURL=refer-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-client.d.ts.map b/lib/core/user-agents/refer-user-agent-client.d.ts.map deleted file mode 100644 index 20d33b578..000000000 --- a/lib/core/user-agents/refer-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"refer-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/refer-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAK,oBAAoB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;gBAC3E,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc;CAIhG"} \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-client.js b/lib/core/user-agents/refer-user-agent-client.js deleted file mode 100644 index abefcbbf6..000000000 --- a/lib/core/user-agents/refer-user-agent-client.js +++ /dev/null @@ -1,13 +0,0 @@ -import { C } from "../messages"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * REFER UAC. - * @public - */ -export class ReferUserAgentClient extends UserAgentClient { - constructor(dialog, delegate, options) { - const message = dialog.createOutgoingRequestMessage(C.REFER, options); - super(NonInviteClientTransaction, dialog.userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/refer-user-agent-server.d.ts b/lib/core/user-agents/refer-user-agent-server.d.ts deleted file mode 100644 index 8203a6445..000000000 --- a/lib/core/user-agents/refer-user-agent-server.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SessionDialog } from "../dialogs"; -import { IncomingReferRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * REFER UAS. - * @public - */ -export declare class ReferUserAgentServer extends UserAgentServer implements IncomingReferRequest { - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - constructor(dialogOrCore: SessionDialog | UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=refer-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-server.d.ts.map b/lib/core/user-agents/refer-user-agent-server.d.ts.map deleted file mode 100644 index 735fcd7f5..000000000 --- a/lib/core/user-agents/refer-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"refer-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/refer-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEpG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAOtD;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,eAAgB,YAAW,oBAAoB;IACvF;;;;OAIG;gBAED,YAAY,EAAE,aAAa,GAAG,aAAa,EAC3C,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,EAAE,uBAAuB;CAKrC"} \ No newline at end of file diff --git a/lib/core/user-agents/refer-user-agent-server.js b/lib/core/user-agents/refer-user-agent-server.js deleted file mode 100644 index 34492b359..000000000 --- a/lib/core/user-agents/refer-user-agent-server.js +++ /dev/null @@ -1,21 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instanceOfSessionDialog(object) { - return object.userAgentCore !== undefined; -} -/** - * REFER UAS. - * @public - */ -export class ReferUserAgentServer extends UserAgentServer { - /** - * REFER UAS constructor. - * @param dialogOrCore - Dialog for in dialog REFER, UserAgentCore for out of dialog REFER. - * @param message - Incoming REFER request message. - */ - constructor(dialogOrCore, message, delegate) { - const userAgentCore = instanceOfSessionDialog(dialogOrCore) ? dialogOrCore.userAgentCore : dialogOrCore; - super(NonInviteServerTransaction, userAgentCore, message, delegate); - } -} diff --git a/lib/core/user-agents/register-user-agent-client.d.ts b/lib/core/user-agents/register-user-agent-client.d.ts deleted file mode 100644 index 71e4150be..000000000 --- a/lib/core/user-agents/register-user-agent-client.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { OutgoingRegisterRequest, OutgoingRequestDelegate, OutgoingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentClient } from "./user-agent-client"; -/** - * REGISTER UAC. - * @public - */ -export declare class RegisterUserAgentClient extends UserAgentClient implements OutgoingRegisterRequest { - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate); -} -//# sourceMappingURL=register-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-client.d.ts.map b/lib/core/user-agents/register-user-agent-client.d.ts.map deleted file mode 100644 index 82113b017..000000000 --- a/lib/core/user-agents/register-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/register-user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,uBAAuB;gBACjF,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAGrG"} \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-client.js b/lib/core/user-agents/register-user-agent-client.js deleted file mode 100644 index be483bf61..000000000 --- a/lib/core/user-agents/register-user-agent-client.js +++ /dev/null @@ -1,11 +0,0 @@ -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * REGISTER UAC. - * @public - */ -export class RegisterUserAgentClient extends UserAgentClient { - constructor(core, message, delegate) { - super(NonInviteClientTransaction, core, message, delegate); - } -} diff --git a/lib/core/user-agents/register-user-agent-server.d.ts b/lib/core/user-agents/register-user-agent-server.d.ts deleted file mode 100644 index b9f6ce296..000000000 --- a/lib/core/user-agents/register-user-agent-server.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IncomingRegisterRequest, IncomingRequestDelegate, IncomingRequestMessage } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * REGISTER UAS. - * @public - */ -export declare class RegisterUserAgentServer extends UserAgentServer implements IncomingRegisterRequest { - protected core: UserAgentCore; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=register-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-server.d.ts.map b/lib/core/user-agents/register-user-agent-server.d.ts.map deleted file mode 100644 index 6b7cc9df7..000000000 --- a/lib/core/user-agents/register-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/register-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,eAAgB,YAAW,uBAAuB;IACjF,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAG/G"} \ No newline at end of file diff --git a/lib/core/user-agents/register-user-agent-server.js b/lib/core/user-agents/register-user-agent-server.js deleted file mode 100644 index c6ce3507c..000000000 --- a/lib/core/user-agents/register-user-agent-server.js +++ /dev/null @@ -1,12 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * REGISTER UAS. - * @public - */ -export class RegisterUserAgentServer extends UserAgentServer { - constructor(core, message, delegate) { - super(NonInviteServerTransaction, core, message, delegate); - this.core = core; - } -} diff --git a/lib/core/user-agents/subscribe-user-agent-client.d.ts b/lib/core/user-agents/subscribe-user-agent-client.d.ts deleted file mode 100644 index 12ba96540..000000000 --- a/lib/core/user-agents/subscribe-user-agent-client.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { IncomingResponseMessage, OutgoingRequestMessage, OutgoingSubscribeRequest, OutgoingSubscribeRequestDelegate } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { NotifyUserAgentServer } from "./notify-user-agent-server"; -import { UserAgentClient } from "./user-agent-client"; -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE requests. - * @public - */ -export declare class SubscribeUserAgentClient extends UserAgentClient implements OutgoingSubscribeRequest { - delegate: OutgoingSubscribeRequestDelegate | undefined; - /** Dialog created upon receiving the first NOTIFY. */ - private dialog; - /** Identifier of this user agent client. */ - private subscriberId; - /** When the subscription expires. Starts as requested expires and updated on 200 and NOTIFY. */ - private subscriptionExpires; - /** The requested expires for the subscription. */ - private subscriptionExpiresRequested; - /** Subscription event being targeted. */ - private subscriptionEvent; - /** Subscription state. */ - private subscriptionState; - /** Timer N Id. */ - private N; - constructor(core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingSubscribeRequestDelegate); - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - dispose(): void; - /** - * Handle out of dialog NOTIFY associated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - onNotify(uas: NotifyUserAgentServer): void; - waitNotifyStart(): void; - waitNotifyStop(): void; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - protected receiveResponse(message: IncomingResponseMessage): void; - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - private timerN; -} -//# sourceMappingURL=subscribe-user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-client.d.ts.map b/lib/core/user-agents/subscribe-user-agent-client.d.ts.map deleted file mode 100644 index 93dc42d26..000000000 --- a/lib/core/user-agents/subscribe-user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscribe-user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/subscribe-user-agent-client.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,wBAAwB,EACxB,gCAAgC,EACjC,MAAM,aAAa,CAAC;AAIrB,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;;GASG;AACH,qBAAa,wBAAyB,SAAQ,eAAgB,YAAW,wBAAwB;IACxF,QAAQ,EAAE,gCAAgC,GAAG,SAAS,CAAC;IAE9D,sDAAsD;IACtD,OAAO,CAAC,MAAM,CAAiC;IAC/C,4CAA4C;IAC5C,OAAO,CAAC,YAAY,CAAS;IAC7B,gGAAgG;IAChG,OAAO,CAAC,mBAAmB,CAAS;IACpC,kDAAkD;IAClD,OAAO,CAAC,4BAA4B,CAAS;IAC7C,yCAAyC;IACzC,OAAO,CAAC,iBAAiB,CAAS;IAClC,0BAA0B;IAC1B,OAAO,CAAC,iBAAiB,CAAoB;IAC7C,kBAAkB;IAClB,OAAO,CAAC,CAAC,CAAqB;gBAElB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,gCAAgC;IAwB7G;;;;;;;;OAQG;IACI,OAAO,IAAI,IAAI;IAItB;;;;OAIG;IACI,QAAQ,CAAC,GAAG,EAAE,qBAAqB,GAAG,IAAI;IAgK1C,eAAe,IAAI,IAAI;IASvB,cAAc,IAAI,IAAI;IAU7B;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAyDjE;;;;;;;;OAQG;IACH,OAAO,CAAC,MAAM;CAOf"} \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-client.js b/lib/core/user-agents/subscribe-user-agent-client.js deleted file mode 100644 index 583d7a83c..000000000 --- a/lib/core/user-agents/subscribe-user-agent-client.js +++ /dev/null @@ -1,287 +0,0 @@ -import { SubscriptionDialog } from "../dialogs/subscription-dialog"; -import { SubscriptionState } from "../subscription"; -import { Timers } from "../timers"; -import { NonInviteClientTransaction } from "../transactions"; -import { UserAgentClient } from "./user-agent-client"; -/** - * SUBSCRIBE UAC. - * @remarks - * 4.1. Subscriber Behavior - * https://tools.ietf.org/html/rfc6665#section-4.1 - * - * User agent client for installation of a single subscription per SUBSCRIBE request. - * TODO: Support for installation of multiple subscriptions on forked SUBSCRIBE requests. - * @public - */ -export class SubscribeUserAgentClient extends UserAgentClient { - constructor(core, message, delegate) { - // Get event from request message. - const event = message.getHeader("Event"); - if (!event) { - throw new Error("Event undefined"); - } - // Get expires from request message. - const expires = message.getHeader("Expires"); - if (!expires) { - throw new Error("Expires undefined"); - } - super(NonInviteClientTransaction, core, message, delegate); - this.delegate = delegate; - // FIXME: Subscriber id should also be matching on event id. - this.subscriberId = message.callId + message.fromTag + event; - this.subscriptionExpiresRequested = this.subscriptionExpires = Number(expires); - this.subscriptionEvent = event; - this.subscriptionState = SubscriptionState.NotifyWait; - // Start waiting for a NOTIFY we can use to create a subscription. - this.waitNotifyStart(); - } - /** - * Destructor. - * Note that Timer N may live on waiting for an initial NOTIFY and - * the delegate may still receive that NOTIFY. If you don't want - * that behavior then either clear the delegate so the delegate - * doesn't get called (a 200 will be sent in response to the NOTIFY) - * or call `waitNotifyStop` which will clear Timer N and remove this - * UAC from the core (a 481 will be sent in response to the NOTIFY). - */ - dispose() { - super.dispose(); - } - /** - * Handle out of dialog NOTIFY associated with SUBSCRIBE request. - * This is the first NOTIFY received after the SUBSCRIBE request. - * @param uas - User agent server handling the subscription creating NOTIFY. - */ - onNotify(uas) { - // NOTIFY requests are matched to such SUBSCRIBE requests if they - // contain the same "Call-ID", a "To" header field "tag" parameter that - // matches the "From" header field "tag" parameter of the SUBSCRIBE - // request, and the same "Event" header field. Rules for comparisons of - // the "Event" header fields are described in Section 8.2.1. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - const event = uas.message.parseHeader("Event").event; - if (!event || event !== this.subscriptionEvent) { - this.logger.warn(`Failed to parse event.`); - uas.reject({ statusCode: 489 }); - return; - } - // NOTIFY requests MUST contain "Subscription-State" header fields that - // indicate the status of the subscription. - // https://tools.ietf.org/html/rfc6665#section-4.1.3 - const subscriptionState = uas.message.parseHeader("Subscription-State"); - if (!subscriptionState || !subscriptionState.state) { - this.logger.warn("Failed to parse subscription state."); - uas.reject({ statusCode: 489 }); - return; - } - // Validate subscription state. - const state = subscriptionState.state; - switch (state) { - case "pending": - break; - case "active": - break; - case "terminated": - break; - default: - this.logger.warn(`Invalid subscription state ${state}`); - uas.reject({ statusCode: 489 }); - return; - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (state !== "terminated") { - // The Contact header field MUST be present and contain exactly one SIP - // or SIPS URI in any request that can result in the establishment of a - // dialog. - // https://tools.ietf.org/html/rfc3261#section-8.1.1.8 - const contact = uas.message.parseHeader("contact"); - if (!contact) { - this.logger.warn("Failed to parse contact."); - uas.reject({ statusCode: 489 }); - return; - } - } - // In accordance with the rules for proxying non-INVITE requests as - // defined in [RFC3261], successful SUBSCRIBE requests will receive only - // one 200-class response; however, due to forking, the subscription may - // have been accepted by multiple nodes. The subscriber MUST therefore - // be prepared to receive NOTIFY requests with "From:" tags that differ - // from the "To:" tag received in the SUBSCRIBE 200-class response. - // - // If multiple NOTIFY requests are received in different dialogs in - // response to a single SUBSCRIBE request, each dialog represents a - // different destination to which the SUBSCRIBE request was forked. - // Subscriber handling in such situations varies by event package; see - // Section 5.4.9 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.4 - // Each event package MUST specify whether forked SUBSCRIBE requests are - // allowed to install multiple subscriptions. - // - // If such behavior is not allowed, the first potential dialog- - // establishing message will create a dialog. All subsequent NOTIFY - // requests that correspond to the SUBSCRIBE request (i.e., have - // matching "To", "From", "Call-ID", and "Event" header fields, as well - // as "From" header field "tag" parameter and "Event" header field "id" - // parameter) but that do not match the dialog would be rejected with a - // 481 response. Note that the 200-class response to the SUBSCRIBE - // request can arrive after a matching NOTIFY request has been received; - // such responses might not correlate to the same dialog established by - // the NOTIFY request. Except as required to complete the SUBSCRIBE - // transaction, such non-matching 200-class responses are ignored. - // - // If installing of multiple subscriptions by way of a single forked - // SUBSCRIBE request is allowed, the subscriber establishes a new dialog - // towards each notifier by returning a 200-class response to each - // NOTIFY request. Each dialog is then handled as its own entity and is - // refreshed independently of the other dialogs. - // - // In the case that multiple subscriptions are allowed, the event - // package MUST specify whether merging of the notifications to form a - // single state is required, and how such merging is to be performed. - // Note that it is possible that some event packages may be defined in - // such a way that each dialog is tied to a mutually exclusive state - // that is unaffected by the other dialogs; this MUST be clearly stated - // if it is the case. - // https://tools.ietf.org/html/rfc6665#section-5.4.9 - // *** NOTE: This implementation is only for event packages which - // do not allow forked requests to install multiple subscriptions. - // As such and in accordance with the specification, we stop waiting - // and any future NOTIFY requests will be rejected with a 481. - if (this.dialog) { - throw new Error("Dialog already created. This implementation only supports install of single subscriptions."); - } - this.waitNotifyStop(); - // Update expires. - this.subscriptionExpires = subscriptionState.expires - ? Math.min(this.subscriptionExpires, Math.max(subscriptionState.expires, 0)) - : this.subscriptionExpires; - // Update subscription state. - switch (state) { - case "pending": - this.subscriptionState = SubscriptionState.Pending; - break; - case "active": - this.subscriptionState = SubscriptionState.Active; - break; - case "terminated": - this.subscriptionState = SubscriptionState.Terminated; - break; - default: - throw new Error(`Unrecognized state ${state}.`); - } - // Dialogs usages are created upon completion of a NOTIFY transaction - // for a new subscription, unless the NOTIFY request contains a - // "Subscription-State" of "terminated." - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - if (this.subscriptionState !== SubscriptionState.Terminated) { - // Because the dialog usage is established by the NOTIFY request, the - // route set at the subscriber is taken from the NOTIFY request itself, - // as opposed to the route set present in the 200-class response to the - // SUBSCRIBE request. - // https://tools.ietf.org/html/rfc6665#section-4.4.1 - const dialogState = SubscriptionDialog.initialDialogStateForSubscription(this.message, uas.message); - // Subscription Initiated! :) - this.dialog = new SubscriptionDialog(this.subscriptionEvent, this.subscriptionExpires, this.subscriptionState, this.core, dialogState); - } - // Delegate. - if (this.delegate && this.delegate.onNotify) { - const request = uas; - const subscription = this.dialog; - this.delegate.onNotify({ request, subscription }); - } - else { - uas.accept(); - } - } - waitNotifyStart() { - if (!this.N) { - // Add ourselves to the core's subscriber map. - // This allows the core to route out of dialog NOTIFY messages to us. - this.core.subscribers.set(this.subscriberId, this); - this.N = setTimeout(() => this.timerN(), Timers.TIMER_N); - } - } - waitNotifyStop() { - if (this.N) { - // Remove ourselves to the core's subscriber map. - // Any future out of dialog NOTIFY messages will be rejected with a 481. - this.core.subscribers.delete(this.subscriberId); - clearTimeout(this.N); - this.N = undefined; - } - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - if (message.statusCode && message.statusCode >= 200 && message.statusCode < 300) { - // The "Expires" header field in a 200-class response to SUBSCRIBE - // request indicates the actual duration for which the subscription will - // remain active (unless refreshed). The received value might be - // smaller than the value indicated in the SUBSCRIBE request but cannot - // be larger; see Section 4.2.1 for details. - // https://tools.ietf.org/html/rfc6665#section-4.1.2.1 - // The "Expires" values present in SUBSCRIBE 200-class responses behave - // in the same way as they do in REGISTER responses: the server MAY - // shorten the interval but MUST NOT lengthen it. - // - // If the duration specified in a SUBSCRIBE request is unacceptably - // short, the notifier may be able to send a 423 response, as - // described earlier in this section. - // - // 200-class responses to SUBSCRIBE requests will not generally contain - // any useful information beyond subscription duration; their primary - // purpose is to serve as a reliability mechanism. State information - // will be communicated via a subsequent NOTIFY request from the - // notifier. - // https://tools.ietf.org/html/rfc6665#section-4.2.1.1 - const expires = message.getHeader("Expires"); - if (!expires) { - this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE"); - } - else { - const subscriptionExpiresReceived = Number(expires); - if (subscriptionExpiresReceived > this.subscriptionExpiresRequested) { - this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"); - } - if (subscriptionExpiresReceived < this.subscriptionExpires) { - this.subscriptionExpires = subscriptionExpiresReceived; - } - } - // If a NOTIFY arrived before 200-class response a dialog may have been created. - // Updated the dialogs expiration only if this indicates earlier expiration. - if (this.dialog) { - if (this.dialog.subscriptionExpires > this.subscriptionExpires) { - this.dialog.subscriptionExpires = this.subscriptionExpires; - } - } - } - if (message.statusCode && message.statusCode >= 300 && message.statusCode < 700) { - this.waitNotifyStop(); // No NOTIFY will be sent after a negative final response. - } - super.receiveResponse(message); - } - /** - * To ensure that subscribers do not wait indefinitely for a - * subscription to be established, a subscriber starts a Timer N, set to - * 64*T1, when it sends a SUBSCRIBE request. If this Timer N expires - * prior to the receipt of a NOTIFY request, the subscriber considers - * the subscription failed, and cleans up any state associated with the - * subscription attempt. - * https://tools.ietf.org/html/rfc6665#section-4.1.2.4 - */ - timerN() { - this.logger.warn(`Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY.`); - this.waitNotifyStop(); - if (this.delegate && this.delegate.onNotifyTimeout) { - this.delegate.onNotifyTimeout(); - } - } -} diff --git a/lib/core/user-agents/subscribe-user-agent-server.d.ts b/lib/core/user-agents/subscribe-user-agent-server.d.ts deleted file mode 100644 index ad65a8261..000000000 --- a/lib/core/user-agents/subscribe-user-agent-server.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IncomingRequestDelegate, IncomingRequestMessage, IncomingSubscribeRequest } from "../messages"; -import { UserAgentCore } from "../user-agent-core"; -import { UserAgentServer } from "./user-agent-server"; -/** - * SUBSCRIBE UAS. - * @public - */ -export declare class SubscribeUserAgentServer extends UserAgentServer implements IncomingSubscribeRequest { - protected core: UserAgentCore; - constructor(core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate); -} -//# sourceMappingURL=subscribe-user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-server.d.ts.map b/lib/core/user-agents/subscribe-user-agent-server.d.ts.map deleted file mode 100644 index 5a807c08c..000000000 --- a/lib/core/user-agents/subscribe-user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"subscribe-user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/subscribe-user-agent-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAExG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,qBAAa,wBAAyB,SAAQ,eAAgB,YAAW,wBAAwB;IACnF,SAAS,CAAC,IAAI,EAAE,aAAa;gBAAnB,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,sBAAsB,EAAE,QAAQ,CAAC,EAAE,uBAAuB;CAG/G"} \ No newline at end of file diff --git a/lib/core/user-agents/subscribe-user-agent-server.js b/lib/core/user-agents/subscribe-user-agent-server.js deleted file mode 100644 index 0a74d226d..000000000 --- a/lib/core/user-agents/subscribe-user-agent-server.js +++ /dev/null @@ -1,12 +0,0 @@ -import { NonInviteServerTransaction } from "../transactions"; -import { UserAgentServer } from "./user-agent-server"; -/** - * SUBSCRIBE UAS. - * @public - */ -export class SubscribeUserAgentServer extends UserAgentServer { - constructor(core, message, delegate) { - super(NonInviteServerTransaction, core, message, delegate); - this.core = core; - } -} diff --git a/lib/core/user-agents/user-agent-client.d.ts b/lib/core/user-agents/user-agent-client.d.ts deleted file mode 100644 index bef772398..000000000 --- a/lib/core/user-agents/user-agent-client.d.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { Dialog } from "../dialogs"; -import { TransportError } from "../exceptions"; -import { Logger, LoggerFactory } from "../log"; -import { IncomingResponseMessage, OutgoingRequest, OutgoingRequestDelegate, OutgoingRequestMessage, RequestOptions } from "../messages"; -import { ClientTransaction, ClientTransactionUser } from "../transactions"; -import { Transport } from "../transport"; -import { UserAgentCore } from "../user-agent-core"; -declare type ClientTransactionConstructor = new (message: OutgoingRequestMessage, transport: Transport, user: ClientTransactionUser) => ClientTransaction; -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export declare class UserAgentClient implements OutgoingRequest { - private transactionConstructor; - protected core: UserAgentCore; - message: OutgoingRequestMessage; - delegate?: OutgoingRequestDelegate | undefined; - protected logger: Logger; - private _transaction; - private credentials; - private challenged; - private stale; - constructor(transactionConstructor: ClientTransactionConstructor, core: UserAgentCore, message: OutgoingRequestMessage, delegate?: OutgoingRequestDelegate | undefined); - dispose(): void; - get loggerFactory(): LoggerFactory; - /** The transaction associated with this request. */ - get transaction(): ClientTransaction; - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - cancel(reason?: string, options?: RequestOptions): OutgoingRequestMessage; - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @param dialog - If defined, the dialog within which the response was received. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - protected authenticationGuard(message: IncomingResponseMessage, dialog?: Dialog): boolean; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - protected onRequestTimeout(): void; - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * @param error - Transport error - */ - protected onTransportError(error: TransportError): void; - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - protected receiveResponse(message: IncomingResponseMessage): void; - private init; -} -export {}; -//# sourceMappingURL=user-agent-client.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-client.d.ts.map b/lib/core/user-agents/user-agent-client.d.ts.map deleted file mode 100644 index 3744966e9..000000000 --- a/lib/core/user-agents/user-agent-client.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-client.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/user-agent-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAEL,uBAAuB,EACvB,eAAe,EACf,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EAGtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,aAAK,4BAA4B,GAAG,KAClC,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,qBAAqB,KACxB,iBAAiB,CAAC;AAEvB;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAgB,YAAW,eAAe;IAWnD,OAAO,CAAC,sBAAsB;IAC9B,SAAS,CAAC,IAAI,EAAE,aAAa;IACtB,OAAO,EAAE,sBAAsB;IAC/B,QAAQ,CAAC;IAblB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IAEzB,OAAO,CAAC,YAAY,CAAgC;IAGpD,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,KAAK,CAAS;gBAGZ,sBAAsB,EAAE,4BAA4B,EAClD,IAAI,EAAE,aAAa,EACtB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,qCAAyB;IAMpC,OAAO,IAAI,IAAI;IAItB,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,oDAAoD;IACpD,IAAI,WAAW,IAAI,iBAAiB,CAKnC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,sBAAsB;IA4EpF;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO;IA+EzF;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,gBAAgB,IAAI,IAAI;IASlC;;;;;;;;;;;;OAYG;IACH,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IASvD;;;OAGG;IACH,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAyCjE,OAAO,CAAC,IAAI;CA6Bb"} \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-client.js b/lib/core/user-agents/user-agent-client.js deleted file mode 100644 index a492ae038..000000000 --- a/lib/core/user-agents/user-agent-client.js +++ /dev/null @@ -1,309 +0,0 @@ -import { C, IncomingResponseMessage } from "../messages"; -import { NonInviteClientTransaction, TransactionState } from "../transactions"; -/** - * User Agent Client (UAC). - * @remarks - * A user agent client is a logical entity - * that creates a new request, and then uses the client - * transaction state machinery to send it. The role of UAC lasts - * only for the duration of that transaction. In other words, if - * a piece of software initiates a request, it acts as a UAC for - * the duration of that transaction. If it receives a request - * later, it assumes the role of a user agent server for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export class UserAgentClient { - constructor(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.challenged = false; - this.stale = false; - this.logger = this.loggerFactory.getLogger("sip.user-agent-client"); - this.init(); - } - dispose() { - this.transaction.dispose(); - } - get loggerFactory() { - return this.core.loggerFactory; - } - /** The transaction associated with this request. */ - get transaction() { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - } - /** - * Since requests other than INVITE are responded to immediately, sending a - * CANCEL for a non-INVITE request would always create a race condition. - * A CANCEL request SHOULD NOT be sent to cancel a request other than INVITE. - * https://tools.ietf.org/html/rfc3261#section-9.1 - * @param options - Cancel options bucket. - */ - cancel(reason, options = {}) { - if (!this.transaction) { - throw new Error("Transaction undefined."); - } - if (!this.message.to) { - throw new Error("To undefined."); - } - if (!this.message.from) { - throw new Error("From undefined."); - } - // The following procedures are used to construct a CANCEL request. The - // Request-URI, Call-ID, To, the numeric part of CSeq, and From header - // fields in the CANCEL request MUST be identical to those in the - // request being cancelled, including tags. A CANCEL constructed by a - // client MUST have only a single Via header field value matching the - // top Via value in the request being cancelled. Using the same values - // for these header fields allows the CANCEL to be matched with the - // request it cancels (Section 9.2 indicates how such matching occurs). - // However, the method part of the CSeq header field MUST have a value - // of CANCEL. This allows it to be identified and processed as a - // transaction in its own right (See Section 17). - // https://tools.ietf.org/html/rfc3261#section-9.1 - const message = this.core.makeOutgoingRequestMessage(C.CANCEL, this.message.ruri, this.message.from.uri, this.message.to.uri, { - toTag: this.message.toTag, - fromTag: this.message.fromTag, - callId: this.message.callId, - cseq: this.message.cseq - }, options.extraHeaders); - // TODO: Revisit this. - // The CANCEL needs to use the same branch parameter so that - // it matches the INVITE transaction, but this is a hacky way to do this. - // Or at the very least not well documented. If the the branch parameter - // is set on the outgoing request, the transaction will use it. - // Otherwise the transaction will make a new one. - message.branch = this.message.branch; - if (this.message.headers.Route) { - message.headers.Route = this.message.headers.Route; - } - if (reason) { - message.setHeader("Reason", reason); - } - // If no provisional response has been received, the CANCEL request MUST - // NOT be sent; rather, the client MUST wait for the arrival of a - // provisional response before sending the request. If the original - // request has generated a final response, the CANCEL SHOULD NOT be - // sent, as it is an effective no-op, since CANCEL has no effect on - // requests that have already generated a final response. - // https://tools.ietf.org/html/rfc3261#section-9.1 - if (this.transaction.state === TransactionState.Proceeding) { - new UserAgentClient(NonInviteClientTransaction, this.core, message); - } - else { - this.transaction.addStateChangeListener(() => { - if (this.transaction && this.transaction.state === TransactionState.Proceeding) { - new UserAgentClient(NonInviteClientTransaction, this.core, message); - } - }, { once: true }); - } - return message; - } - /** - * If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - * response is received, the UAC SHOULD follow the authorization - * procedures of Section 22.2 and Section 22.3 to retry the request with - * credentials. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - * 22 Usage of HTTP Authentication - * https://tools.ietf.org/html/rfc3261#section-22 - * 22.1 Framework - * https://tools.ietf.org/html/rfc3261#section-22.1 - * 22.2 User-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.2 - * 22.3 Proxy-to-User Authentication - * https://tools.ietf.org/html/rfc3261#section-22.3 - * - * FIXME: This "guard for and retry the request with credentials" - * implementation is not complete and at best minimally passable. - * @param response - The incoming response to guard. - * @param dialog - If defined, the dialog within which the response was received. - * @returns True if the program execution is to continue in the branch in question. - * Otherwise the request is retried with credentials and current request processing must stop. - */ - authenticationGuard(message, dialog) { - const statusCode = message.statusCode; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - // If a 401 (Unauthorized) or 407 (Proxy Authentication Required) - // response is received, the UAC SHOULD follow the authorization - // procedures of Section 22.2 and Section 22.3 to retry the request with - // credentials. - // https://tools.ietf.org/html/rfc3261#section-8.1.3.5 - if (statusCode !== 401 && statusCode !== 407) { - return true; - } - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let challenge; - let authorizationHeaderName; - if (statusCode === 401) { - challenge = message.parseHeader("www-authenticate"); - authorizationHeaderName = "authorization"; - } - else { - challenge = message.parseHeader("proxy-authenticate"); - authorizationHeaderName = "proxy-authorization"; - } - // Verify it seems a valid challenge. - if (!challenge) { - this.logger.warn(statusCode + " with wrong or missing challenge, cannot authenticate"); - return true; - } - // Avoid infinite authentications. - if (this.challenged && (this.stale || challenge.stale !== true)) { - this.logger.warn(statusCode + " apparently in authentication loop, cannot authenticate"); - return true; - } - // Get credentials. - if (!this.credentials) { - this.credentials = this.core.configuration.authenticationFactory(); - if (!this.credentials) { - this.logger.warn("Unable to obtain credentials, cannot authenticate"); - return true; - } - } - // Verify that the challenge is really valid. - if (!this.credentials.authenticate(this.message, challenge)) { - return true; - } - this.challenged = true; - if (challenge.stale) { - this.stale = true; - } - // If response to out of dialog request, assume incrementing the CSeq will suffice. - let cseq = (this.message.cseq += 1); - // If response to in dialog request, get a valid next CSeq number. - if (dialog && dialog.localSequenceNumber) { - dialog.incrementLocalSequenceNumber(); - cseq = this.message.cseq = dialog.localSequenceNumber; - } - this.message.setHeader("cseq", cseq + " " + this.message.method); - this.message.setHeader(authorizationHeaderName, this.credentials.toString()); - // Calling init (again) will swap out our existing client transaction with a new one. - // FIXME: HACK: An assumption is being made here that there is nothing that needs to - // be cleaned up beyond the client transaction which is being replaced. For example, - // it is assumed that no early dialogs have been created. - this.init(); - return false; - } - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - */ - onRequestTimeout() { - this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout."); - const message = new IncomingResponseMessage(); - message.statusCode = 408; - message.reasonPhrase = "Request Timeout"; - this.receiveResponse(message); - return; - } - /** - * 8.1.3.1 Transaction Layer Errors - * In some cases, the response returned by the transaction layer will - * not be a SIP message, but rather a transaction layer error. When a - * timeout error is received from the transaction layer, it MUST be - * treated as if a 408 (Request Timeout) status code has been received. - * If a fatal transport error is reported by the transport layer - * (generally, due to fatal ICMP errors in UDP or connection failures in - * TCP), the condition MUST be treated as a 503 (Service Unavailable) - * status code. - * https://tools.ietf.org/html/rfc3261#section-8.1.3.1 - * @param error - Transport error - */ - onTransportError(error) { - this.logger.error(error.message); - this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable."); - const message = new IncomingResponseMessage(); - message.statusCode = 503; - message.reasonPhrase = "Service Unavailable"; - this.receiveResponse(message); - } - /** - * Receive a response from the transaction layer. - * @param message - Incoming response message. - */ - receiveResponse(message) { - if (!this.authenticationGuard(message)) { - return; - } - const statusCode = message.statusCode ? message.statusCode.toString() : ""; - if (!statusCode) { - throw new Error("Response status code undefined."); - } - switch (true) { - case /^100$/.test(statusCode): - if (this.delegate && this.delegate.onTrying) { - this.delegate.onTrying({ message }); - } - break; - case /^1[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onProgress) { - this.delegate.onProgress({ message }); - } - break; - case /^2[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onAccept) { - this.delegate.onAccept({ message }); - } - break; - case /^3[0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onRedirect) { - this.delegate.onRedirect({ message }); - } - break; - case /^[4-6][0-9]{2}$/.test(statusCode): - if (this.delegate && this.delegate.onReject) { - this.delegate.onReject({ message }); - } - break; - default: - throw new Error(`Invalid status code ${statusCode}`); - } - } - init() { - // We are the transaction user. - const user = { - loggerFactory: this.loggerFactory, - onRequestTimeout: () => this.onRequestTimeout(), - onStateChange: (newState) => { - if (newState === TransactionState.Terminated) { - // Remove the terminated transaction from the core. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.core.userAgentClients.delete(userAgentClientId); - // FIXME: HACK: Our transaction may have been swapped out with a new one - // post authentication (see above), so make sure to only to dispose of - // ourselves if this terminating transaction is our current transaction. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - if (transaction === this._transaction) { - this.dispose(); - } - } - }, - onTransportError: (error) => this.onTransportError(error), - receiveResponse: (message) => this.receiveResponse(message) - }; - // Create a new transaction with us as the user. - const transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - const userAgentClientId = transaction.id + transaction.request.method; - this.core.userAgentClients.set(userAgentClientId, this); - } -} diff --git a/lib/core/user-agents/user-agent-server.d.ts b/lib/core/user-agents/user-agent-server.d.ts deleted file mode 100644 index 807a60604..000000000 --- a/lib/core/user-agents/user-agent-server.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { Logger, LoggerFactory } from "../log"; -import { IncomingRequest, IncomingRequestDelegate, IncomingRequestMessage, OutgoingResponse, ResponseOptions, URI } from "../messages"; -import { ServerTransaction, ServerTransactionUser } from "../transactions"; -import { Transport } from "../transport"; -import { UserAgentCore } from "../user-agent-core"; -declare type ServerTransactionConstructor = new (message: IncomingRequestMessage, transport: Transport, user: ServerTransactionUser) => ServerTransaction; -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export declare class UserAgentServer implements IncomingRequest { - private transactionConstructor; - protected core: UserAgentCore; - message: IncomingRequestMessage; - delegate?: IncomingRequestDelegate | undefined; - protected logger: Logger; - protected toTag: string; - private _transaction; - constructor(transactionConstructor: ServerTransactionConstructor, core: UserAgentCore, message: IncomingRequestMessage, delegate?: IncomingRequestDelegate | undefined); - dispose(): void; - get loggerFactory(): LoggerFactory; - /** The transaction associated with this request. */ - get transaction(): ServerTransaction; - accept(options?: ResponseOptions): OutgoingResponse; - progress(options?: ResponseOptions): OutgoingResponse; - redirect(contacts: Array, options?: ResponseOptions): OutgoingResponse; - reject(options?: ResponseOptions): OutgoingResponse; - trying(options?: ResponseOptions): OutgoingResponse; - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - receiveCancel(message: IncomingRequestMessage): void; - protected get acceptable(): boolean; - protected get progressable(): boolean; - protected get redirectable(): boolean; - protected get rejectable(): boolean; - protected get tryingable(): boolean; - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - private reply; - private init; -} -export {}; -//# sourceMappingURL=user-agent-server.d.ts.map \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-server.d.ts.map b/lib/core/user-agents/user-agent-server.d.ts.map deleted file mode 100644 index 8474aa6d7..000000000 --- a/lib/core/user-agents/user-agent-server.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user-agent-server.d.ts","sourceRoot":"","sources":["../../../src/core/user-agents/user-agent-server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,eAAe,EACf,GAAG,EACJ,MAAM,aAAa,CAAC;AAGrB,OAAO,EAGL,iBAAiB,EACjB,qBAAqB,EAEtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,aAAK,4BAA4B,GAAG,KAClC,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,qBAAqB,KACxB,iBAAiB,CAAC;AAEvB;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAgB,YAAW,eAAe;IAOnD,OAAO,CAAC,sBAAsB;IAC9B,SAAS,CAAC,IAAI,EAAE,aAAa;IACtB,OAAO,EAAE,sBAAsB;IAC/B,QAAQ,CAAC;IATlB,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;IAExB,OAAO,CAAC,YAAY,CAAgC;gBAG1C,sBAAsB,EAAE,4BAA4B,EAClD,IAAI,EAAE,aAAa,EACtB,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,CAAC,qCAAyB;IAOpC,OAAO,IAAI,IAAI;IAItB,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,oDAAoD;IACpD,IAAI,WAAW,IAAI,iBAAiB,CAKnC;IAEM,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAYxE,QAAQ,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAY1E,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAehG,MAAM,CAAC,OAAO,GAAE,eAAqC,GAAG,gBAAgB;IAaxE,MAAM,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAQ1D;;;;;;;;;;;;;;;;;OAiBG;IACI,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAW3D,SAAS,KAAK,UAAU,IAAI,OAAO,CAYlC;IAED,SAAS,KAAK,YAAY,IAAI,OAAO,CAQpC;IAED,SAAS,KAAK,YAAY,IAAI,OAAO,CAUpC;IAED,SAAS,KAAK,UAAU,IAAI,OAAO,CAUlC;IAED,SAAS,KAAK,UAAU,IAAI,OAAO,CAQlC;IAED;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,KAAK;IAWb,OAAO,CAAC,IAAI;CA4Bb"} \ No newline at end of file diff --git a/lib/core/user-agents/user-agent-server.js b/lib/core/user-agents/user-agent-server.js deleted file mode 100644 index b33cd37bb..000000000 --- a/lib/core/user-agents/user-agent-server.js +++ /dev/null @@ -1,222 +0,0 @@ -import { TransactionStateError } from "../exceptions"; -import { constructOutgoingResponse } from "../messages"; -import { newTag } from "../messages/utils"; -import { InviteServerTransaction, NonInviteServerTransaction, TransactionState } from "../transactions"; -/** - * User Agent Server (UAS). - * @remarks - * A user agent server is a logical entity - * that generates a response to a SIP request. The response - * accepts, rejects, or redirects the request. This role lasts - * only for the duration of that transaction. In other words, if - * a piece of software responds to a request, it acts as a UAS for - * the duration of that transaction. If it generates a request - * later, it assumes the role of a user agent client for the - * processing of that transaction. - * https://tools.ietf.org/html/rfc3261#section-6 - * @public - */ -export class UserAgentServer { - constructor(transactionConstructor, core, message, delegate) { - this.transactionConstructor = transactionConstructor; - this.core = core; - this.message = message; - this.delegate = delegate; - this.logger = this.loggerFactory.getLogger("sip.user-agent-server"); - this.toTag = message.toTag ? message.toTag : newTag(); - this.init(); - } - dispose() { - this.transaction.dispose(); - } - get loggerFactory() { - return this.core.loggerFactory; - } - /** The transaction associated with this request. */ - get transaction() { - if (!this._transaction) { - throw new Error("Transaction undefined."); - } - return this._transaction; - } - accept(options = { statusCode: 200 }) { - if (!this.acceptable) { - throw new TransactionStateError(`${this.message.method} not acceptable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 200 || statusCode > 299) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - progress(options = { statusCode: 180 }) { - if (!this.progressable) { - throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 101 || statusCode > 199) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - redirect(contacts, options = { statusCode: 302 }) { - if (!this.redirectable) { - throw new TransactionStateError(`${this.message.method} not redirectable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 300 || statusCode > 399) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const contactHeaders = new Array(); - contacts.forEach((contact) => contactHeaders.push(`Contact: ${contact.toString()}`)); - options.extraHeaders = (options.extraHeaders || []).concat(contactHeaders); - const response = this.reply(options); - return response; - } - reject(options = { statusCode: 480 }) { - if (!this.rejectable) { - throw new TransactionStateError(`${this.message.method} not rejectable in state ${this.transaction.state}.`); - } - const statusCode = options.statusCode; - if (statusCode < 400 || statusCode > 699) { - throw new TypeError(`Invalid statusCode: ${statusCode}`); - } - const response = this.reply(options); - return response; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - trying(options) { - if (!this.tryingable) { - throw new TransactionStateError(`${this.message.method} not tryingable in state ${this.transaction.state}.`); - } - const response = this.reply({ statusCode: 100 }); - return response; - } - /** - * If the UAS did not find a matching transaction for the CANCEL - * according to the procedure above, it SHOULD respond to the CANCEL - * with a 481 (Call Leg/Transaction Does Not Exist). If the transaction - * for the original request still exists, the behavior of the UAS on - * receiving a CANCEL request depends on whether it has already sent a - * final response for the original request. If it has, the CANCEL - * request has no effect on the processing of the original request, no - * effect on any session state, and no effect on the responses generated - * for the original request. If the UAS has not issued a final response - * for the original request, its behavior depends on the method of the - * original request. If the original request was an INVITE, the UAS - * SHOULD immediately respond to the INVITE with a 487 (Request - * Terminated). A CANCEL request has no impact on the processing of - * transactions with any other method defined in this specification. - * https://tools.ietf.org/html/rfc3261#section-9.2 - * @param request - Incoming CANCEL request. - */ - receiveCancel(message) { - // Note: Currently CANCEL is being handled as a special case. - // No UAS is created to handle the CANCEL and the response to - // it CANCEL is being handled statelessly by the user agent core. - // As such, there is currently no way to externally impact the - // response to the a CANCEL request. - if (this.delegate && this.delegate.onCancel) { - this.delegate.onCancel(message); - } - } - get acceptable() { - if (this.transaction instanceof InviteServerTransaction) { - return (this.transaction.state === TransactionState.Proceeding || this.transaction.state === TransactionState.Accepted); - } - if (this.transaction instanceof NonInviteServerTransaction) { - return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - } - get progressable() { - if (this.transaction instanceof InviteServerTransaction) { - return this.transaction.state === TransactionState.Proceeding; - } - if (this.transaction instanceof NonInviteServerTransaction) { - return false; // https://tools.ietf.org/html/rfc4320#section-4.1 - } - throw new Error("Unknown transaction type."); - } - get redirectable() { - if (this.transaction instanceof InviteServerTransaction) { - return this.transaction.state === TransactionState.Proceeding; - } - if (this.transaction instanceof NonInviteServerTransaction) { - return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - } - get rejectable() { - if (this.transaction instanceof InviteServerTransaction) { - return this.transaction.state === TransactionState.Proceeding; - } - if (this.transaction instanceof NonInviteServerTransaction) { - return (this.transaction.state === TransactionState.Trying || this.transaction.state === TransactionState.Proceeding); - } - throw new Error("Unknown transaction type."); - } - get tryingable() { - if (this.transaction instanceof InviteServerTransaction) { - return this.transaction.state === TransactionState.Proceeding; - } - if (this.transaction instanceof NonInviteServerTransaction) { - return this.transaction.state === TransactionState.Trying; - } - throw new Error("Unknown transaction type."); - } - /** - * When a UAS wishes to construct a response to a request, it follows - * the general procedures detailed in the following subsections. - * Additional behaviors specific to the response code in question, which - * are not detailed in this section, may also be required. - * - * Once all procedures associated with the creation of a response have - * been completed, the UAS hands the response back to the server - * transaction from which it received the request. - * https://tools.ietf.org/html/rfc3261#section-8.2.6 - * @param statusCode - Status code to reply with. - * @param options - Reply options bucket. - */ - reply(options) { - if (!options.toTag && options.statusCode !== 100) { - options.toTag = this.toTag; - } - options.userAgent = options.userAgent || this.core.configuration.userAgentHeaderFieldValue; - options.supported = options.supported || this.core.configuration.supportedOptionTagsResponse; - const response = constructOutgoingResponse(this.message, options); - this.transaction.receiveResponse(options.statusCode, response.message); - return response; - } - init() { - // We are the transaction user. - const user = { - loggerFactory: this.loggerFactory, - onStateChange: (newState) => { - if (newState === TransactionState.Terminated) { - // Remove the terminated transaction from the core. - // eslint-disable-next-line @typescript-eslint/no-use-before-define - this.core.userAgentServers.delete(userAgentServerId); - this.dispose(); - } - }, - onTransportError: (error) => { - this.logger.error(error.message); - if (this.delegate && this.delegate.onTransportError) { - this.delegate.onTransportError(error); - } - else { - this.logger.error("User agent server response transport error."); - } - } - }; - // Create a new transaction with us as the user. - const transaction = new this.transactionConstructor(this.message, this.core.transport, user); - this._transaction = transaction; - // Add the new transaction to the core. - const userAgentServerId = transaction.id; - this.core.userAgentServers.set(transaction.id, this); - } -} diff --git a/lib/grammar/grammar.d.ts b/lib/grammar/grammar.d.ts deleted file mode 100644 index 656d32dfd..000000000 --- a/lib/grammar/grammar.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { NameAddrHeader } from "./name-addr-header"; -import { URI } from "./uri"; -/** - * Grammar. - * @internal - */ -export declare namespace Grammar { - /** - * Parse. - * @param input - - * @param startRule - - */ - function parse(input: string, startRule: string): any; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader: string): NameAddrHeader | undefined; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri: string): URI | undefined; -} -//# sourceMappingURL=grammar.d.ts.map \ No newline at end of file diff --git a/lib/grammar/grammar.d.ts.map b/lib/grammar/grammar.d.ts.map deleted file mode 100644 index 597a2ca5d..000000000 --- a/lib/grammar/grammar.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../src/grammar/grammar.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B;;;GAGG;AACH,yBAAiB,OAAO,CAAC;IAEvB;;;;OAIG;IAEH,SAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,GAAG,CAU3D;IAED;;;;OAIG;IACH,SAAgB,mBAAmB,CAAC,cAAc,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAKtF;IAED;;;;OAIG;IACH,SAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CAKrD;CACF"} \ No newline at end of file diff --git a/lib/grammar/grammar.js b/lib/grammar/grammar.js deleted file mode 100644 index 1f6bdae99..000000000 --- a/lib/grammar/grammar.js +++ /dev/null @@ -1,50 +0,0 @@ -/* eslint-disable @typescript-eslint/no-namespace */ -/* eslint-disable no-inner-declarations */ -import * as pegGrammar from "./pegjs/dist/grammar"; -/** - * Grammar. - * @internal - */ -export var Grammar; -(function (Grammar) { - /** - * Parse. - * @param input - - * @param startRule - - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function parse(input, startRule) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const options = { startRule }; - try { - pegGrammar.parse(input, options); - } - catch (e) { - options.data = -1; - } - return options.data; - } - Grammar.parse = parse; - /** - * Parse the given string and returns a SIP.NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - * @param name_addr_header - - */ - function nameAddrHeaderParse(nameAddrHeader) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parsedNameAddrHeader = Grammar.parse(nameAddrHeader, "Name_Addr_Header"); - return parsedNameAddrHeader !== -1 ? parsedNameAddrHeader : undefined; - } - Grammar.nameAddrHeaderParse = nameAddrHeaderParse; - /** - * Parse the given string and returns a SIP.URI instance or undefined if - * it is an invalid URI. - * @param uri - - */ - function URIParse(uri) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const parsedUri = Grammar.parse(uri, "SIP_URI"); - return parsedUri !== -1 ? parsedUri : undefined; - } - Grammar.URIParse = URIParse; -})(Grammar || (Grammar = {})); diff --git a/lib/grammar/index.d.ts b/lib/grammar/index.d.ts deleted file mode 100644 index 3f672880a..000000000 --- a/lib/grammar/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./grammar"; -export * from "./name-addr-header"; -export * from "./parameters"; -export * from "./uri"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/grammar/index.d.ts.map b/lib/grammar/index.d.ts.map deleted file mode 100644 index 61a386066..000000000 --- a/lib/grammar/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/grammar/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,OAAO,CAAC"} \ No newline at end of file diff --git a/lib/grammar/index.js b/lib/grammar/index.js deleted file mode 100644 index 6e2c72b5c..000000000 --- a/lib/grammar/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./grammar"; -export * from "./name-addr-header"; -export * from "./parameters"; -export * from "./uri"; diff --git a/lib/grammar/name-addr-header.d.ts b/lib/grammar/name-addr-header.d.ts deleted file mode 100644 index 93a329038..000000000 --- a/lib/grammar/name-addr-header.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Parameters } from "./parameters"; -import { URI } from "./uri"; -/** - * Name Address SIP header. - * @public - */ -export declare class NameAddrHeader extends Parameters { - uri: URI; - private _displayName; - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - constructor(uri: URI, displayName: string, parameters: { - [name: string]: string; - }); - get friendlyName(): string; - get displayName(): string; - set displayName(value: string); - clone(): NameAddrHeader; - toString(): string; -} -//# sourceMappingURL=name-addr-header.d.ts.map \ No newline at end of file diff --git a/lib/grammar/name-addr-header.d.ts.map b/lib/grammar/name-addr-header.d.ts.map deleted file mode 100644 index ada0c2016..000000000 --- a/lib/grammar/name-addr-header.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"name-addr-header.d.ts","sourceRoot":"","sources":["../../src/grammar/name-addr-header.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B;;;GAGG;AACH,qBAAa,cAAe,SAAQ,UAAU;IACrC,GAAG,EAAE,GAAG,CAAC;IAEhB,OAAO,CAAC,YAAY,CAAS;IAE7B;;;;;OAKG;gBACS,GAAG,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE;IAMjF,IAAI,YAAY,IAAI,MAAM,CAEzB;IAED,IAAI,WAAW,IAAI,MAAM,CAA8B;IACvD,IAAI,WAAW,CAAC,KAAK,EAAE,MAAM,EAE5B;IAEM,KAAK,IAAI,cAAc;IAOvB,QAAQ,IAAI,MAAM;CAiB1B"} \ No newline at end of file diff --git a/lib/grammar/name-addr-header.js b/lib/grammar/name-addr-header.js deleted file mode 100644 index 306b0766b..000000000 --- a/lib/grammar/name-addr-header.js +++ /dev/null @@ -1,42 +0,0 @@ -import { Parameters } from "./parameters"; -/** - * Name Address SIP header. - * @public - */ -export class NameAddrHeader extends Parameters { - /** - * Constructor - * @param uri - - * @param displayName - - * @param parameters - - */ - constructor(uri, displayName, parameters) { - super(parameters); - this.uri = uri; - this._displayName = displayName; - } - get friendlyName() { - return this.displayName || this.uri.aor; - } - get displayName() { return this._displayName; } - set displayName(value) { - this._displayName = value; - } - clone() { - return new NameAddrHeader(this.uri.clone(), this._displayName, JSON.parse(JSON.stringify(this.parameters))); - } - toString() { - let body = (this.displayName || this.displayName === "0") ? '"' + this.displayName + '" ' : ""; - body += "<" + this.uri.toString() + ">"; - for (const parameter in this.parameters) { - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - body += ";" + parameter; - if (this.parameters[parameter] !== null) { - body += "=" + this.parameters[parameter]; - } - } - } - return body; - } -} diff --git a/lib/grammar/parameters.d.ts b/lib/grammar/parameters.d.ts deleted file mode 100644 index 299b598ba..000000000 --- a/lib/grammar/parameters.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * @internal - */ -export declare class Parameters { - parameters: { - [name: string]: string; - }; - constructor(parameters: { - [name: string]: string; - }); - setParam(key: string, value: any): void; - getParam(key: string): string | undefined; - hasParam(key: string): boolean; - deleteParam(parameter: string): any; - clearParams(): void; -} -//# sourceMappingURL=parameters.d.ts.map \ No newline at end of file diff --git a/lib/grammar/parameters.d.ts.map b/lib/grammar/parameters.d.ts.map deleted file mode 100644 index 866ff3928..000000000 --- a/lib/grammar/parameters.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parameters.d.ts","sourceRoot":"","sources":["../../src/grammar/parameters.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,UAAU;IACd,UAAU,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAC,CAAM;gBAErC,UAAU,EAAE;QAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAC;IAUzC,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAMvC,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAMzC,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAS9B,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,GAAG;IAUnC,WAAW,IAAI,IAAI;CAG3B"} \ No newline at end of file diff --git a/lib/grammar/parameters.js b/lib/grammar/parameters.js deleted file mode 100644 index ba8922d38..000000000 --- a/lib/grammar/parameters.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @internal - */ -export class Parameters { - constructor(parameters) { - this.parameters = {}; - for (const param in parameters) { - // eslint-disable-next-line no-prototype-builtins - if (parameters.hasOwnProperty(param)) { - this.setParam(param, parameters[param]); - } - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setParam(key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === "undefined" || value === null) ? null : value.toString(); - } - } - getParam(key) { - if (key) { - return this.parameters[key.toLowerCase()]; - } - } - hasParam(key) { - if (key) { - // eslint-disable-next-line no-prototype-builtins - return !!this.parameters.hasOwnProperty(key.toLowerCase()); - } - return false; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - deleteParam(parameter) { - parameter = parameter.toLowerCase(); - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - const value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - } - clearParams() { - this.parameters = {}; - } -} diff --git a/lib/grammar/pegjs/dist/grammar.d.ts b/lib/grammar/pegjs/dist/grammar.d.ts deleted file mode 100644 index 5dff5415d..000000000 --- a/lib/grammar/pegjs/dist/grammar.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -export interface IFilePosition { - offset: number; - line: number; - column: number; -} -export interface IFileRange { - start: IFilePosition; - end: IFilePosition; -} -export interface ILiteralExpectation { - type: "literal"; - text: string; - ignoreCase: boolean; -} -export interface IClassParts extends Array { -} -export interface IClassExpectation { - type: "class"; - parts: IClassParts; - inverted: boolean; - ignoreCase: boolean; -} -export interface IAnyExpectation { - type: "any"; -} -export interface IEndExpectation { - type: "end"; -} -export interface IOtherExpectation { - type: "other"; - description: string; -} -export declare type Expectation = ILiteralExpectation | IClassExpectation | IAnyExpectation | IEndExpectation | IOtherExpectation; -export declare class SyntaxError extends Error { - static buildMessage(expected: Expectation[], found: string | null): string; - message: string; - expected: Expectation[]; - found: string | null; - location: IFileRange; - name: string; - constructor(message: string, expected: Expectation[], found: string | null, location: IFileRange); -} -export interface IParseOptions { - filename?: string; - startRule?: string; - tracer?: any; - [key: string]: any; -} -export declare type ParseFunction = (input: string, options?: IParseOptions) => any; -export declare const parse: ParseFunction; -//# sourceMappingURL=grammar.d.ts.map \ No newline at end of file diff --git a/lib/grammar/pegjs/dist/grammar.d.ts.map b/lib/grammar/pegjs/dist/grammar.d.ts.map deleted file mode 100644 index 4b2899795..000000000 --- a/lib/grammar/pegjs/dist/grammar.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../../../src/grammar/pegjs/dist/grammar.ts"],"names":[],"mappings":"AA8BA,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,aAAa,CAAC;IACrB,GAAG,EAAE,aAAa,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,WAAY,SAAQ,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC;CAAG;AAEnE,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,KAAK,CAAC;CACb;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,KAAK,CAAC;CACb;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,oBAAY,WAAW,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,eAAe,GAAG,eAAe,GAAG,iBAAiB,CAAC;AAE1H,qBAAa,WAAY,SAAQ,KAAK;WACtB,YAAY,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IA0FjE,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,EAAE,UAAU,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;gBAER,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,UAAU;CAYjG;AAg3CD,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AACD,oBAAY,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,KAAK,GAAG,CAAC;AAC5E,eAAO,MAAM,KAAK,EAAE,aAAyB,CAAC"} \ No newline at end of file diff --git a/lib/grammar/pegjs/dist/grammar.js b/lib/grammar/pegjs/dist/grammar.js deleted file mode 100644 index fb8530422..000000000 --- a/lib/grammar/pegjs/dist/grammar.js +++ /dev/null @@ -1,1501 +0,0 @@ -// tslint:disable:interface-name -// tslint:disable: trailing-comma -// tslint:disable: object-literal-sort-keys -// tslint:disable: max-line-length -// tslint:disable: only-arrow-functions -// tslint:disable: one-variable-per-declaration -// tslint:disable: no-consecutive-blank-lines -// tslint:disable: align -// tslint:disable: radix -// tslint:disable: quotemark -// tslint:disable: semicolon -// tslint:disable: object-literal-shorthand -// tslint:disable: variable-name -// tslint:disable: no-var-keyword -// tslint:disable: whitespace -// tslint:disable: curly -// tslint:disable: prefer-const -// tslint:disable: object-literal-key-quotes -// tslint:disable: no-string-literal -// tslint:disable: one-line -// tslint:disable: no-unused-expression -// tslint:disable: space-before-function-paren -// tslint:disable: arrow-return-shorthand -// Generated by PEG.js v. 0.10.0 (ts-pegjs plugin v. 0.2.6 ) -// -// https://pegjs.org/ https://github.com/metadevpro/ts-pegjs -import { NameAddrHeader } from "../../name-addr-header"; -import { URI } from "../../uri"; -export class SyntaxError extends Error { - constructor(message, expected, found, location) { - super(); - this.message = message; - this.expected = expected; - this.found = found; - this.location = location; - this.name = "SyntaxError"; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(this, SyntaxError); - } - } - static buildMessage(expected, found) { - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - function literalEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) - .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); - } - function classEscape(s) { - return s - .replace(/\\/g, "\\\\") - .replace(/\]/g, "\\]") - .replace(/\^/g, "\\^") - .replace(/-/g, "\\-") - .replace(/\0/g, "\\0") - .replace(/\t/g, "\\t") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)) - .replace(/[\x10-\x1F\x7F-\x9F]/g, (ch) => "\\x" + hex(ch)); - } - function describeExpectation(expectation) { - switch (expectation.type) { - case "literal": - return "\"" + literalEscape(expectation.text) + "\""; - case "class": - const escapedParts = expectation.parts.map((part) => { - return Array.isArray(part) - ? classEscape(part[0]) + "-" + classEscape(part[1]) - : classEscape(part); - }); - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - case "any": - return "any character"; - case "end": - return "end of input"; - case "other": - return expectation.description; - } - } - function describeExpected(expected1) { - const descriptions = expected1.map(describeExpectation); - let i; - let j; - descriptions.sort(); - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - switch (descriptions.length) { - case 1: - return descriptions[0]; - case 2: - return descriptions[0] + " or " + descriptions[1]; - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - function describeFound(found1) { - return found1 ? "\"" + literalEscape(found1) + "\"" : "end of input"; - } - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - } -} -function peg$parse(input, options) { - options = options !== undefined ? options : {}; - const peg$FAILED = {}; - const peg$startRuleIndices = { Contact: 119, Name_Addr_Header: 156, Record_Route: 176, Request_Response: 81, SIP_URI: 45, Subscription_State: 186, Supported: 191, Require: 182, Via: 194, absoluteURI: 84, Call_ID: 118, Content_Disposition: 130, Content_Length: 135, Content_Type: 136, CSeq: 146, displayName: 122, Event: 149, From: 151, host: 52, Max_Forwards: 154, Min_SE: 213, Proxy_Authenticate: 157, quoted_string: 40, Refer_To: 178, Replaces: 179, Session_Expires: 210, stun_URI: 217, To: 192, turn_URI: 223, uuid: 226, WWW_Authenticate: 209, challenge: 158, sipfrag: 230, Referred_By: 231 }; - let peg$startRuleIndex = 119; - const peg$consts = [ - "\r\n", - peg$literalExpectation("\r\n", false), - /^[0-9]/, - peg$classExpectation([["0", "9"]], false, false), - /^[a-zA-Z]/, - peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - /^[0-9a-fA-F]/, - peg$classExpectation([["0", "9"], ["a", "f"], ["A", "F"]], false, false), - /^[\0-\xFF]/, - peg$classExpectation([["\0", "\xFF"]], false, false), - /^["]/, - peg$classExpectation(["\""], false, false), - " ", - peg$literalExpectation(" ", false), - "\t", - peg$literalExpectation("\t", false), - /^[a-zA-Z0-9]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - ";", - peg$literalExpectation(";", false), - "/", - peg$literalExpectation("/", false), - "?", - peg$literalExpectation("?", false), - ":", - peg$literalExpectation(":", false), - "@", - peg$literalExpectation("@", false), - "&", - peg$literalExpectation("&", false), - "=", - peg$literalExpectation("=", false), - "+", - peg$literalExpectation("+", false), - "$", - peg$literalExpectation("$", false), - ",", - peg$literalExpectation(",", false), - "-", - peg$literalExpectation("-", false), - "_", - peg$literalExpectation("_", false), - ".", - peg$literalExpectation(".", false), - "!", - peg$literalExpectation("!", false), - "~", - peg$literalExpectation("~", false), - "*", - peg$literalExpectation("*", false), - "'", - peg$literalExpectation("'", false), - "(", - peg$literalExpectation("(", false), - ")", - peg$literalExpectation(")", false), - "%", - peg$literalExpectation("%", false), - function () { return " "; }, - function () { return ':'; }, - /^[!-~]/, - peg$classExpectation([["!", "~"]], false, false), - /^[\x80-\uFFFF]/, - peg$classExpectation([["\x80", "\uFFFF"]], false, false), - /^[\x80-\xBF]/, - peg$classExpectation([["\x80", "\xBF"]], false, false), - /^[a-f]/, - peg$classExpectation([["a", "f"]], false, false), - "`", - peg$literalExpectation("`", false), - "<", - peg$literalExpectation("<", false), - ">", - peg$literalExpectation(">", false), - "\\", - peg$literalExpectation("\\", false), - "[", - peg$literalExpectation("[", false), - "]", - peg$literalExpectation("]", false), - "{", - peg$literalExpectation("{", false), - "}", - peg$literalExpectation("}", false), - function () { return "*"; }, - function () { return "/"; }, - function () { return "="; }, - function () { return "("; }, - function () { return ")"; }, - function () { return ">"; }, - function () { return "<"; }, - function () { return ","; }, - function () { return ";"; }, - function () { return ":"; }, - function () { return "\""; }, - /^[!-']/, - peg$classExpectation([["!", "'"]], false, false), - /^[*-[]/, - peg$classExpectation([["*", "["]], false, false), - /^[\]-~]/, - peg$classExpectation([["]", "~"]], false, false), - function (contents) { - return contents; - }, - /^[#-[]/, - peg$classExpectation([["#", "["]], false, false), - /^[\0-\t]/, - peg$classExpectation([["\0", "\t"]], false, false), - /^[\x0B-\f]/, - peg$classExpectation([["\x0B", "\f"]], false, false), - /^[\x0E-\x7F]/, - peg$classExpectation([["\x0E", "\x7F"]], false, false), - function () { - options = options || { data: {} }; - options.data.uri = new URI(options.data.scheme, options.data.user, options.data.host, options.data.port); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - }, - function () { - options = options || { data: {} }; - options.data.uri = new URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - if (options.startRule === 'SIP_URI') { - options.data = options.data.uri; - } - }, - "sips", - peg$literalExpectation("sips", true), - "sip", - peg$literalExpectation("sip", true), - function (uri_scheme) { - options = options || { data: {} }; - options.data.scheme = uri_scheme; - }, - function () { - options = options || { data: {} }; - options.data.user = decodeURIComponent(text().slice(0, -1)); - }, - function () { - options = options || { data: {} }; - options.data.password = text(); - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - return options.data.host; - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'domain'; - return text(); - }, - /^[a-zA-Z0-9_\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "_", "-"], false, false), - /^[a-zA-Z0-9\-]/, - peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-"], false, false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - "::", - peg$literalExpectation("::", false), - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv6'; - return text(); - }, - function () { - options = options || { data: {} }; - options.data.host_type = 'IPv4'; - return text(); - }, - "25", - peg$literalExpectation("25", false), - /^[0-5]/, - peg$classExpectation([["0", "5"]], false, false), - "2", - peg$literalExpectation("2", false), - /^[0-4]/, - peg$classExpectation([["0", "4"]], false, false), - "1", - peg$literalExpectation("1", false), - /^[1-9]/, - peg$classExpectation([["1", "9"]], false, false), - function (port) { - options = options || { data: {} }; - port = parseInt(port.join('')); - options.data.port = port; - return port; - }, - "transport=", - peg$literalExpectation("transport=", true), - "udp", - peg$literalExpectation("udp", true), - "tcp", - peg$literalExpectation("tcp", true), - "sctp", - peg$literalExpectation("sctp", true), - "tls", - peg$literalExpectation("tls", true), - function (transport) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['transport'] = transport.toLowerCase(); - }, - "user=", - peg$literalExpectation("user=", true), - "phone", - peg$literalExpectation("phone", true), - "ip", - peg$literalExpectation("ip", true), - function (user) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['user'] = user.toLowerCase(); - }, - "method=", - peg$literalExpectation("method=", true), - function (method) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['method'] = method; - }, - "ttl=", - peg$literalExpectation("ttl=", true), - function (ttl) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['ttl'] = ttl; - }, - "maddr=", - peg$literalExpectation("maddr=", true), - function (maddr) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['maddr'] = maddr; - }, - "lr", - peg$literalExpectation("lr", true), - function () { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - options.data.uri_params['lr'] = undefined; - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.uri_params) - options.data.uri_params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.uri_params[param.toLowerCase()] = value; - }, - function (hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - options = options || { data: {} }; - if (!options.data.uri_headers) - options.data.uri_headers = {}; - if (!options.data.uri_headers[hname]) { - options.data.uri_headers[hname] = [hvalue]; - } - else { - options.data.uri_headers[hname].push(hvalue); - } - }, - function () { - options = options || { data: {} }; - // lots of tests fail if this isn't guarded... - if (options.startRule === 'Refer_To') { - options.data.uri = new URI(options.data.scheme, options.data.user, options.data.host, options.data.port, options.data.uri_params, options.data.uri_headers); - delete options.data.scheme; - delete options.data.user; - delete options.data.host; - delete options.data.host_type; - delete options.data.port; - delete options.data.uri_params; - } - }, - "//", - peg$literalExpectation("//", false), - function () { - options = options || { data: {} }; - options.data.scheme = text(); - }, - peg$literalExpectation("SIP", true), - function () { - options = options || { data: {} }; - options.data.sip_version = text(); - }, - "INVITE", - peg$literalExpectation("INVITE", false), - "ACK", - peg$literalExpectation("ACK", false), - "VXACH", - peg$literalExpectation("VXACH", false), - "OPTIONS", - peg$literalExpectation("OPTIONS", false), - "BYE", - peg$literalExpectation("BYE", false), - "CANCEL", - peg$literalExpectation("CANCEL", false), - "REGISTER", - peg$literalExpectation("REGISTER", false), - "SUBSCRIBE", - peg$literalExpectation("SUBSCRIBE", false), - "NOTIFY", - peg$literalExpectation("NOTIFY", false), - "REFER", - peg$literalExpectation("REFER", false), - "PUBLISH", - peg$literalExpectation("PUBLISH", false), - function () { - options = options || { data: {} }; - options.data.method = text(); - return options.data.method; - }, - function (status_code) { - options = options || { data: {} }; - options.data.status_code = parseInt(status_code.join('')); - }, - function () { - options = options || { data: {} }; - options.data.reason_phrase = text(); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function (displayName) { - displayName = text().trim(); - if (displayName[0] === '\"') { - displayName = displayName.substring(1, displayName.length - 1); - } - options = options || { data: {} }; - options.data.displayName = displayName; - }, - "q", - peg$literalExpectation("q", true), - function (q) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['q'] = q; - }, - "expires", - peg$literalExpectation("expires", true), - function (expires) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - options.data.params['expires'] = expires; - }, - function (delta_seconds) { - return parseInt(delta_seconds.join('')); - }, - "0", - peg$literalExpectation("0", false), - function () { - return parseFloat(text()); - }, - function (param, value) { - options = options || { data: {} }; - if (!options.data.params) - options.data.params = {}; - if (value === null) { - value = undefined; - } - else { - value = value[1]; - } - options.data.params[param.toLowerCase()] = value; - }, - "render", - peg$literalExpectation("render", true), - "session", - peg$literalExpectation("session", true), - "icon", - peg$literalExpectation("icon", true), - "alert", - peg$literalExpectation("alert", true), - function () { - options = options || { data: {} }; - if (options.startRule === 'Content_Disposition') { - options.data.type = text().toLowerCase(); - } - }, - "handling", - peg$literalExpectation("handling", true), - "optional", - peg$literalExpectation("optional", true), - "required", - peg$literalExpectation("required", true), - function (length) { - options = options || { data: {} }; - options.data = parseInt(length.join('')); - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "text", - peg$literalExpectation("text", true), - "image", - peg$literalExpectation("image", true), - "audio", - peg$literalExpectation("audio", true), - "video", - peg$literalExpectation("video", true), - "application", - peg$literalExpectation("application", true), - "message", - peg$literalExpectation("message", true), - "multipart", - peg$literalExpectation("multipart", true), - "x-", - peg$literalExpectation("x-", true), - function (cseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(cseq_value.join('')); - }, - function (expires) { options = options || { data: {} }; options.data = expires; }, - function (event_type) { - options = options || { data: {} }; - options.data.event = event_type.toLowerCase(); - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "tag", - peg$literalExpectation("tag", true), - function (tag) { options = options || { data: {} }; options.data.tag = tag; }, - function (forwards) { - options = options || { data: {} }; - options.data = parseInt(forwards.join('')); - }, - function (min_expires) { options = options || { data: {} }; options.data = min_expires; }, - function () { - options = options || { data: {} }; - options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - "digest", - peg$literalExpectation("Digest", true), - "realm", - peg$literalExpectation("realm", true), - function (realm) { options = options || { data: {} }; options.data.realm = realm; }, - "domain", - peg$literalExpectation("domain", true), - "nonce", - peg$literalExpectation("nonce", true), - function (nonce) { options = options || { data: {} }; options.data.nonce = nonce; }, - "opaque", - peg$literalExpectation("opaque", true), - function (opaque) { options = options || { data: {} }; options.data.opaque = opaque; }, - "stale", - peg$literalExpectation("stale", true), - "true", - peg$literalExpectation("true", true), - function () { options = options || { data: {} }; options.data.stale = true; }, - "false", - peg$literalExpectation("false", true), - function () { options = options || { data: {} }; options.data.stale = false; }, - "algorithm", - peg$literalExpectation("algorithm", true), - "md5", - peg$literalExpectation("MD5", true), - "md5-sess", - peg$literalExpectation("MD5-sess", true), - function (algorithm) { - options = options || { data: {} }; - options.data.algorithm = algorithm.toUpperCase(); - }, - "qop", - peg$literalExpectation("qop", true), - "auth-int", - peg$literalExpectation("auth-int", true), - "auth", - peg$literalExpectation("auth", true), - function (qop_value) { - options = options || { data: {} }; - options.data.qop || (options.data.qop = []); - options.data.qop.push(qop_value.toLowerCase()); - }, - function (rack_value) { - options = options || { data: {} }; - options.data.value = parseInt(rack_value.join('')); - }, - function () { - var idx, length; - options = options || { data: {} }; - length = options.data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (options.data.multi_header[idx].parsed === null) { - options.data = null; - break; - } - } - if (options.data !== null) { - options.data = options.data.multi_header; - } - else { - options.data = -1; - } - }, - function () { - var header; - options = options || { data: {} }; - if (!options.data.multi_header) - options.data.multi_header = []; - try { - header = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - delete options.data.uri; - delete options.data.displayName; - delete options.data.params; - } - catch (e) { - header = null; - } - options.data.multi_header.push({ 'position': peg$currPos, - 'offset': location().start.offset, - 'parsed': header - }); - }, - function () { - options = options || { data: {} }; - options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - }, - function () { - options = options || { data: {} }; - if (!(options.data.replaces_from_tag && options.data.replaces_to_tag)) { - options.data = -1; - } - }, - function () { - options = options || { data: {} }; - options.data = { - call_id: options.data - }; - }, - "from-tag", - peg$literalExpectation("from-tag", true), - function (from_tag) { - options = options || { data: {} }; - options.data.replaces_from_tag = from_tag; - }, - "to-tag", - peg$literalExpectation("to-tag", true), - function (to_tag) { - options = options || { data: {} }; - options.data.replaces_to_tag = to_tag; - }, - "early-only", - peg$literalExpectation("early-only", true), - function () { - options = options || { data: {} }; - options.data.early_only = true; - }, - function (head, r) { return r; }, - function (head, tail) { return list(head, tail); }, - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Require') { - options.data = value || []; - } - }, - function (rseq_value) { - options = options || { data: {} }; - options.data.value = parseInt(rseq_value.join('')); - }, - "active", - peg$literalExpectation("active", true), - "pending", - peg$literalExpectation("pending", true), - "terminated", - peg$literalExpectation("terminated", true), - function () { - options = options || { data: {} }; - options.data.state = text(); - }, - "reason", - peg$literalExpectation("reason", true), - function (reason) { - options = options || { data: {} }; - if (typeof reason !== 'undefined') - options.data.reason = reason; - }, - function (expires) { - options = options || { data: {} }; - if (typeof expires !== 'undefined') - options.data.expires = expires; - }, - "retry_after", - peg$literalExpectation("retry_after", true), - function (retry_after) { - options = options || { data: {} }; - if (typeof retry_after !== 'undefined') - options.data.retry_after = retry_after; - }, - "deactivated", - peg$literalExpectation("deactivated", true), - "probation", - peg$literalExpectation("probation", true), - "rejected", - peg$literalExpectation("rejected", true), - "timeout", - peg$literalExpectation("timeout", true), - "giveup", - peg$literalExpectation("giveup", true), - "noresource", - peg$literalExpectation("noresource", true), - "invariant", - peg$literalExpectation("invariant", true), - function (value) { - options = options || { data: {} }; - if (options.startRule === 'Supported') { - options.data = value || []; - } - }, - function () { - options = options || { data: {} }; - var tag = options.data.tag; - options.data = new NameAddrHeader(options.data.uri, options.data.displayName, options.data.params); - if (tag) { - options.data.setParam('tag', tag); - } - }, - "ttl", - peg$literalExpectation("ttl", true), - function (via_ttl_value) { - options = options || { data: {} }; - options.data.ttl = via_ttl_value; - }, - "maddr", - peg$literalExpectation("maddr", true), - function (via_maddr) { - options = options || { data: {} }; - options.data.maddr = via_maddr; - }, - "received", - peg$literalExpectation("received", true), - function (via_received) { - options = options || { data: {} }; - options.data.received = via_received; - }, - "branch", - peg$literalExpectation("branch", true), - function (via_branch) { - options = options || { data: {} }; - options.data.branch = via_branch; - }, - "rport", - peg$literalExpectation("rport", true), - function (response_port) { - options = options || { data: {} }; - if (typeof response_port !== 'undefined') - options.data.rport = response_port.join(''); - }, - function (via_protocol) { - options = options || { data: {} }; - options.data.protocol = via_protocol; - }, - peg$literalExpectation("UDP", true), - peg$literalExpectation("TCP", true), - peg$literalExpectation("TLS", true), - peg$literalExpectation("SCTP", true), - function (via_transport) { - options = options || { data: {} }; - options.data.transport = via_transport; - }, - function () { - options = options || { data: {} }; - options.data.host = text(); - }, - function (via_sent_by_port) { - options = options || { data: {} }; - options.data.port = parseInt(via_sent_by_port.join('')); - }, - function (ttl) { - return parseInt(ttl.join('')); - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.deltaSeconds = deltaSeconds; - } - }, - "refresher", - peg$literalExpectation("refresher", false), - "uas", - peg$literalExpectation("uas", false), - "uac", - peg$literalExpectation("uac", false), - function (endpoint) { - options = options || { data: {} }; - if (options.startRule === 'Session_Expires') { - options.data.refresher = endpoint; - } - }, - function (deltaSeconds) { - options = options || { data: {} }; - if (options.startRule === 'Min_SE') { - options.data = deltaSeconds; - } - }, - "stuns", - peg$literalExpectation("stuns", true), - "stun", - peg$literalExpectation("stun", true), - function (scheme) { - options = options || { data: {} }; - options.data.scheme = scheme; - }, - function (host) { - options = options || { data: {} }; - options.data.host = host; - }, - "?transport=", - peg$literalExpectation("?transport=", false), - "turns", - peg$literalExpectation("turns", true), - "turn", - peg$literalExpectation("turn", true), - function (transport) { - options = options || { data: {} }; - options.data.transport = transport; - }, - function () { - options = options || { data: {} }; - options.data = text(); - }, - "Referred-By", - peg$literalExpectation("Referred-By", false), - "b", - peg$literalExpectation("b", false), - "cid", - peg$literalExpectation("cid", false) - ]; - const peg$bytecode = [ - peg$decode("2 \"\"6 7!"), - peg$decode("4\"\"\"5!7#"), - peg$decode("4$\"\"5!7%"), - peg$decode("4&\"\"5!7'"), - peg$decode(";'.# &;("), - peg$decode("4(\"\"5!7)"), - peg$decode("4*\"\"5!7+"), - peg$decode("2,\"\"6,7-"), - peg$decode("2.\"\"6.7/"), - peg$decode("40\"\"5!71"), - peg$decode("22\"\"6273.\x89 &24\"\"6475.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode(";).# &;,"), - peg$decode("2F\"\"6F7G.} &2H\"\"6H7I.q &2J\"\"6J7K.e &2L\"\"6L7M.Y &2N\"\"6N7O.M &2P\"\"6P7Q.A &2R\"\"6R7S.5 &2T\"\"6T7U.) &2V\"\"6V7W"), - peg$decode("%%2X\"\"6X7Y/5#;#/,$;#/#$+#)(#'#(\"'#&'#/\"!&,)"), - peg$decode("%%$;$0#*;$&/,#; /#$+\")(\"'#&'#.\" &\"/=#$;$/�#*;$&&&#/'$8\":Z\" )(\"'#&'#"), - peg$decode(";..\" &\""), - peg$decode("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"), - peg$decode("%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+\")(\"'#&'#0=*%$;.0#*;.&/,#;2/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/\"!&,)"), - peg$decode("4\\\"\"5!7].# &;3"), - peg$decode("4^\"\"5!7_"), - peg$decode("4`\"\"5!7a"), - peg$decode(";!.) &4b\"\"5!7c"), - peg$decode("%$;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x9E#0\x9B*;).\x95 &2F\"\"6F7G.\x89 &2J\"\"6J7K.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("%$;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O/\x92#0\x8F*;).\x89 &2F\"\"6F7G.} &2L\"\"6L7M.q &2X\"\"6X7Y.e &2P\"\"6P7Q.Y &2H\"\"6H7I.M &2@\"\"6@7A.A &2d\"\"6d7e.5 &2R\"\"6R7S.) &2N\"\"6N7O&&&#/\"!&,)"), - peg$decode("2T\"\"6T7U.\xE3 &2V\"\"6V7W.\xD7 &2f\"\"6f7g.\xCB &2h\"\"6h7i.\xBF &2:\"\"6:7;.\xB3 &2D\"\"6D7E.\xA7 &22\"\"6273.\x9B &28\"\"6879.\x8F &2j\"\"6j7k.\x83 &;&.} &24\"\"6475.q &2l\"\"6l7m.e &2n\"\"6n7o.Y &26\"\"6677.M &2>\"\"6>7?.A &2p\"\"6p7q.5 &2r\"\"6r7s.) &;'.# &;("), - peg$decode("%$;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s/\u0134#0\u0131*;).\u012B &2F\"\"6F7G.\u011F &2J\"\"6J7K.\u0113 &2L\"\"6L7M.\u0107 &2X\"\"6X7Y.\xFB &2P\"\"6P7Q.\xEF &2H\"\"6H7I.\xE3 &2@\"\"6@7A.\xD7 &2d\"\"6d7e.\xCB &2R\"\"6R7S.\xBF &2N\"\"6N7O.\xB3 &2T\"\"6T7U.\xA7 &2V\"\"6V7W.\x9B &2f\"\"6f7g.\x8F &2h\"\"6h7i.\x83 &28\"\"6879.w &2j\"\"6j7k.k &;&.e &24\"\"6475.Y &2l\"\"6l7m.M &2n\"\"6n7o.A &26\"\"6677.5 &2p\"\"6p7q.) &2r\"\"6r7s&&&#/\"!&,)"), - peg$decode("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"), - peg$decode("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"), - peg$decode("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"), - peg$decode("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"), - peg$decode("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"), - peg$decode("%2h\"\"6h7i/0#;//'$8\":y\" )(\"'#&'#"), - peg$decode("%;//6#2f\"\"6f7g/'$8\":z\" )(\"'#&'#"), - peg$decode("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"), - peg$decode("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"), - peg$decode("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"), - peg$decode("%;//0#;&/'$8\":~\" )(\"'#&'#"), - peg$decode("%;&/0#;//'$8\":~\" )(\"'#&'#"), - peg$decode("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"), - peg$decode("4\x7F\"\"5!7\x80.A &4\x81\"\"5!7\x82.5 &4\x83\"\"5!7\x84.) &;3.# &;."), - peg$decode("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"), - peg$decode("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:\x85$!!)($'#(#'#(\"'#&'#"), - peg$decode(";..G &2L\"\"6L7M.; &4\x86\"\"5!7\x87./ &4\x83\"\"5!7\x84.# &;3"), - peg$decode("%2j\"\"6j7k/J#4\x88\"\"5!7\x89.5 &4\x8A\"\"5!7\x8B.) &4\x8C\"\"5!7\x8D/#$+\")(\"'#&'#"), - peg$decode("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:\x8E$ )($'#(#'#(\"'#&'#"), - peg$decode("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:\x8F& )(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x90\"\"5$7\x91.) &3\x92\"\"5#7\x93/' 8!:\x94!! )"), - peg$decode("%;P/]#%28\"\"6879/,#;R/#$+\")(\"'#&'#.\" &\"/6$2:\"\"6:7;/'$8#:\x95# )(#'#(\"'#&'#"), - peg$decode("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"), - peg$decode("2<\"\"6<7=.q &2>\"\"6>7?.e &2@\"\"6@7A.Y &2B\"\"6B7C.M &2D\"\"6D7E.A &22\"\"6273.5 &26\"\"6677.) &24\"\"6475"), - peg$decode("%$;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E0e*;+._ &;-.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E&/& 8!:\x96! )"), - peg$decode("%;T/J#%28\"\"6879/,#;^/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\x97! )"), - peg$decode("%$%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#0<*%;V/2#2J\"\"6J7K/#$+\")(\"'#&'#&/D#;W/;$2J\"\"6J7K.\" &\"/'$8#:\x98# )(#'#(\"'#&'#"), - peg$decode("$4\x99\"\"5!7\x9A/,#0)*4\x99\"\"5!7\x9A&&&#"), - peg$decode("%4$\"\"5!7%/?#$4\x9B\"\"5!7\x9C0)*4\x9B\"\"5!7\x9C&/#$+\")(\"'#&'#"), - peg$decode("%2l\"\"6l7m/?#;Y/6$2n\"\"6n7o/'$8#:\x9D# )(#'#(\"'#&'#"), - peg$decode("%%;Z/\xB3#28\"\"6879/\xA4$;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0790 &%2\x9E\"\"6\x9E7\x9F/\xA4#;Z/\x9B$28\"\"6879/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u06F9 &%2\x9E\"\"6\x9E7\x9F/\x8C#;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u067A &%2\x9E\"\"6\x9E7\x9F/t#;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0613 &%2\x9E\"\"6\x9E7\x9F/\\#;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+&)(&'#(%'#($'#(#'#(\"'#&'#.\u05C4 &%2\x9E\"\"6\x9E7\x9F/D#;Z/;$28\"\"6879/,$;[/#$+$)($'#(#'#(\"'#&'#.\u058D &%2\x9E\"\"6\x9E7\x9F/,#;[/#$+\")(\"'#&'#.\u056E &%2\x9E\"\"6\x9E7\x9F/,#;Z/#$+\")(\"'#&'#.\u054F &%;Z/\x9B#2\x9E\"\"6\x9E7\x9F/\x8C$;Z/\x83$28\"\"6879/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u04C7 &%;Z/\xAA#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x83$2\x9E\"\"6\x9E7\x9F/t$;Z/k$28\"\"6879/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0430 &%;Z/\xB9#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x92$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/k$2\x9E\"\"6\x9E7\x9F/\\$;Z/S$28\"\"6879/D$;Z/;$28\"\"6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u038A &%;Z/\xC8#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA1$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/z$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/S$2\x9E\"\"6\x9E7\x9F/D$;Z/;$28\"\"6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u02D5 &%;Z/\xD7#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;[/#$+')(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0211 &%;Z/\xFE#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xD7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xB0$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x89$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/b$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/;$2\x9E\"\"6\x9E7\x9F/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#.\u0126 &%;Z/\u011C#%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xF5$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xCE$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\xA7$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/\x80$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/Y$%28\"\"6879/,#;Z/#$+\")(\"'#&'#.\" &\"/2$2\x9E\"\"6\x9E7\x9F/#$+()(('#(''#(&'#(%'#($'#(#'#(\"'#&'#/& 8!:\xA0! )"), - peg$decode("%;#/M#;#.\" &\"/?$;#.\" &\"/1$;#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"), - peg$decode("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':\xA1' )(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%2\xA2\"\"6\xA27\xA3/2#4\xA4\"\"5!7\xA5/#$+\")(\"'#&'#.\x98 &%2\xA6\"\"6\xA67\xA7/;#4\xA8\"\"5!7\xA9/,$;!/#$+#)(#'#(\"'#&'#.j &%2\xAA\"\"6\xAA7\xAB/5#;!/,$;!/#$+#)(#'#(\"'#&'#.B &%4\xAC\"\"5!7\xAD/,#;!/#$+\")(\"'#&'#.# &;!"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\xAE!! )"), - peg$decode("$%22\"\"6273/,#;`/#$+\")(\"'#&'#0<*%22\"\"6273/,#;`/#$+\")(\"'#&'#&"), - peg$decode(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"), - peg$decode("%3\xAF\"\"5*7\xB0/a#3\xB1\"\"5#7\xB2.G &3\xB3\"\"5#7\xB4.; &3\xB5\"\"5$7\xB6./ &3\xB7\"\"5#7\xB8.# &;6/($8\":\xB9\"! )(\"'#&'#"), - peg$decode("%3\xBA\"\"5%7\xBB/I#3\xBC\"\"5%7\xBD./ &3\xBE\"\"5\"7\xBF.# &;6/($8\":\xC0\"! )(\"'#&'#"), - peg$decode("%3\xC1\"\"5'7\xC2/1#;\x90/($8\":\xC3\"! )(\"'#&'#"), - peg$decode("%3\xC4\"\"5$7\xC5/1#;\xF0/($8\":\xC6\"! )(\"'#&'#"), - peg$decode("%3\xC7\"\"5&7\xC8/1#;T/($8\":\xC9\"! )(\"'#&'#"), - peg$decode("%3\xCA\"\"5\"7\xCB/N#%2>\"\"6>7?/,#;6/#$+\")(\"'#&'#.\" &\"/'$8\":\xCC\" )(\"'#&'#"), - peg$decode("%;h/P#%2>\"\"6>7?/,#;i/#$+\")(\"'#&'#.\" &\"/)$8\":\xCD\"\"! )(\"'#&'#"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode("%$;j/�#*;j&&&#/\"!&,)"), - peg$decode(";k.) &;+.# &;-"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &28\"\"6879.A &2<\"\"6<7=.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode("%26\"\"6677/n#;m/e$$%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#0<*%2<\"\"6<7=/,#;m/#$+\")(\"'#&'#&/#$+#)(#'#(\"'#&'#"), - peg$decode("%;n/A#2>\"\"6>7?/2$;o/)$8#:\xCE#\"\" )(#'#(\"'#&'#"), - peg$decode("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"), - peg$decode("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"), - peg$decode("2l\"\"6l7m.e &2n\"\"6n7o.Y &24\"\"6475.M &26\"\"6677.A &28\"\"6879.5 &2@\"\"6@7A.) &2B\"\"6B7C"), - peg$decode(";\x91.# &;r"), - peg$decode("%;\x90/G#;'/>$;s/5$;'/,$;\x84/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode(";M.# &;t"), - peg$decode("%;\x7F/E#28\"\"6879/6$;u.# &;x/'$8#:\xCF# )(#'#(\"'#&'#"), - peg$decode("%;v.# &;w/J#%26\"\"6677/,#;\x83/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%2\xD0\"\"6\xD07\xD1/:#;\x80/1$;w.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%24\"\"6475/,#;{/#$+\")(\"'#&'#"), - peg$decode("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"), - peg$decode(";*.) &;+.# &;-"), - peg$decode(";+.\x8F &;-.\x89 &22\"\"6273.} &26\"\"6677.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%;|/e#$%24\"\"6475/,#;|/#$+\")(\"'#&'#0<*%24\"\"6475/,#;|/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%$;~0#*;~&/e#$%22\"\"6273/,#;}/#$+\")(\"'#&'#0<*%22\"\"6273/,#;}/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("$;~0#*;~&"), - peg$decode(";+.w &;-.q &28\"\"6879.e &2:\"\"6:7;.Y &2<\"\"6<7=.M &2>\"\"6>7?.A &2@\"\"6@7A.5 &2B\"\"6B7C.) &2D\"\"6D7E"), - peg$decode("%%;\"/\x87#$;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K0M*;\".G &;!.A &2@\"\"6@7A.5 &2F\"\"6F7G.) &2J\"\"6J7K&/#$+\")(\"'#&'#/& 8!:\xD2! )"), - peg$decode(";\x81.# &;\x82"), - peg$decode("%%;O/2#2:\"\"6:7;/#$+\")(\"'#&'#.\" &\"/,#;S/#$+\")(\"'#&'#.\" &\""), - peg$decode("$;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A/\x8C#0\x89*;+.\x83 &;-.} &2B\"\"6B7C.q &2D\"\"6D7E.e &22\"\"6273.Y &28\"\"6879.M &2:\"\"6:7;.A &2<\"\"6<7=.5 &2>\"\"6>7?.) &2@\"\"6@7A&&&#"), - peg$decode("$;y0#*;y&"), - peg$decode("%3\x92\"\"5#7\xD3/q#24\"\"6475/b$$;!/�#*;!&&&#/L$2J\"\"6J7K/=$$;!/�#*;!&&&#/'$8%:\xD4% )(%'#($'#(#'#(\"'#&'#"), - peg$decode("2\xD5\"\"6\xD57\xD6"), - peg$decode("2\xD7\"\"6\xD77\xD8"), - peg$decode("2\xD9\"\"6\xD97\xDA"), - peg$decode("2\xDB\"\"6\xDB7\xDC"), - peg$decode("2\xDD\"\"6\xDD7\xDE"), - peg$decode("2\xDF\"\"6\xDF7\xE0"), - peg$decode("2\xE1\"\"6\xE17\xE2"), - peg$decode("2\xE3\"\"6\xE37\xE4"), - peg$decode("2\xE5\"\"6\xE57\xE6"), - peg$decode("2\xE7\"\"6\xE77\xE8"), - peg$decode("2\xE9\"\"6\xE97\xEA"), - peg$decode("%;\x85.Y &;\x86.S &;\x88.M &;\x89.G &;\x8A.A &;\x8B.; &;\x8C.5 &;\x8F./ &;\x8D.) &;\x8E.# &;6/& 8!:\xEB! )"), - peg$decode("%;\x84/G#;'/>$;\x92/5$;'/,$;\x94/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;\x93/' 8!:\xEC!! )"), - peg$decode("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"), - peg$decode("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:\xED! )"), - peg$decode("%;\xB6/Y#$%;A/,#;\xB6/#$+\")(\"'#&'#06*%;A/,#;\xB6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"), - peg$decode("%;9/N#%2:\"\"6:7;/,#;9/#$+\")(\"'#&'#.\" &\"/'$8\":\xEE\" )(\"'#&'#"), - peg$decode("%;:.c &%;\x98/Y#$%;A/,#;\x98/#$+\")(\"'#&'#06*%;A/,#;\x98/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:\xEF! )"), - peg$decode("%;L.# &;\x99/]#$%;B/,#;\x9B/#$+\")(\"'#&'#06*%;B/,#;\x9B/#$+\")(\"'#&'#&/'$8\":\xF0\" )(\"'#&'#"), - peg$decode("%;\x9A.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:\xF1!! )"), - peg$decode(";\x9C.) &;\x9D.# &;\xA0"), - peg$decode("%3\xF2\"\"5!7\xF3/:#;$;\xCF/5$;./,$;\x90/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%$;!/�#*;!&&&#/' 8!:\u014B!! )"), - peg$decode("%;\xD1/]#$%;A/,#;\xD1/#$+\")(\"'#&'#06*%;A/,#;\xD1/#$+\")(\"'#&'#&/'$8\":\u014C\" )(\"'#&'#"), - peg$decode("%;\x99/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014D\" )(\"'#&'#"), - peg$decode("%;L.O &;\x99.I &%;@.\" &\"/:#;t/1$;?.\" &\"/#$+#)(#'#(\"'#&'#/]#$%;B/,#;\xA0/#$+\")(\"'#&'#06*%;B/,#;\xA0/#$+\")(\"'#&'#&/'$8\":\u014E\" )(\"'#&'#"), - peg$decode("%;\xD4/]#$%;B/,#;\xD5/#$+\")(\"'#&'#06*%;B/,#;\xD5/#$+\")(\"'#&'#&/'$8\":\u014F\" )(\"'#&'#"), - peg$decode("%;\x96/& 8!:\u0150! )"), - peg$decode("%3\u0151\"\"5(7\u0152/:#;$;6/5$;;/,$;\xEC/#$+%)(%'#($'#(#'#(\"'#&'#"), - peg$decode("%3\x92\"\"5#7\xD3.# &;6/' 8!:\u018B!! )"), - peg$decode("%3\xB1\"\"5#7\u018C.G &3\xB3\"\"5#7\u018D.; &3\xB7\"\"5#7\u018E./ &3\xB5\"\"5$7\u018F.# &;6/' 8!:\u0190!! )"), - peg$decode("%;\xEE/D#%;C/,#;\xEF/#$+\")(\"'#&'#.\" &\"/#$+\")(\"'#&'#"), - peg$decode("%;U.) &;\\.# &;X/& 8!:\u0191! )"), - peg$decode("%%;!.\" &\"/[#;!.\" &\"/M$;!.\" &\"/?$;!.\" &\"/1$;!.\" &\"/#$+%)(%'#($'#(#'#(\"'#&'#/' 8!:\u0192!! )"), - peg$decode("%%;!/?#;!.\" &\"/1$;!.\" &\"/#$+#)(#'#(\"'#&'#/' 8!:\u0193!! )"), - peg$decode(";\xBE"), - peg$decode("%;\x9E/^#$%;B/,#;\xF3/#$+\")(\"'#&'#06*%;B/,#;\xF3/#$+\")(\"'#&'#&/($8\":\u0194\"!!)(\"'#&'#"), - peg$decode(";\xF4.# &;\xA0"), - peg$decode("%2\u0195\"\"6\u01957\u0196/L#;\"\"6>7?"), - peg$decode("%;\u0100/b#28\"\"6879/S$;\xFB/J$%2\u01A3\"\"6\u01A37\u01A4/,#;\xEC/#$+\")(\"'#&'#.\" &\"/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%3\u01A5\"\"5%7\u01A6.) &3\u01A7\"\"5$7\u01A8/' 8!:\u01A1!! )"), - peg$decode("%3\xB1\"\"5#7\xB2.6 &3\xB3\"\"5#7\xB4.* &$;+0#*;+&/' 8!:\u01A9!! )"), - peg$decode("%;\u0104/\x87#2F\"\"6F7G/x$;\u0103/o$2F\"\"6F7G/`$;\u0103/W$2F\"\"6F7G/H$;\u0103/?$2F\"\"6F7G/0$;\u0105/'$8):\u01AA) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"), - peg$decode("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"), - peg$decode("%;\u0103/,#;\u0103/#$+\")(\"'#&'#"), - peg$decode("%;\u0103/5#;\u0103/,$;\u0103/#$+#)(#'#(\"'#&'#"), - peg$decode("%;q/T#$;m0#*;m&/D$%; /,#;\xF8/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"), - peg$decode("%2\u01AB\"\"6\u01AB7\u01AC.) &2\u01AD\"\"6\u01AD7\u01AE/w#;0/n$;\u0108/e$$%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#0<*%;B/2#;\u0109.# &;\xA0/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"), - peg$decode(";\x99.# &;L"), - peg$decode("%2\u01AF\"\"6\u01AF7\u01B0/5#; peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - peg$maxFailExpected.push(expected1); - } - function peg$buildSimpleError(message, location1) { - return new SyntaxError(message, [], "", location1); - } - function peg$buildStructuredError(expected1, found, location1) { - return new SyntaxError(SyntaxError.buildMessage(expected1, found), expected1, found, location1); - } - function peg$decode(s) { - return s.split("").map((ch) => ch.charCodeAt(0) - 32); - } - function peg$parseRule(index) { - const bc = peg$bytecode[index]; - let ip = 0; - const ips = []; - let end = bc.length; - const ends = []; - const stack = []; - let params; - while (true) { - while (ip < end) { - switch (bc[ip]) { - case 0: - stack.push(peg$consts[bc[ip + 1]]); - ip += 2; - break; - case 1: - stack.push(undefined); - ip++; - break; - case 2: - stack.push(null); - ip++; - break; - case 3: - stack.push(peg$FAILED); - ip++; - break; - case 4: - stack.push([]); - ip++; - break; - case 5: - stack.push(peg$currPos); - ip++; - break; - case 6: - stack.pop(); - ip++; - break; - case 7: - peg$currPos = stack.pop(); - ip++; - break; - case 8: - stack.length -= bc[ip + 1]; - ip += 2; - break; - case 9: - stack.splice(-2, 1); - ip++; - break; - case 10: - stack[stack.length - 2].push(stack.pop()); - ip++; - break; - case 11: - stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); - ip += 2; - break; - case 12: - stack.push(input.substring(stack.pop(), peg$currPos)); - ip++; - break; - case 13: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1]) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 14: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] === peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 15: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (stack[stack.length - 1] !== peg$FAILED) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 16: - if (stack[stack.length - 1] !== peg$FAILED) { - ends.push(end); - ips.push(ip); - end = ip + 2 + bc[ip + 1]; - ip += 2; - } - else { - ip += 2 + bc[ip + 1]; - } - break; - case 17: - ends.push(end); - ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); - if (input.length > peg$currPos) { - end = ip + 3 + bc[ip + 1]; - ip += 3; - } - else { - end = ip + 3 + bc[ip + 1] + bc[ip + 2]; - ip += 3 + bc[ip + 1]; - } - break; - case 18: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 19: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 20: - ends.push(end); - ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); - if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { - end = ip + 4 + bc[ip + 2]; - ip += 4; - } - else { - end = ip + 4 + bc[ip + 2] + bc[ip + 3]; - ip += 4 + bc[ip + 2]; - } - break; - case 21: - stack.push(input.substr(peg$currPos, bc[ip + 1])); - peg$currPos += bc[ip + 1]; - ip += 2; - break; - case 22: - stack.push(peg$consts[bc[ip + 1]]); - peg$currPos += peg$consts[bc[ip + 1]].length; - ip += 2; - break; - case 23: - stack.push(peg$FAILED); - if (peg$silentFails === 0) { - peg$fail(peg$consts[bc[ip + 1]]); - } - ip += 2; - break; - case 24: - peg$savedPos = stack[stack.length - 1 - bc[ip + 1]]; - ip += 2; - break; - case 25: - peg$savedPos = peg$currPos; - ip++; - break; - case 26: - params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]) - .map(function (p) { return stack[stack.length - 1 - p]; }); - stack.splice(stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params)); - ip += 4 + bc[ip + 3]; - break; - case 27: - stack.push(peg$parseRule(bc[ip + 1])); - ip += 2; - break; - case 28: - peg$silentFails++; - ip++; - break; - case 29: - peg$silentFails--; - ip++; - break; - default: - throw new Error("Invalid opcode: " + bc[ip] + "."); - } - } - if (ends.length > 0) { - end = ends.pop(); - ip = ips.pop(); - } - else { - break; - } - } - return stack[0]; - } - options.data = {}; // Object to which header attributes will be assigned during parsing - function list(head, tail) { - return [head].concat(tail); - } - peg$result = peg$parseRule(peg$startRuleIndex); - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } - else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); - } -} -export const parse = peg$parse; diff --git a/lib/grammar/uri.d.ts b/lib/grammar/uri.d.ts deleted file mode 100644 index 21d1f58d8..000000000 --- a/lib/grammar/uri.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Parameters } from "./parameters"; -/** - * URI. - * @public - */ -export declare class URI extends Parameters { - private headers; - private normal; - private raw; - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - constructor(scheme: string, user: string, host: string, port?: number, parameters?: any, headers?: any); - get scheme(): string; - set scheme(value: string); - get user(): string | undefined; - set user(value: string | undefined); - get host(): string; - set host(value: string); - get aor(): string; - get port(): number | undefined; - set port(value: number | undefined); - setHeader(name: string, value: any): void; - getHeader(name: string): string | undefined; - hasHeader(name: string): boolean; - deleteHeader(header: string): any; - clearHeaders(): void; - clone(): URI; - toRaw(): string; - toString(): string; - private get _normal(); - private get _raw(); - private _toString; - private escapeUser; - private headerize; -} -//# sourceMappingURL=uri.d.ts.map \ No newline at end of file diff --git a/lib/grammar/uri.d.ts.map b/lib/grammar/uri.d.ts.map deleted file mode 100644 index 9137ebf67..000000000 --- a/lib/grammar/uri.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uri.d.ts","sourceRoot":"","sources":["../../src/grammar/uri.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAS1C;;;GAGG;AACH,qBAAa,GAAI,SAAQ,UAAU;IACjC,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,GAAG,CAAY;IAEvB;;;;;;;;OAQG;gBAED,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,MAAM,EACb,UAAU,CAAC,EAAE,GAAG,EAChB,OAAO,CAAC,EAAE,GAAG;IAmCf,IAAI,MAAM,IAAI,MAAM,CAA+B;IACnD,IAAI,MAAM,CAAC,KAAK,EAAE,MAAM,EAGvB;IAED,IAAI,IAAI,IAAI,MAAM,GAAG,SAAS,CAA6B;IAC3D,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IAAI,IAAI,IAAI,MAAM,CAA6B;IAC/C,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,EAGrB;IAED,IAAI,GAAG,IAAI,MAAM,CAAsD;IAEvE,IAAI,IAAI,IAAI,MAAM,GAAG,SAAS,CAA6B;IAC3D,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAEM,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAIzC,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAM3C,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAKhC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;IAWjC,YAAY,IAAI,IAAI;IAIpB,KAAK,IAAI,GAAG;IAUZ,KAAK,IAAI,MAAM;IAIf,QAAQ,IAAI,MAAM;IAIzB,OAAO,KAAK,OAAO,GAAqC;IAExD,OAAO,KAAK,IAAI,GAAkC;IAElD,OAAO,CAAC,SAAS;IAkDjB,OAAO,CAAC,UAAU;IAwBlB,OAAO,CAAC,SAAS;CAwBlB"} \ No newline at end of file diff --git a/lib/grammar/uri.js b/lib/grammar/uri.js deleted file mode 100644 index 3b3e91526..000000000 --- a/lib/grammar/uri.js +++ /dev/null @@ -1,190 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { Parameters } from "./parameters"; -/** - * URI. - * @public - */ -export class URI extends Parameters { - /** - * Constructor - * @param scheme - - * @param user - - * @param host - - * @param port - - * @param parameters - - * @param headers - - */ - constructor(scheme, user, host, port, parameters, headers) { - super(parameters); - this.headers = {}; - // Checks - if (!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - // Initialize parameters - scheme = scheme || "sip"; - for (const header in headers) { - // eslint-disable-next-line no-prototype-builtins - if (headers.hasOwnProperty(header)) { - this.setHeader(header, headers[header]); - } - } - // Raw URI - this.raw = { - scheme, - user, - host, - port - }; - // Normalized URI - this.normal = { - scheme: scheme.toLowerCase(), - user, - host: host.toLowerCase(), - port - }; - } - get scheme() { return this.normal.scheme; } - set scheme(value) { - this.raw.scheme = value; - this.normal.scheme = value.toLowerCase(); - } - get user() { return this.normal.user; } - set user(value) { - this.normal.user = this.raw.user = value; - } - get host() { return this.normal.host; } - set host(value) { - this.raw.host = value; - this.normal.host = value.toLowerCase(); - } - get aor() { return this.normal.user + "@" + this.normal.host; } - get port() { return this.normal.port; } - set port(value) { - this.normal.port = this.raw.port = value === 0 ? value : value; - } - setHeader(name, value) { - this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; - } - getHeader(name) { - if (name) { - return this.headers[this.headerize(name)]; - } - } - hasHeader(name) { - // eslint-disable-next-line no-prototype-builtins - return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); - } - deleteHeader(header) { - header = this.headerize(header); - // eslint-disable-next-line no-prototype-builtins - if (this.headers.hasOwnProperty(header)) { - const value = this.headers[header]; - delete this.headers[header]; - return value; - } - } - clearHeaders() { - this.headers = {}; - } - clone() { - return new URI(this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); - } - toRaw() { - return this._toString(this._raw); - } - toString() { - return this._toString(this._normal); - } - get _normal() { return this.normal; } - get _raw() { return this.raw; } - _toString(uri) { - let uriString = uri.scheme + ":"; - // add slashes if it's not a sip(s) URI - if (!uri.scheme.toLowerCase().match("^sips?$")) { - uriString += "//"; - } - if (uri.user) { - uriString += this.escapeUser(uri.user) + "@"; - } - uriString += uri.host; - if (uri.port || uri.port === 0) { - uriString += ":" + uri.port; - } - for (const parameter in this.parameters) { - // eslint-disable-next-line no-prototype-builtins - if (this.parameters.hasOwnProperty(parameter)) { - uriString += ";" + parameter; - if (this.parameters[parameter] !== null) { - uriString += "=" + this.parameters[parameter]; - } - } - } - const headers = []; - for (const header in this.headers) { - // eslint-disable-next-line no-prototype-builtins - if (this.headers.hasOwnProperty(header)) { - for (const idx in this.headers[header]) { - // eslint-disable-next-line no-prototype-builtins - if (this.headers[header].hasOwnProperty(idx)) { - headers.push(header + "=" + this.headers[header][idx]); - } - } - } - } - if (headers.length > 0) { - uriString += "?" + headers.join("&"); - } - return uriString; - } - /* - * Hex-escape a SIP URI user. - * @private - * @param {String} user - */ - escapeUser(user) { - let decodedUser; - // FIXME: This is called by toString above which should never throw, but - // decodeURIComponent can throw and I've seen one case in production where - // it did throw resulting in a cascading failure. This class should be - // fixed so that decodeURIComponent is not called at this point (in toString). - // The user should be decoded when the URI is constructor or some other - // place where we can catch the error before the URI is created or somesuch. - // eslint-disable-next-line no-useless-catch - try { - decodedUser = decodeURIComponent(user); - } - catch (error) { - throw error; - } - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodedUser) - .replace(/%3A/ig, ":") - .replace(/%2B/ig, "+") - .replace(/%3F/ig, "?") - .replace(/%2F/ig, "/"); - } - headerize(str) { - const exceptions = { - "Call-Id": "Call-ID", - "Cseq": "CSeq", - "Min-Se": "Min-SE", - "Rack": "RAck", - "Rseq": "RSeq", - "Www-Authenticate": "WWW-Authenticate", - }; - const name = str.toLowerCase().replace(/_/g, "-").split("-"); - const parts = name.length; - let hname = ""; - for (let part = 0; part < parts; part++) { - if (part !== 0) { - hname += "-"; - } - hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; - } -} diff --git a/lib/index.d.ts b/lib/index.d.ts deleted file mode 100644 index 22e8debd0..000000000 --- a/lib/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare const version = "0.17.1"; -declare const name = "sip.js"; -export { name, version }; -export * from "./api"; -export * from "./grammar"; -import * as Core from "./core"; -export { Core }; -import * as Web from "./platform/web"; -export { Web }; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/index.d.ts.map b/lib/index.d.ts.map deleted file mode 100644 index 3da2129e6..000000000 --- a/lib/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,QAAA,MAAM,OAAO,WAAkB,CAAC;AAChC,QAAA,MAAM,IAAI,WAAW,CAAC;AACtB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAGzB,cAAc,OAAO,CAAC;AAGtB,cAAc,WAAW,CAAC;AAG1B,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,EAAE,IAAI,EAAE,CAAC;AAGhB,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index 3b7fa4729..000000000 --- a/lib/index.js +++ /dev/null @@ -1,15 +0,0 @@ -// Helpful name and version exports -import { LIBRARY_VERSION } from "./version"; -const version = LIBRARY_VERSION; -const name = "sip.js"; -export { name, version }; -// Export api -export * from "./api"; -// Export grammar -export * from "./grammar"; -// Export namespaced core -import * as Core from "./core"; -export { Core }; -// Export namespaced web -import * as Web from "./platform/web"; -export { Web }; diff --git a/lib/platform/web/index.d.ts b/lib/platform/web/index.d.ts deleted file mode 100644 index 9f2af6e9a..000000000 --- a/lib/platform/web/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./modifiers"; -export * from "./session-description-handler"; -export * from "./simple-user"; -export * from "./transport"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/index.d.ts.map b/lib/platform/web/index.d.ts.map deleted file mode 100644 index fade71b09..000000000 --- a/lib/platform/web/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/platform/web/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,+BAA+B,CAAC;AAC9C,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/index.js b/lib/platform/web/index.js deleted file mode 100644 index 627e6198d..000000000 --- a/lib/platform/web/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./modifiers"; -export * from "./session-description-handler"; -export * from "./simple-user"; -export * from "./transport"; diff --git a/lib/platform/web/modifiers/index.d.ts b/lib/platform/web/modifiers/index.d.ts deleted file mode 100644 index 4816d5405..000000000 --- a/lib/platform/web/modifiers/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * SessionDescriptionHandlerModifer functions for web browsers. - * @packageDocumentation - */ -export * from "./modifiers"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/modifiers/index.d.ts.map b/lib/platform/web/modifiers/index.d.ts.map deleted file mode 100644 index afac4a503..000000000 --- a/lib/platform/web/modifiers/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/modifiers/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/modifiers/index.js b/lib/platform/web/modifiers/index.js deleted file mode 100644 index 5e3c3bade..000000000 --- a/lib/platform/web/modifiers/index.js +++ /dev/null @@ -1,5 +0,0 @@ -/** - * SessionDescriptionHandlerModifer functions for web browsers. - * @packageDocumentation - */ -export * from "./modifiers"; diff --git a/lib/platform/web/modifiers/modifiers.d.ts b/lib/platform/web/modifiers/modifiers.d.ts deleted file mode 100644 index 4a18e9ffb..000000000 --- a/lib/platform/web/modifiers/modifiers.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { SessionDescriptionHandlerModifier } from "../../../api"; -/** - * Modifier. - * @public - */ -export declare function stripTcpCandidates(description: RTCSessionDescriptionInit): Promise; -/** - * Modifier. - * @public - */ -export declare function stripTelephoneEvent(description: RTCSessionDescriptionInit): Promise; -/** - * Modifier. - * @public - */ -export declare function cleanJitsiSdpImageattr(description: RTCSessionDescriptionInit): Promise; -/** - * Modifier. - * @public - */ -export declare function stripG722(description: RTCSessionDescriptionInit): Promise; -/** - * Modifier. - * @public - */ -export declare function stripRtpPayload(payload: string): SessionDescriptionHandlerModifier; -/** - * Modifier. - * @public - */ -export declare function stripVideo(description: RTCSessionDescriptionInit): Promise; -/** - * Modifier. - * @public - */ -export declare function addMidLines(description: RTCSessionDescriptionInit): Promise; -/** - * The modifier that should be used when the session would like to place the call on hold. - * @param description - The description that will be modified. - */ -export declare function holdModifier(description: RTCSessionDescriptionInit): Promise; -//# sourceMappingURL=modifiers.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/modifiers/modifiers.d.ts.map b/lib/platform/web/modifiers/modifiers.d.ts.map deleted file mode 100644 index cbb2af238..000000000 --- a/lib/platform/web/modifiers/modifiers.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"modifiers.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/modifiers/modifiers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,cAAc,CAAC;AA+EjE;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG7G;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAG9G;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGjH;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGpG;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,iCAAiC,CAKlF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAGrG;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAmBtG;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAevG"} \ No newline at end of file diff --git a/lib/platform/web/modifiers/modifiers.js b/lib/platform/web/modifiers/modifiers.js deleted file mode 100644 index bc87b33b7..000000000 --- a/lib/platform/web/modifiers/modifiers.js +++ /dev/null @@ -1,163 +0,0 @@ -const stripPayload = (sdp, payload) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const mediaDescs = []; - const lines = sdp.split(/\r\n/); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let currentMediaDesc; - for (let i = 0; i < lines.length;) { - const line = lines[i]; - if (/^m=(?:audio|video)/.test(line)) { - currentMediaDesc = { - index: i, - stripped: [] - }; - mediaDescs.push(currentMediaDesc); - } - else if (currentMediaDesc) { - const rtpmap = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line); - if (rtpmap && payload === rtpmap[2]) { - lines.splice(i, 1); - currentMediaDesc.stripped.push(rtpmap[1]); - continue; // Don't increment 'i' - } - } - i++; - } - for (const mediaDesc of mediaDescs) { - const mline = lines[mediaDesc.index].split(" "); - // Ignore the first 3 parameters of the mline. The codec information is after that - for (let j = 3; j < mline.length;) { - if (mediaDesc.stripped.indexOf(mline[j]) !== -1) { - mline.splice(j, 1); - continue; - } - j++; - } - lines[mediaDesc.index] = mline.join(" "); - } - return lines.join("\r\n"); -}; -const stripMediaDescription = (sdp, description) => { - const descriptionRegExp = new RegExp("m=" + description + ".*$", "gm"); - const groupRegExp = new RegExp("^a=group:.*$", "gm"); - if (descriptionRegExp.test(sdp)) { - let midLineToRemove; - sdp = sdp.split(/^m=/gm).filter((section) => { - if (section.substr(0, description.length) === description) { - midLineToRemove = section.match(/^a=mid:.*$/gm); - if (midLineToRemove) { - const step = midLineToRemove[0].match(/:.+$/g); - if (step) { - midLineToRemove = step[0].substr(1); - } - } - return false; - } - return true; - }).join("m="); - const groupLine = sdp.match(groupRegExp); - if (groupLine && groupLine.length === 1) { - let groupLinePortion = groupLine[0]; - // eslint-disable-next-line no-useless-escape - const groupRegExpReplace = new RegExp("\ *" + midLineToRemove + "[^\ ]*", "g"); - groupLinePortion = groupLinePortion.replace(groupRegExpReplace, ""); - sdp = sdp.split(groupRegExp).join(groupLinePortion); - } - } - return sdp; -}; -/** - * Modifier. - * @public - */ -export function stripTcpCandidates(description) { - description.sdp = (description.sdp || "").replace(/^a=candidate:\d+ \d+ tcp .*?\r\n/img, ""); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -export function stripTelephoneEvent(description) { - description.sdp = stripPayload(description.sdp || "", "telephone-event"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -export function cleanJitsiSdpImageattr(description) { - description.sdp = (description.sdp || "").replace(/^(a=imageattr:.*?)(x|y)=\[0-/gm, "$1$2=[1:"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -export function stripG722(description) { - description.sdp = stripPayload(description.sdp || "", "G722"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -export function stripRtpPayload(payload) { - return (description) => { - description.sdp = stripPayload(description.sdp || "", payload); - return Promise.resolve(description); - }; -} -/** - * Modifier. - * @public - */ -export function stripVideo(description) { - description.sdp = stripMediaDescription(description.sdp || "", "video"); - return Promise.resolve(description); -} -/** - * Modifier. - * @public - */ -export function addMidLines(description) { - let sdp = description.sdp || ""; - if (sdp.search(/^a=mid.*$/gm) === -1) { - const mlines = sdp.match(/^m=.*$/gm); - const sdpArray = sdp.split(/^m=.*$/gm); - if (mlines) { - mlines.forEach((elem, idx) => { - mlines[idx] = elem + "\na=mid:" + idx; - }); - } - sdpArray.forEach((elem, idx) => { - if (mlines && mlines[idx]) { - sdpArray[idx] = elem + mlines[idx]; - } - }); - sdp = sdpArray.join(""); - description.sdp = sdp; - } - return Promise.resolve(description); -} -/** - * The modifier that should be used when the session would like to place the call on hold. - * @param description - The description that will be modified. - */ -export function holdModifier(description) { - if (!description.sdp || !description.type) { - throw new Error("Invalid SDP"); - } - let sdp = description.sdp; - const type = description.type; - if (sdp) { - if (!/a=(sendrecv|sendonly|recvonly|inactive)/.test(sdp)) { - sdp = sdp.replace(/(m=[^\r]*\r\n)/g, "$1a=sendonly\r\n"); - } - else { - sdp = sdp.replace(/a=sendrecv\r\n/g, "a=sendonly\r\n"); - sdp = sdp.replace(/a=recvonly\r\n/g, "a=inactive\r\n"); - } - } - return Promise.resolve({ sdp, type }); -} diff --git a/lib/platform/web/session-description-handler/index.d.ts b/lib/platform/web/session-description-handler/index.d.ts deleted file mode 100644 index c2d06bcce..000000000 --- a/lib/platform/web/session-description-handler/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * A SessionDescriptionHandler for web browsers. - * @packageDocumentation - */ -export * from "./media-stream-factory-default"; -export * from "./media-stream-factory"; -export * from "./peer-connection-configuration-default"; -export * from "./peer-connection-delegate"; -export * from "./session-description-handler-configuration"; -export * from "./session-description-handler-factory-default"; -export * from "./session-description-handler-factory-options"; -export * from "./session-description-handler-factory"; -export * from "./session-description-handler-options"; -export * from "./session-description-handler"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/index.d.ts.map b/lib/platform/web/session-description-handler/index.d.ts.map deleted file mode 100644 index 3737a47e0..000000000 --- a/lib/platform/web/session-description-handler/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,gCAAgC,CAAC;AAC/C,cAAc,wBAAwB,CAAC;AACvC,cAAc,yCAAyC,CAAC;AACxD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6CAA6C,CAAC;AAC5D,cAAc,+CAA+C,CAAC;AAC9D,cAAc,+CAA+C,CAAC;AAC9D,cAAc,uCAAuC,CAAC;AACtD,cAAc,uCAAuC,CAAC;AACtD,cAAc,+BAA+B,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/index.js b/lib/platform/web/session-description-handler/index.js deleted file mode 100644 index 63c3b42f0..000000000 --- a/lib/platform/web/session-description-handler/index.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A SessionDescriptionHandler for web browsers. - * @packageDocumentation - */ -export * from "./media-stream-factory-default"; -export * from "./media-stream-factory"; -export * from "./peer-connection-configuration-default"; -export * from "./peer-connection-delegate"; -export * from "./session-description-handler-configuration"; -export * from "./session-description-handler-factory-default"; -export * from "./session-description-handler-factory-options"; -export * from "./session-description-handler-factory"; -export * from "./session-description-handler-options"; -export * from "./session-description-handler"; diff --git a/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts b/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts deleted file mode 100644 index 5c1537d99..000000000 --- a/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MediaStreamFactory } from "./media-stream-factory"; -/** - * Function which returns a MediaStreamFactory. - * @public - */ -export declare function defaultMediaStreamFactory(): MediaStreamFactory; -//# sourceMappingURL=media-stream-factory-default.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map b/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map deleted file mode 100644 index 791b6f5ea..000000000 --- a/lib/platform/web/session-description-handler/media-stream-factory-default.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"media-stream-factory-default.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/media-stream-factory-default.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE5D;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,kBAAkB,CAe9D"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory-default.js b/lib/platform/web/session-description-handler/media-stream-factory-default.js deleted file mode 100644 index abbed9c71..000000000 --- a/lib/platform/web/session-description-handler/media-stream-factory-default.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Function which returns a MediaStreamFactory. - * @public - */ -export function defaultMediaStreamFactory() { - return (constraints) => { - // if no audio or video, return a media stream without tracks - if (!constraints.audio && !constraints.video) { - return Promise.resolve(new MediaStream()); - } - // getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, - // navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, - // a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. - // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Privacy_and_security - if (navigator.mediaDevices === undefined) { - return Promise.reject(new Error("Media devices not available in insecure contexts.")); - } - return navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices, constraints); - }; -} diff --git a/lib/platform/web/session-description-handler/media-stream-factory.d.ts b/lib/platform/web/session-description-handler/media-stream-factory.d.ts deleted file mode 100644 index 99935573f..000000000 --- a/lib/platform/web/session-description-handler/media-stream-factory.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { SessionDescriptionHandler } from "./session-description-handler"; -/** - * Interface of factory function which produces a MediaStream. - * @public - */ -export declare type MediaStreamFactory = (constraints: MediaStreamConstraints, sessionDescriptionHandler: SessionDescriptionHandler) => Promise; -//# sourceMappingURL=media-stream-factory.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory.d.ts.map b/lib/platform/web/session-description-handler/media-stream-factory.d.ts.map deleted file mode 100644 index f591f66fc..000000000 --- a/lib/platform/web/session-description-handler/media-stream-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"media-stream-factory.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/media-stream-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E;;;GAGG;AACH,oBAAY,kBAAkB,GAAG,CAC/B,WAAW,EAAE,sBAAsB,EACnC,yBAAyB,EAAE,yBAAyB,KACjD,OAAO,CAAC,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/media-stream-factory.js b/lib/platform/web/session-description-handler/media-stream-factory.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts b/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts deleted file mode 100644 index 2a875e2ee..000000000 --- a/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Function which returns an RTCConfiguration. - * @public - */ -export declare function defaultPeerConnectionConfiguration(): RTCConfiguration; -//# sourceMappingURL=peer-connection-configuration-default.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map b/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map deleted file mode 100644 index 7e73cdd1c..000000000 --- a/lib/platform/web/session-description-handler/peer-connection-configuration-default.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"peer-connection-configuration-default.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/peer-connection-configuration-default.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,kCAAkC,IAAI,gBAAgB,CAWrE"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-configuration-default.js b/lib/platform/web/session-description-handler/peer-connection-configuration-default.js deleted file mode 100644 index 2ab132086..000000000 --- a/lib/platform/web/session-description-handler/peer-connection-configuration-default.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Function which returns an RTCConfiguration. - * @public - */ -export function defaultPeerConnectionConfiguration() { - const configuration = { - bundlePolicy: "balanced", - certificates: undefined, - iceCandidatePoolSize: 0, - iceServers: [{ urls: "stun:stun.l.google.com:19302" }], - iceTransportPolicy: "all", - peerIdentity: undefined, - rtcpMuxPolicy: "require" - }; - return configuration; -} diff --git a/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts b/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts deleted file mode 100644 index 8d1f8e511..000000000 --- a/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Delegate to handle PeerConnection state changes. - * @public - */ -export interface PeerConnectionDelegate { - /** - * This happens whenever the aggregate state of the connection changes. - * The aggregate state is a combination of the states of all of the - * individual network transports being used by the connection. - * @param event - Event. - */ - onconnectionstatechange?(event: Event): void; - /** - * Triggered when an RTCDataChannel is added to the connection by the - * remote peer calling createDataChannel(). - * @param event - RTCDataChannelEvent. - */ - ondatachannel?(event: RTCDataChannelEvent): void; - /** - * Triggered when a new ICE candidate has been found. - * @param event - RTCPeerConnectionIceEvent. - */ - onicecandidate?(event: RTCPeerConnectionIceEvent): void; - /** - * Triggered when an error occurred during ICE candidate gathering. - * @param event - RTCPeerConnectionIceErrorEvent. - */ - onicecandidateerror?(event: RTCPeerConnectionIceErrorEvent): void; - /** - * This happens whenever the local ICE agent needs to deliver a message to - * the other peer through the signaling server. This lets the ICE agent - * perform negotiation with the remote peer without the browser itself - * needing to know any specifics about the technology being used for - * signalingTriggered when the IceConnectionState changes. - * @param event - Event. - */ - oniceconnectionstatechange?(event: Event): void; - /** - * Triggered when the ICE gathering state changes. - * @param event - Event. - */ - onicegatheringstatechange?(event: Event): void; - /** - * Triggered when renegotiation is necessary. - * @param event - Event. - */ - onnegotiationneeded?(event: Event): void; - /** - * Triggered when the SignalingState changes. - * @param event - Event. - */ - onsignalingstatechange?(event: Event): void; - /** - * Triggered when when a statistics object being monitored is deleted. - * @param event - Event. - */ - onstatsended?(event: Event): void; - /** - * Triggered when a new track is signaled by the remote peer, as a result of setRemoteDescription. - * @param event - Event. - */ - ontrack?(event: Event): void; -} -//# sourceMappingURL=peer-connection-delegate.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map b/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map deleted file mode 100644 index 5a133138d..000000000 --- a/lib/platform/web/session-description-handler/peer-connection-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"peer-connection-delegate.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/peer-connection-delegate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;;;OAKG;IACH,uBAAuB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAE7C;;;;OAIG;IACH,aAAa,CAAC,CAAC,KAAK,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAEjD;;;OAGG;IACH,cAAc,CAAC,CAAC,KAAK,EAAE,yBAAyB,GAAG,IAAI,CAAC;IAExD;;;OAGG;IACH,mBAAmB,CAAC,CAAC,KAAK,EAAE,8BAA8B,GAAG,IAAI,CAAC;IAElE;;;;;;;OAOG;IACH,0BAA0B,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEhD;;;OAGG;IACH,yBAAyB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAE/C;;;OAGG;IACH,mBAAmB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEzC;;;OAGG;IACH,sBAAsB,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,YAAY,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAElC;;;OAGG;IACH,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CAC9B"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/peer-connection-delegate.js b/lib/platform/web/session-description-handler/peer-connection-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts b/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts deleted file mode 100644 index 3b212fc76..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Configuration for SessionDescriptionHandler. - * @public - */ -export interface SessionDescriptionHandlerConfiguration { - /** - * The maximum duration to wait in ms for ICE gathering to complete. - * If undefined, implementation dependent. - * If zero, no timeout. - */ - iceGatheringTimeout?: number; - /** - * Peer connection options. - */ - peerConnectionConfiguration?: RTCConfiguration; -} -//# sourceMappingURL=session-description-handler-configuration.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map deleted file mode 100644 index d31181610..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-configuration.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-configuration.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-configuration.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,sCAAsC;IACrD;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,2BAA2B,CAAC,EAAE,gBAAgB,CAAC;CAChD"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-configuration.js b/lib/platform/web/session-description-handler/session-description-handler-configuration.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts b/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts deleted file mode 100644 index c0a3341d9..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { SessionDescriptionHandler } from "./session-description-handler"; -import { SessionDescriptionHandlerFactory } from "./session-description-handler-factory"; -/** - * Function which returns a SessionDescriptionHandlerFactory. - * @remarks - * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. - * The ICE gathering timeout defaults to 5000ms. - * @param mediaStreamFactory - MediaStream factory. - * @public - */ -export declare function defaultSessionDescriptionHandlerFactory(mediaStreamFactory?: (constraints: MediaStreamConstraints, sessionDescriptionHandler: SessionDescriptionHandler) => Promise): SessionDescriptionHandlerFactory; -//# sourceMappingURL=session-description-handler-factory-default.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map deleted file mode 100644 index 2f5f9627d..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory-default.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-factory-default.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-factory-default.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAGzF;;;;;;;GAOG;AACH,wBAAgB,uCAAuC,CACrD,kBAAkB,CAAC,EAAE,CACnB,WAAW,EAAE,sBAAsB,EACnC,yBAAyB,EAAE,yBAAyB,KACjD,OAAO,CAAC,WAAW,CAAC,GACxB,gCAAgC,CAuBlC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-default.js b/lib/platform/web/session-description-handler/session-description-handler-factory-default.js deleted file mode 100644 index cf2bd48b7..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory-default.js +++ /dev/null @@ -1,28 +0,0 @@ -import { defaultMediaStreamFactory } from "./media-stream-factory-default"; -import { defaultPeerConnectionConfiguration } from "./peer-connection-configuration-default"; -import { SessionDescriptionHandler } from "./session-description-handler"; -/** - * Function which returns a SessionDescriptionHandlerFactory. - * @remarks - * See {@link defaultPeerConnectionConfiguration} for the default peer connection configuration. - * The ICE gathering timeout defaults to 5000ms. - * @param mediaStreamFactory - MediaStream factory. - * @public - */ -export function defaultSessionDescriptionHandlerFactory(mediaStreamFactory) { - return (session, options) => { - // provide a default media stream factory if need be - if (mediaStreamFactory === undefined) { - mediaStreamFactory = defaultMediaStreamFactory(); - } - // make sure we allow `0` to be passed in so timeout can be disabled - const iceGatheringTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) !== undefined ? options === null || options === void 0 ? void 0 : options.iceGatheringTimeout : 5000; - // merge passed factory options into default session description configuration - const sessionDescriptionHandlerConfiguration = { - iceGatheringTimeout, - peerConnectionConfiguration: Object.assign(Object.assign({}, defaultPeerConnectionConfiguration()), options === null || options === void 0 ? void 0 : options.peerConnectionConfiguration) - }; - const logger = session.userAgent.getLogger("sip.SessionDescriptionHandler"); - return new SessionDescriptionHandler(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration); - }; -} diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts b/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts deleted file mode 100644 index dd3c97b4d..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { SessionDescriptionHandlerConfiguration } from "./session-description-handler-configuration"; -/** - * Options for SessionDescriptionHandlerFactory. - * @remarks - * The "options" are provided as part of the UserAgent configuration and passed through - * on every call to SessionDescriptionHandlerFactory's constructor. - * @public - */ -export declare type SessionDescriptionHandlerFactoryOptions = SessionDescriptionHandlerConfiguration; -//# sourceMappingURL=session-description-handler-factory-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map deleted file mode 100644 index 6ac43615b..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-factory-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-factory-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,6CAA6C,CAAC;AAErG;;;;;;GAMG;AACH,oBAAY,uCAAuC,GAAG,sCAAsC,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory-options.js b/lib/platform/web/session-description-handler/session-description-handler-factory-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts b/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts deleted file mode 100644 index 8239fd08e..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Session, SessionDescriptionHandlerFactory as SessionDescriptionHandlerFactoryDefinition } from "../../../api"; -import { SessionDescriptionHandler } from "./session-description-handler"; -import { SessionDescriptionHandlerFactoryOptions } from "./session-description-handler-factory-options"; -/** - * Factory for {@link SessionDescriptionHandler}. - * @public - */ -export interface SessionDescriptionHandlerFactory extends SessionDescriptionHandlerFactoryDefinition { - /** - * SessionDescriptionHandler factory function. - * @remarks - * The `options` are provided as part of the UserAgent configuration - * and passed through on every call to SessionDescriptionHandlerFactory's constructor. - */ - (session: Session, options?: SessionDescriptionHandlerFactoryOptions): SessionDescriptionHandler; -} -//# sourceMappingURL=session-description-handler-factory.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map deleted file mode 100644 index ba3f315a0..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-factory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-factory.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gCAAgC,IAAI,0CAA0C,EAAE,MAAM,cAAc,CAAC;AACvH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,uCAAuC,EAAE,MAAM,+CAA+C,CAAC;AAExG;;;GAGG;AACH,MAAM,WAAW,gCAAiC,SAAQ,0CAA0C;IAClG;;;;;OAKG;IACH,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,uCAAuC,GAAG,yBAAyB,CAAC;CAClG"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-factory.js b/lib/platform/web/session-description-handler/session-description-handler-factory.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/session-description-handler/session-description-handler-options.d.ts b/lib/platform/web/session-description-handler/session-description-handler-options.d.ts deleted file mode 100644 index 0e34afc95..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-options.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { SessionDescriptionHandlerOptions as SessionDescriptionHandlerOptionsDefinition } from "../../../api"; -/** - * Options for {@link SessionDescriptionHandler}. - * @public - */ -export interface SessionDescriptionHandlerOptions extends SessionDescriptionHandlerOptionsDefinition { - /** - * Answer options to use when creating an answer. - */ - answerOptions?: RTCAnswerOptions; - /** - * Constraints to use when creating local media stream. - * @remarks - * If undefined, defaults to audio true and video false. - * If audio and video are false, media stream will have no tracks. - */ - constraints?: MediaStreamConstraints; - /** - * If true, create a data channel when making initial offer. - */ - dataChannel?: boolean; - /** - * A human-readable name to use when creating the data channel. - */ - dataChannelLabel?: string; - /** - * Configuration options for creating the data channel. - */ - dataChannelOptions?: RTCDataChannelInit; - /** - * The maximum duration to wait in ms for ICE gathering to complete. - * No timeout if undefined or zero. - */ - iceGatheringTimeout?: number; - /** - * Offer options to use when creating an offer. - */ - offerOptions?: RTCOfferOptions; - /** - * Called upon creating a data channel. - */ - onDataChannel?: (dataChannel: RTCDataChannel) => void; -} -//# sourceMappingURL=session-description-handler-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map deleted file mode 100644 index 3d6f37c61..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,IAAI,0CAA0C,EAAE,MAAM,cAAc,CAAC;AAE9G;;;GAGG;AACH,MAAM,WAAW,gCAAiC,SAAQ,0CAA0C;IAClG;;OAEG;IACH,aAAa,CAAC,EAAE,gBAAgB,CAAC;IAEjC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,sBAAsB,CAAC;IAErC;;OAEG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;OAEG;IACH,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;IAExC;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,YAAY,CAAC,EAAE,eAAe,CAAC;IAE/B;;OAEG;IACH,aAAa,CAAC,EAAE,CAAC,WAAW,EAAE,cAAc,KAAK,IAAI,CAAC;CACvD"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler-options.js b/lib/platform/web/session-description-handler/session-description-handler-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/session-description-handler/session-description-handler.d.ts b/lib/platform/web/session-description-handler/session-description-handler.d.ts deleted file mode 100644 index c29b1f552..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler.d.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { BodyAndContentType, SessionDescriptionHandler as SessionDescriptionHandlerDefinition, SessionDescriptionHandlerModifier } from "../../../api"; -import { Logger } from "../../../core"; -import { MediaStreamFactory } from "./media-stream-factory"; -import { SessionDescriptionHandlerConfiguration } from "./session-description-handler-configuration"; -import { SessionDescriptionHandlerOptions } from "./session-description-handler-options"; -import { PeerConnectionDelegate } from "./peer-connection-delegate"; -/** - * A base class implementing a WebRTC session description handler for sip.js. - * @remarks - * It is expected/intended to be extended by specific WebRTC based applications. - * @privateRemarks - * So do not put application specific implementation in here. - * @public - */ -export declare class SessionDescriptionHandler implements SessionDescriptionHandlerDefinition { - /** Logger. */ - protected logger: Logger; - /** Media stream factory. */ - protected mediaStreamFactory: MediaStreamFactory; - /** Configuration options. */ - protected sessionDescriptionHandlerConfiguration?: SessionDescriptionHandlerConfiguration; - /** The local media stream. */ - protected _localMediaStream: MediaStream; - /** The remote media stream. */ - protected _remoteMediaStream: MediaStream; - /** The data channel. Undefined before created. */ - protected _dataChannel: RTCDataChannel | undefined; - /** The peer connection. Undefined after SessionDescriptionHandler.close(). */ - protected _peerConnection: RTCPeerConnection | undefined; - /** The peer connection delegate. */ - protected _peerConnectionDelegate: PeerConnectionDelegate | undefined; - private iceGatheringCompletePromise; - private iceGatheringCompleteTimeoutId; - private iceGatheringCompleteResolve; - private iceGatheringCompleteReject; - private localMediaStreamConstraints; - private onDataChannel; - /** - * Constructor - * @param logger - A logger - * @param mediaStreamFactory - A factory to provide a MediaStream - * @param options - Options passed from the SessionDescriptionHandleFactory - */ - constructor(logger: Logger, mediaStreamFactory: MediaStreamFactory, sessionDescriptionHandlerConfiguration?: SessionDescriptionHandlerConfiguration); - /** - * The local media stream currently being sent. - * - * @remarks - * The local media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * local media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get localMediaStream(): MediaStream; - /** - * The remote media stream currently being received. - * - * @remarks - * The remote media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * remote media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get remoteMediaStream(): MediaStream; - /** - * The data channel. Undefined before it is created. - */ - get dataChannel(): RTCDataChannel | undefined; - /** - * The peer connection. Undefined if peer connection has closed. - * - * @remarks - * While access to the underlying `RTCPeerConnection` is provided, note that - * using methods with modify it may break the operation of this class. - * In particular, this class depends on exclusive access to the - * event handler properties. If you need access to the peer connection - * events, either register for events using `addEventListener()` on - * the `RTCPeerConnection` or set the `peerConnectionDelegate` on - * this `SessionDescriptionHandler`. - */ - get peerConnection(): RTCPeerConnection | undefined; - /** - * A delegate which provides access to the peer connection event handlers. - * - * @remarks - * Setting the peer connection event handlers directly is not supported - * and may break this class. As this class depends on exclusive access - * to them, a delegate may be set which provides alternative access to - * the event handlers in a fashion which is supported. - */ - get peerConnectionDelegate(): PeerConnectionDelegate | undefined; - set peerConnectionDelegate(delegate: PeerConnectionDelegate | undefined); - private static dispatchAddTrackEvent; - private static dispatchRemoveTrackEvent; - /** - * Stop tracks and close peer connection. - */ - close(): void; - /** - * Creates an offer or answer. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - getDescription(options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; - /** - * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. - * @param contentType - The content type that is in the SIP Message. - */ - hasDescription(contentType: string): boolean; - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones - A string containing DTMF digits. - * @param options - Options object to be used by sendDtmf. - */ - sendDtmf(tones: string, options?: { - duration: number; - interToneGap: number; - }): boolean; - /** - * Sets an offer or answer. - * @param sdp - The session description. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - setDescription(sdp: string, options?: SessionDescriptionHandlerOptions, modifiers?: Array): Promise; - /** - * Applies modifiers to SDP prior to setting the local or remote description. - * @param sdp - SDP to modify. - * @param modifiers - Modifiers to apply. - */ - protected applyModifiers(sdp: RTCSessionDescriptionInit, modifiers?: Array): Promise; - /** - * Create a data channel. - * @remarks - * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. - * Only creates a data channel if creating a local offer. - * Only if one does not already exist. - * @param options - Session description handler options. - */ - protected createDataChannel(options?: SessionDescriptionHandlerOptions): Promise; - /** - * Depending on current signaling state, create a local offer or answer. - * @param options - Session description handler options. - */ - protected createLocalOfferOrAnswer(options?: SessionDescriptionHandlerOptions): Promise; - /** - * Get a media stream from the media stream factory and set the local media stream. - * @param options - Session description handler options. - */ - protected getLocalMediaStream(options?: SessionDescriptionHandlerOptions): Promise; - /** - * Sets the peer connection's sender tracks and local media stream tracks. - * - * @remarks - * Only the first audio and video tracks of the provided MediaStream are utilized. - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param stream - Media stream containing tracks to be utilized. - */ - protected setLocalMediaStream(stream: MediaStream): Promise; - /** - * Gets the peer connection's local session description. - */ - protected getLocalSessionDescription(): Promise; - /** - * Sets the peer connection's local session description. - * @param sessionDescription - sessionDescription The session description. - */ - protected setLocalSessionDescription(sessionDescription: RTCSessionDescriptionInit): Promise; - /** - * Sets the peer connection's remote session description. - * @param sessionDescription - The session description. - */ - protected setRemoteSessionDescription(sessionDescription: RTCSessionDescriptionInit): Promise; - /** - * Sets a remote media stream track. - * - * @remarks - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param track - Media stream track to be utilized. - */ - protected setRemoteTrack(track: MediaStreamTrack): void; - /** - * Called when ICE gathering completes and resolves any waiting promise. - */ - protected iceGatheringComplete(): void; - /** - * Wait for ICE gathering to complete. - * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). - * @param timeout - Milliseconds after which waiting times out. No timeout if 0. - */ - protected waitForIceGatheringComplete(restart?: boolean, timeout?: number): Promise; - /** - * Initializes the peer connection event handlers - */ - private initPeerConnectionEventHandlers; -} -//# sourceMappingURL=session-description-handler.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler.d.ts.map b/lib/platform/web/session-description-handler/session-description-handler.d.ts.map deleted file mode 100644 index ebeb96425..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"session-description-handler.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/session-description-handler/session-description-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,yBAAyB,IAAI,mCAAmC,EAChE,iCAAiC,EAClC,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,sCAAsC,EAAE,MAAM,6CAA6C,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAoBpE;;;;;;;GAOG;AACH,qBAAa,yBAA0B,YAAW,mCAAmC;IACnF,cAAc;IACd,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,4BAA4B;IAC5B,SAAS,CAAC,kBAAkB,EAAE,kBAAkB,CAAC;IACjD,6BAA6B;IAC7B,SAAS,CAAC,sCAAsC,CAAC,EAAE,sCAAsC,CAAC;IAE1F,8BAA8B;IAC9B,SAAS,CAAC,iBAAiB,EAAE,WAAW,CAAC;IACzC,+BAA+B;IAC/B,SAAS,CAAC,kBAAkB,EAAE,WAAW,CAAC;IAC1C,kDAAkD;IAClD,SAAS,CAAC,YAAY,EAAE,cAAc,GAAG,SAAS,CAAC;IACnD,8EAA8E;IAC9E,SAAS,CAAC,eAAe,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACzD,oCAAoC;IACpC,SAAS,CAAC,uBAAuB,EAAE,sBAAsB,GAAG,SAAS,CAAC;IAEtE,OAAO,CAAC,2BAA2B,CAA4B;IAC/D,OAAO,CAAC,6BAA6B,CAAqB;IAC1D,OAAO,CAAC,2BAA2B,CAA8B;IACjE,OAAO,CAAC,0BAA0B,CAA6B;IAC/D,OAAO,CAAC,2BAA2B,CAAqC;IACxE,OAAO,CAAC,aAAa,CAAsD;IAE3E;;;;;OAKG;gBAED,MAAM,EAAE,MAAM,EACd,kBAAkB,EAAE,kBAAkB,EACtC,sCAAsC,CAAC,EAAE,sCAAsC;IAYjF;;;;;;;;;;;;OAYG;IACH,IAAI,gBAAgB,IAAI,WAAW,CAElC;IAED;;;;;;;;;;;;OAYG;IACH,IAAI,iBAAiB,IAAI,WAAW,CAEnC;IAED;;OAEG;IACH,IAAI,WAAW,IAAI,cAAc,GAAG,SAAS,CAE5C;IAED;;;;;;;;;;;OAWG;IACH,IAAI,cAAc,IAAI,iBAAiB,GAAG,SAAS,CAElD;IAED;;;;;;;;OAQG;IACH,IAAI,sBAAsB,IAAI,sBAAsB,GAAG,SAAS,CAE/D;IAED,IAAI,sBAAsB,CAAC,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAEtE;IAID,OAAO,CAAC,MAAM,CAAC,qBAAqB;IAKpC,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAIvC;;OAEG;IACI,KAAK,IAAI,IAAI;IAkBpB;;;;OAIG;IACI,cAAc,CACnB,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,kBAAkB,CAAC;IAoC9B;;;OAGG;IACI,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO;IAKnD;;;;;OAKG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO;IA4B7F;;;;;OAKG;IACI,cAAc,CACnB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gCAAgC,EAC1C,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,IAAI,CAAC;IAqBhB;;;;OAIG;IACH,SAAS,CAAC,cAAc,CACtB,GAAG,EAAE,yBAAyB,EAC9B,SAAS,CAAC,EAAE,KAAK,CAAC,iCAAiC,CAAC,GACnD,OAAO,CAAC,yBAAyB,CAAC;IAgBrC;;;;;;;OAOG;IACH,SAAS,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC,IAAI,CAAC;IAuCtF;;;OAGG;IACH,SAAS,CAAC,wBAAwB,CAAC,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAsBlH;;;OAGG;IACH,SAAS,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC,IAAI,CAAC;IA+BxF;;;;;;;;OAQG;IACH,SAAS,CAAC,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAgFjE;;OAEG;IACH,SAAS,CAAC,0BAA0B,IAAI,OAAO,CAAC,qBAAqB,CAAC;IAYtE;;;OAGG;IACH,SAAS,CAAC,0BAA0B,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQlG;;;OAGG;IACH,SAAS,CAAC,2BAA2B,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IA8BnG;;;;;;;OAOG;IACH,SAAS,CAAC,cAAc,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IA4BvD;;OAEG;IACH,SAAS,CAAC,oBAAoB,IAAI,IAAI;IAkBtC;;;;OAIG;IACH,SAAS,CAAC,2BAA2B,CAAC,OAAO,UAAQ,EAAE,OAAO,SAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAgClF;;OAEG;IACH,OAAO,CAAC,+BAA+B;CA0FxC"} \ No newline at end of file diff --git a/lib/platform/web/session-description-handler/session-description-handler.js b/lib/platform/web/session-description-handler/session-description-handler.js deleted file mode 100644 index 003192159..000000000 --- a/lib/platform/web/session-description-handler/session-description-handler.js +++ /dev/null @@ -1,661 +0,0 @@ -/** - * A base class implementing a WebRTC session description handler for sip.js. - * @remarks - * It is expected/intended to be extended by specific WebRTC based applications. - * @privateRemarks - * So do not put application specific implementation in here. - * @public - */ -export class SessionDescriptionHandler { - /** - * Constructor - * @param logger - A logger - * @param mediaStreamFactory - A factory to provide a MediaStream - * @param options - Options passed from the SessionDescriptionHandleFactory - */ - constructor(logger, mediaStreamFactory, sessionDescriptionHandlerConfiguration) { - logger.debug("SessionDescriptionHandler.constructor"); - this.logger = logger; - this.mediaStreamFactory = mediaStreamFactory; - this.sessionDescriptionHandlerConfiguration = sessionDescriptionHandlerConfiguration; - this._localMediaStream = new MediaStream(); - this._remoteMediaStream = new MediaStream(); - this._peerConnection = new RTCPeerConnection(sessionDescriptionHandlerConfiguration === null || sessionDescriptionHandlerConfiguration === void 0 ? void 0 : sessionDescriptionHandlerConfiguration.peerConnectionConfiguration); - this.initPeerConnectionEventHandlers(); - } - /** - * The local media stream currently being sent. - * - * @remarks - * The local media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * local media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get localMediaStream() { - return this._localMediaStream; - } - /** - * The remote media stream currently being received. - * - * @remarks - * The remote media stream initially has no tracks, so the presence of tracks - * should not be assumed. Furthermore, tracks may be added or removed if the - * remote media changes - for example, on upgrade from audio only to a video session. - * At any given time there will be at most one audio track and one video track - * (it's possible that this restriction may not apply to sub-classes). - * Use `MediaStream.onaddtrack` or add a listener for the `addtrack` event - * to detect when a new track becomes available: - * https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - */ - get remoteMediaStream() { - return this._remoteMediaStream; - } - /** - * The data channel. Undefined before it is created. - */ - get dataChannel() { - return this._dataChannel; - } - /** - * The peer connection. Undefined if peer connection has closed. - * - * @remarks - * While access to the underlying `RTCPeerConnection` is provided, note that - * using methods with modify it may break the operation of this class. - * In particular, this class depends on exclusive access to the - * event handler properties. If you need access to the peer connection - * events, either register for events using `addEventListener()` on - * the `RTCPeerConnection` or set the `peerConnectionDelegate` on - * this `SessionDescriptionHandler`. - */ - get peerConnection() { - return this._peerConnection; - } - /** - * A delegate which provides access to the peer connection event handlers. - * - * @remarks - * Setting the peer connection event handlers directly is not supported - * and may break this class. As this class depends on exclusive access - * to them, a delegate may be set which provides alternative access to - * the event handlers in a fashion which is supported. - */ - get peerConnectionDelegate() { - return this._peerConnectionDelegate; - } - set peerConnectionDelegate(delegate) { - this._peerConnectionDelegate = delegate; - } - // The addtrack event does not get fired when JavaScript code explicitly adds tracks to the stream (by calling addTrack()). - // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onaddtrack - static dispatchAddTrackEvent(stream, track) { - stream.dispatchEvent(new MediaStreamTrackEvent("addtrack", { track })); - } - // The removetrack event does not get fired when JavaScript code explicitly removes tracks from the stream (by calling removeTrack()). - // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/onremovetrack - static dispatchRemoveTrackEvent(stream, track) { - stream.dispatchEvent(new MediaStreamTrackEvent("removetrack", { track })); - } - /** - * Stop tracks and close peer connection. - */ - close() { - this.logger.debug("SessionDescriptionHandler.close"); - if (this._peerConnection === undefined) { - return; - } - this._peerConnection.getReceivers().forEach((receiver) => { - receiver.track && receiver.track.stop(); - }); - this._peerConnection.getSenders().forEach((sender) => { - sender.track && sender.track.stop(); - }); - if (this._dataChannel) { - this._dataChannel.close(); - } - this._peerConnection.close(); - this._peerConnection = undefined; - } - /** - * Creates an offer or answer. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - getDescription(options, modifiers) { - var _a, _b; - this.logger.debug("SessionDescriptionHandler.getDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // Callback on data channel creation - this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; - // ICE will restart upon applying an offer created with the iceRestart option - const iceRestart = (_a = options === null || options === void 0 ? void 0 : options.offerOptions) === null || _a === void 0 ? void 0 : _a.iceRestart; - // ICE gathering timeout may be set on a per call basis, otherwise the configured default is used - const iceTimeout = (options === null || options === void 0 ? void 0 : options.iceGatheringTimeout) === undefined - ? (_b = this.sessionDescriptionHandlerConfiguration) === null || _b === void 0 ? void 0 : _b.iceGatheringTimeout : options === null || options === void 0 ? void 0 : options.iceGatheringTimeout; - return this.getLocalMediaStream(options) - .then(() => this.createDataChannel(options)) - .then(() => this.createLocalOfferOrAnswer(options)) - .then((sessionDescription) => this.applyModifiers(sessionDescription, modifiers)) - .then((sessionDescription) => this.setLocalSessionDescription(sessionDescription)) - .then(() => this.waitForIceGatheringComplete(iceRestart, iceTimeout)) - .then(() => this.getLocalSessionDescription()) - .then((sessionDescription) => { - return { - body: sessionDescription.sdp, - contentType: "application/sdp" - }; - }) - .catch((error) => { - this.logger.error("SessionDescriptionHandler.getDescription failed - " + error); - throw error; - }); - } - /** - * Returns true if the SessionDescriptionHandler can handle the Content-Type described by a SIP message. - * @param contentType - The content type that is in the SIP Message. - */ - hasDescription(contentType) { - this.logger.debug("SessionDescriptionHandler.hasDescription"); - return contentType === "application/sdp"; - } - /** - * Send DTMF via RTP (RFC 4733). - * Returns true if DTMF send is successful, false otherwise. - * @param tones - A string containing DTMF digits. - * @param options - Options object to be used by sendDtmf. - */ - sendDtmf(tones, options) { - this.logger.debug("SessionDescriptionHandler.sendDtmf"); - if (this._peerConnection === undefined) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"); - return false; - } - const senders = this._peerConnection.getSenders(); - if (senders.length === 0) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"); - return false; - } - const dtmfSender = senders[0].dtmf; - if (!dtmfSender) { - this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"); - return false; - } - const duration = options === null || options === void 0 ? void 0 : options.duration; - const interToneGap = options === null || options === void 0 ? void 0 : options.interToneGap; - try { - dtmfSender.insertDTMF(tones, duration, interToneGap); - } - catch (e) { - this.logger.error(e); - return false; - } - this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: " + tones.toString()); - return true; - } - /** - * Sets an offer or answer. - * @param sdp - The session description. - * @param options - Options bucket. - * @param modifiers - Modifiers. - */ - setDescription(sdp, options, modifiers) { - this.logger.debug("SessionDescriptionHandler.setDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // Callback on data channel creation - this.onDataChannel = options === null || options === void 0 ? void 0 : options.onDataChannel; - // SDP type - const type = this._peerConnection.signalingState === "have-local-offer" ? "answer" : "offer"; - return this.getLocalMediaStream(options) - .then(() => this.applyModifiers({ sdp, type }, modifiers)) - .then((sessionDescription) => this.setRemoteSessionDescription(sessionDescription)) - .catch((error) => { - this.logger.error("SessionDescriptionHandler.setDescription failed - " + error); - throw error; - }); - } - /** - * Applies modifiers to SDP prior to setting the local or remote description. - * @param sdp - SDP to modify. - * @param modifiers - Modifiers to apply. - */ - applyModifiers(sdp, modifiers) { - this.logger.debug("SessionDescriptionHandler.applyModifiers"); - if (!modifiers || modifiers.length === 0) { - return Promise.resolve(sdp); - } - return modifiers - .reduce((cur, next) => cur.then(next), Promise.resolve(sdp)) - .then((modified) => { - this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"); - if (!modified.sdp || !modified.type) { - throw new Error("Invalid SDP."); - } - return { sdp: modified.sdp, type: modified.type }; - }); - } - /** - * Create a data channel. - * @remarks - * Only creates a data channel if SessionDescriptionHandlerOptions.dataChannel is true. - * Only creates a data channel if creating a local offer. - * Only if one does not already exist. - * @param options - Session description handler options. - */ - createDataChannel(options) { - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - // only create a data channel if requested - if ((options === null || options === void 0 ? void 0 : options.dataChannel) !== true) { - return Promise.resolve(); - } - // do not create a data channel if we already have one - if (this._dataChannel) { - return Promise.resolve(); - } - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable, assume we are creating a local offer so create a data channel - this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel"); - try { - this._dataChannel = this._peerConnection.createDataChannel((options === null || options === void 0 ? void 0 : options.dataChannelLabel) || "", options === null || options === void 0 ? void 0 : options.dataChannelOptions); - if (this.onDataChannel) { - this.onDataChannel(this._dataChannel); - } - return Promise.resolve(); - } - catch (error) { - return Promise.reject(error); - } - case "have-remote-offer": - return Promise.resolve(); - case "have-local-offer": - case "have-local-pranswer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - } - /** - * Depending on current signaling state, create a local offer or answer. - * @param options - Session description handler options. - */ - createLocalOfferOrAnswer(options) { - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable, assume we are creating a local offer - this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"); - return this._peerConnection.createOffer(options === null || options === void 0 ? void 0 : options.offerOptions); - case "have-remote-offer": - // if we have a remote offer, assume we are creating a local answer - this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"); - return this._peerConnection.createAnswer(options === null || options === void 0 ? void 0 : options.answerOptions); - case "have-local-offer": - case "have-local-pranswer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - } - /** - * Get a media stream from the media stream factory and set the local media stream. - * @param options - Session description handler options. - */ - getLocalMediaStream(options) { - this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - let constraints = Object.assign({}, options === null || options === void 0 ? void 0 : options.constraints); - // if we already have a local media stream... - if (this.localMediaStreamConstraints) { - // ignore constraint "downgrades" - constraints.audio = constraints.audio || this.localMediaStreamConstraints.audio; - constraints.video = constraints.video || this.localMediaStreamConstraints.video; - // if constraints have not changed, do not get a new media stream - if (JSON.stringify(this.localMediaStreamConstraints.audio) === JSON.stringify(constraints.audio) && - JSON.stringify(this.localMediaStreamConstraints.video) === JSON.stringify(constraints.video)) { - return Promise.resolve(); - } - } - else { - // if no constraints have been specified, default to audio for initial media stream - if (constraints.audio === undefined && constraints.video === undefined) { - constraints = { audio: true }; - } - } - this.localMediaStreamConstraints = constraints; - return this.mediaStreamFactory(constraints, this).then((mediaStream) => this.setLocalMediaStream(mediaStream)); - } - /** - * Sets the peer connection's sender tracks and local media stream tracks. - * - * @remarks - * Only the first audio and video tracks of the provided MediaStream are utilized. - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param stream - Media stream containing tracks to be utilized. - */ - setLocalMediaStream(stream) { - this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"); - if (!this._peerConnection) { - throw new Error("Peer connection undefined."); - } - const pc = this._peerConnection; - const localStream = this._localMediaStream; - const trackUpdates = []; - const updateTrack = (newTrack) => { - const kind = newTrack.kind; - if (kind !== "audio" && kind !== "video") { - throw new Error(`Unknown new track kind ${kind}.`); - } - const sender = pc.getSenders().find((sender) => sender.track && sender.track.kind === kind); - if (sender) { - trackUpdates.push(new Promise((resolve) => { - this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${kind} track`); - resolve(); - }).then(() => sender - .replaceTrack(newTrack) - .then(() => { - const oldTrack = localStream.getTracks().find((localTrack) => localTrack.kind === kind); - if (oldTrack) { - oldTrack.stop(); - localStream.removeTrack(oldTrack); - SessionDescriptionHandler.dispatchRemoveTrackEvent(localStream, oldTrack); - } - localStream.addTrack(newTrack); - SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); - }) - .catch((error) => { - this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${kind} track`); - throw error; - }))); - } - else { - trackUpdates.push(new Promise((resolve) => { - this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${kind} track`); - resolve(); - }).then(() => { - // Review: could make streamless tracks a configurable option? - // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack#Usage_notes - try { - pc.addTrack(newTrack, localStream); - } - catch (error) { - this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${kind} track`); - throw error; - } - localStream.addTrack(newTrack); - SessionDescriptionHandler.dispatchAddTrackEvent(localStream, newTrack); - })); - } - }; - // update peer connection audio tracks - const audioTracks = stream.getAudioTracks(); - if (audioTracks.length) { - updateTrack(audioTracks[0]); - } - // update peer connection video tracks - const videoTracks = stream.getVideoTracks(); - if (videoTracks.length) { - updateTrack(videoTracks[0]); - } - return trackUpdates.reduce((p, x) => p.then(() => x), Promise.resolve()); - } - /** - * Gets the peer connection's local session description. - */ - getLocalSessionDescription() { - this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - const sdp = this._peerConnection.localDescription; - if (!sdp) { - return Promise.reject(new Error("Failed to get local session description")); - } - return Promise.resolve(sdp); - } - /** - * Sets the peer connection's local session description. - * @param sessionDescription - sessionDescription The session description. - */ - setLocalSessionDescription(sessionDescription) { - this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - return this._peerConnection.setLocalDescription(sessionDescription); - } - /** - * Sets the peer connection's remote session description. - * @param sessionDescription - The session description. - */ - setRemoteSessionDescription(sessionDescription) { - this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"); - if (this._peerConnection === undefined) { - return Promise.reject(new Error("Peer connection closed.")); - } - const sdp = sessionDescription.sdp; - let type; - switch (this._peerConnection.signalingState) { - case "stable": - // if we are stable assume this is a remote offer - type = "offer"; - break; - case "have-local-offer": - // if we made an offer, assume this is a remote answer - type = "answer"; - break; - case "have-local-pranswer": - case "have-remote-offer": - case "have-remote-pranswer": - case "closed": - default: - return Promise.reject(new Error("Invalid signaling state " + this._peerConnection.signalingState)); - } - if (!sdp) { - this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"); - return Promise.reject(new Error("SDP is undefined")); - } - return this._peerConnection.setRemoteDescription({ sdp, type }); - } - /** - * Sets a remote media stream track. - * - * @remarks - * Adds tracks if audio and/or video tracks are not already present, otherwise replaces tracks. - * - * @param track - Media stream track to be utilized. - */ - setRemoteTrack(track) { - this.logger.debug("SessionDescriptionHandler.setRemoteTrack"); - const remoteStream = this._remoteMediaStream; - if (remoteStream.getTrackById(track.id)) { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${track.kind} track`); - } - else if (track.kind === "audio") { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); - remoteStream.getAudioTracks().forEach((track) => { - track.stop(); - remoteStream.removeTrack(track); - SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); - }); - remoteStream.addTrack(track); - SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); - } - else if (track.kind === "video") { - this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${track.kind} track`); - remoteStream.getVideoTracks().forEach((track) => { - track.stop(); - remoteStream.removeTrack(track); - SessionDescriptionHandler.dispatchRemoveTrackEvent(remoteStream, track); - }); - remoteStream.addTrack(track); - SessionDescriptionHandler.dispatchAddTrackEvent(remoteStream, track); - } - } - /** - * Called when ICE gathering completes and resolves any waiting promise. - */ - iceGatheringComplete() { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"); - // clear timer if need be - if (this.iceGatheringCompleteTimeoutId !== undefined) { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"); - clearTimeout(this.iceGatheringCompleteTimeoutId); - this.iceGatheringCompleteTimeoutId = undefined; - } - // resolve and cleanup promise if need be - if (this.iceGatheringCompletePromise !== undefined) { - this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"); - this.iceGatheringCompleteResolve && this.iceGatheringCompleteResolve(); - this.iceGatheringCompletePromise = undefined; - this.iceGatheringCompleteResolve = undefined; - this.iceGatheringCompleteReject = undefined; - } - } - /** - * Wait for ICE gathering to complete. - * @param restart - If true, waits if current state is "complete" (waits for transition to "complete"). - * @param timeout - Milliseconds after which waiting times out. No timeout if 0. - */ - waitForIceGatheringComplete(restart = false, timeout = 0) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"); - if (this._peerConnection === undefined) { - return Promise.reject("Peer connection closed."); - } - // guard already complete - if (!restart && this._peerConnection.iceGatheringState === "complete") { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"); - return Promise.resolve(); - } - // only one may be waiting, reject any prior - if (this.iceGatheringCompletePromise !== undefined) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"); - this.iceGatheringCompleteReject && this.iceGatheringCompleteReject(new Error("Promise superseded.")); - this.iceGatheringCompletePromise = undefined; - this.iceGatheringCompleteResolve = undefined; - this.iceGatheringCompleteReject = undefined; - } - this.iceGatheringCompletePromise = new Promise((resolve, reject) => { - this.iceGatheringCompleteResolve = resolve; - this.iceGatheringCompleteReject = reject; - if (timeout > 0) { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in " + timeout); - this.iceGatheringCompleteTimeoutId = setTimeout(() => { - this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"); - this.iceGatheringComplete(); - }, timeout); - } - }); - return this.iceGatheringCompletePromise; - } - /** - * Initializes the peer connection event handlers - */ - initPeerConnectionEventHandlers() { - this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"); - if (!this._peerConnection) - throw new Error("Peer connection undefined."); - const peerConnection = this._peerConnection; - peerConnection.onconnectionstatechange = (event) => { - var _a; - const newState = peerConnection.connectionState; - this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onconnectionstatechange) { - this._peerConnectionDelegate.onconnectionstatechange(event); - } - }; - peerConnection.ondatachannel = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.ondatachannel`); - this._dataChannel = event.channel; - if (this.onDataChannel) { - this.onDataChannel(this._dataChannel); - } - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ondatachannel) { - this._peerConnectionDelegate.ondatachannel(event); - } - }; - peerConnection.onicecandidate = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onicecandidate`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidate) { - this._peerConnectionDelegate.onicecandidate(event); - } - }; - peerConnection.onicecandidateerror = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onicecandidateerror`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicecandidateerror) { - this._peerConnectionDelegate.onicecandidateerror(event); - } - }; - peerConnection.oniceconnectionstatechange = (event) => { - var _a; - const newState = peerConnection.iceConnectionState; - this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.oniceconnectionstatechange) { - this._peerConnectionDelegate.oniceconnectionstatechange(event); - } - }; - peerConnection.onicegatheringstatechange = (event) => { - var _a; - const newState = peerConnection.iceGatheringState; - this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${newState}`); - if (newState === "complete") { - this.iceGatheringComplete(); // complete waiting for ICE gathering to complete - } - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onicegatheringstatechange) { - this._peerConnectionDelegate.onicegatheringstatechange(event); - } - }; - peerConnection.onnegotiationneeded = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onnegotiationneeded`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onnegotiationneeded) { - this._peerConnectionDelegate.onnegotiationneeded(event); - } - }; - peerConnection.onsignalingstatechange = (event) => { - var _a; - const newState = peerConnection.signalingState; - this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${newState}`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onsignalingstatechange) { - this._peerConnectionDelegate.onsignalingstatechange(event); - } - }; - peerConnection.onstatsended = (event) => { - var _a; - this.logger.debug(`SessionDescriptionHandler.onstatsended`); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.onstatsended) { - this._peerConnectionDelegate.onstatsended(event); - } - }; - peerConnection.ontrack = (event) => { - var _a; - const kind = event.track.kind; - const enabled = event.track.enabled ? "enabled" : "disabled"; - this.logger.debug(`SessionDescriptionHandler.ontrack ${kind} ${enabled}`); - this.setRemoteTrack(event.track); - if ((_a = this._peerConnectionDelegate) === null || _a === void 0 ? void 0 : _a.ontrack) { - this._peerConnectionDelegate.ontrack(event); - } - }; - } -} diff --git a/lib/platform/web/simple-user/index.d.ts b/lib/platform/web/simple-user/index.d.ts deleted file mode 100644 index ecf9f4fa4..000000000 --- a/lib/platform/web/simple-user/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * A simple SIP user implementation for web browsers. - * @packageDocumentation - */ -export * from "./simple-user"; -export * from "./simple-user-delegate"; -export * from "./simple-user-options"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/index.d.ts.map b/lib/platform/web/simple-user/index.d.ts.map deleted file mode 100644 index 8b8931df7..000000000 --- a/lib/platform/web/simple-user/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,eAAe,CAAC;AAC9B,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/index.js b/lib/platform/web/simple-user/index.js deleted file mode 100644 index 6231e8cd7..000000000 --- a/lib/platform/web/simple-user/index.js +++ /dev/null @@ -1,7 +0,0 @@ -/** - * A simple SIP user implementation for web browsers. - * @packageDocumentation - */ -export * from "./simple-user"; -export * from "./simple-user-delegate"; -export * from "./simple-user-options"; diff --git a/lib/platform/web/simple-user/simple-user-delegate.d.ts b/lib/platform/web/simple-user/simple-user-delegate.d.ts deleted file mode 100644 index dff4542c8..000000000 --- a/lib/platform/web/simple-user/simple-user-delegate.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Delegate for {@link SimpleUser}. - * @public - */ -export interface SimpleUserDelegate { - /** - * Called when a call is answered. - * @remarks - * Callback for handling establishment of a new Session. - */ - onCallAnswered?(): void; - /** - * Called when a call is created. - * @remarks - * Callback for handling the creation of a new Session. - */ - onCallCreated?(): void; - /** - * Called when a call is received. - * @remarks - * Callback for handling incoming INVITE requests. - * The callback must either accept or reject the incoming call by calling `answer()` or `decline()` respectively. - */ - onCallReceived?(): void; - /** - * Called when a call is hung up. - * @remarks - * Callback for handling termination of a Session. - */ - onCallHangup?(): void; - /** - * Called when a call is put on hold or taken off hold. - * @remarks - * Callback for handling re-INVITE responses. - */ - onCallHold?(held: boolean): void; - /** - * Called when a call receives an incoming DTMF tone. - * @remarks - * Callback for handling an incoming INFO request with content type application/dtmf-relay. - */ - onCallDTMFReceived?(tone: string, duration: number): void; - /** - * Called upon receiving a message. - * @remarks - * Callback for handling incoming MESSAGE requests. - * @param message - The message received. - */ - onMessageReceived?(message: string): void; - /** - * Called when user is registered to received calls. - */ - onRegistered?(): void; - /** - * Called when user is no longer registered to received calls. - */ - onUnregistered?(): void; - /** - * Called when user is connected to server. - * @remarks - * Callback for handling user becomes connected. - */ - onServerConnect?(): void; - /** - * Called when user is no longer connected. - * @remarks - * Callback for handling user becomes disconnected. - * - * @param error - An Error if server caused the disconnect. Otherwise undefined. - */ - onServerDisconnect?(error?: Error): void; -} -//# sourceMappingURL=simple-user-delegate.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-delegate.d.ts.map b/lib/platform/web/simple-user/simple-user-delegate.d.ts.map deleted file mode 100644 index 90e080a39..000000000 --- a/lib/platform/web/simple-user/simple-user-delegate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simple-user-delegate.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/simple-user-delegate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,cAAc,CAAC,IAAI,IAAI,CAAC;IAExB;;;;OAIG;IACH,aAAa,CAAC,IAAI,IAAI,CAAC;IAEvB;;;;;OAKG;IACH,cAAc,CAAC,IAAI,IAAI,CAAC;IAExB;;;;OAIG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;IAEtB;;;;OAIG;IACH,UAAU,CAAC,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IAEjC;;;;OAIG;IACH,kBAAkB,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1D;;;;;OAKG;IACH,iBAAiB,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1C;;OAEG;IACH,YAAY,CAAC,IAAI,IAAI,CAAC;IAEtB;;OAEG;IACH,cAAc,CAAC,IAAI,IAAI,CAAC;IAExB;;;;OAIG;IACH,eAAe,CAAC,IAAI,IAAI,CAAC;IAEzB;;;;;;OAMG;IACH,kBAAkB,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;CAC1C"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-delegate.js b/lib/platform/web/simple-user/simple-user-delegate.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/simple-user/simple-user-options.d.ts b/lib/platform/web/simple-user/simple-user-options.d.ts deleted file mode 100644 index f5feb00cc..000000000 --- a/lib/platform/web/simple-user/simple-user-options.d.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { UserAgentOptions } from "../../../api"; -import { SimpleUserDelegate } from "./simple-user-delegate"; -/** - * Media for {@link SimpleUserOptions}. - * @public - */ -export interface SimpleUserMedia { - /** - * Offer/Answer constraints determine if audio and/or video are utilized. - * If not specified, only audio is utilized (audio is true, video is false). - * @remarks - * Constraints are used when creating local media stream. - * If undefined, defaults to audio true and video false. - * If audio and video are false, media stream will have no tracks. - */ - constraints?: SimpleUserMediaConstraints; - /** HTML elements for local media streams. */ - local?: SimpleUserMediaLocal; - /** Local HTML media elements. */ - remote?: SimpleUserMediaRemote; -} -/** - * Constraints for {@link SimpleUserMedia}. - * @public - */ -export interface SimpleUserMediaConstraints { - /** If true, offer and answer to send and receive audio. */ - audio: boolean; - /** If true, offer and answer to send and receive video. */ - video: boolean; -} -/** - * Local media elements for {@link SimpleUserMedia}. - * @public - */ -export interface SimpleUserMediaLocal { - /** The local video media stream is attached to this element. */ - video?: HTMLVideoElement; -} -/** - * Remote media elements for {@link SimpleUserMedia}. - * @public - */ -export interface SimpleUserMediaRemote { - /** The remote audio media stream is attached to this element. */ - audio?: HTMLAudioElement; - /** The remote video media stream is attached to this element. */ - video?: HTMLVideoElement; -} -/** - * Options for {@link SimpleUser}. - * @public - */ -export interface SimpleUserOptions { - /** - * User's SIP Address of Record (AOR). - * @remarks - * The AOR is registered to receive incoming calls. - * If not specified, a random anonymous address is created for the user. - */ - aor?: string; - /** - * Delegate for SimpleUser. - */ - delegate?: SimpleUserDelegate; - /** - * Media options. - */ - media?: SimpleUserMedia; - /** - * Maximum number of times to attempt to reconnection. - * @remarks - * When the transport connection is lost (WebSocket disconnects), - * reconnection will be attempted immediately. If that fails, - * reconnection will be attempted again when the browser indicates - * the application has come online. See: - * https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine - * @defaultValue 3 - */ - reconnectionAttempts?: number; - /** - * Seconds to wait between reconnection attempts. - * @defaultValue 4 - */ - reconnectionDelay?: number; - /** - * Options for UserAgent. - */ - userAgentOptions?: UserAgentOptions; -} -//# sourceMappingURL=simple-user-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-options.d.ts.map b/lib/platform/web/simple-user/simple-user-options.d.ts.map deleted file mode 100644 index b904deb68..000000000 --- a/lib/platform/web/simple-user/simple-user-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simple-user-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/simple-user-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,0BAA0B,CAAC;IAEzC,6CAA6C;IAC7C,KAAK,CAAC,EAAE,oBAAoB,CAAC;IAE7B,iCAAiC;IACjC,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA0B;IACzC,2DAA2D;IAC3D,KAAK,EAAE,OAAO,CAAC;IACf,2DAA2D;IAC3D,KAAK,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,gEAAgE;IAChE,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,iEAAiE;IACjE,KAAK,CAAC,EAAE,gBAAgB,CAAC;IACzB,iEAAiE;IACjE,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAE9B;;OAEG;IACH,KAAK,CAAC,EAAE,eAAe,CAAC;IAExB;;;;;;;;;OASG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user-options.js b/lib/platform/web/simple-user/simple-user-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/simple-user/simple-user.d.ts b/lib/platform/web/simple-user/simple-user.d.ts deleted file mode 100644 index 70e4da390..000000000 --- a/lib/platform/web/simple-user/simple-user.d.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { InvitationAcceptOptions, InviterInviteOptions, InviterOptions, RegistererOptions, RegistererRegisterOptions, RegistererUnregisterOptions } from "../../../api"; -import { SimpleUserDelegate } from "./simple-user-delegate"; -import { SimpleUserOptions } from "./simple-user-options"; -/** - * A simple SIP user class. - * @remarks - * While this class is completely functional for simple use cases, it is not intended - * to provide an interface which is suitable for most (must less all) applications. - * While this class has many limitations (for example, it only handles a single concurrent session), - * it is, however, intended to serve as a simple example of using the SIP.js API. - * @public - */ -export declare class SimpleUser { - /** Delegate. */ - delegate: SimpleUserDelegate | undefined; - private attemptingReconnection; - private connectRequested; - private logger; - private held; - private options; - private registerer; - private registerRequested; - private session; - private userAgent; - /** - * Constructs a new instance of the `SimpleUser` class. - * @param server - SIP WebSocket Server URL. - * @param options - Options bucket. See {@link SimpleUserOptions} for details. - */ - constructor(server: string, options?: SimpleUserOptions); - /** - * Instance identifier. - * @internal - */ - get id(): string; - /** The local media stream. Undefined if call not answered. */ - get localMediaStream(): MediaStream | undefined; - /** The remote media stream. Undefined if call not answered. */ - get remoteMediaStream(): MediaStream | undefined; - /** - * The local audio track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localAudioTrack(): MediaStreamTrack | undefined; - /** - * The local video track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localVideoTrack(): MediaStreamTrack | undefined; - /** - * The remote audio track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteAudioTrack(): MediaStreamTrack | undefined; - /** - * The remote video track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteVideoTrack(): MediaStreamTrack | undefined; - /** - * Connect. - * @remarks - * Start the UserAgent's WebSocket Transport. - */ - connect(): Promise; - /** - * Disconnect. - * @remarks - * Stop the UserAgent's WebSocket Transport. - */ - disconnect(): Promise; - /** - * Return true if connected. - */ - isConnected(): boolean; - /** - * Start receiving incoming calls. - * @remarks - * Send a REGISTER request for the UserAgent's AOR. - * Resolves when the REGISTER request is sent, otherwise rejects. - */ - register(registererOptions?: RegistererOptions, registererRegisterOptions?: RegistererRegisterOptions): Promise; - /** - * Stop receiving incoming calls. - * @remarks - * Send an un-REGISTER request for the UserAgent's AOR. - * Resolves when the un-REGISTER request is sent, otherwise rejects. - */ - unregister(registererUnregisterOptions?: RegistererUnregisterOptions): Promise; - /** - * Make an outgoing call. - * @remarks - * Send an INVITE request to create a new Session. - * Resolves when the INVITE request is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if Session is established. - * @param destination - The target destination to call. A SIP address to send the INVITE to. - * @param inviterOptions - Optional options for Inviter constructor. - * @param inviterInviteOptions - Optional options for Inviter.invite(). - */ - call(destination: string, inviterOptions?: InviterOptions, inviterInviteOptions?: InviterInviteOptions): Promise; - /** - * Hangup a call. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - hangup(): Promise; - /** - * Answer an incoming call. - * @remarks - * Accept an incoming INVITE request creating a new Session. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if and when call is established. - * @param invitationAcceptOptions - Optional options for Inviter.accept(). - */ - answer(invitationAcceptOptions?: InvitationAcceptOptions): Promise; - /** - * Decline an incoming call. - * @remarks - * Reject an incoming INVITE request. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - decline(): Promise; - /** - * Hold call - * @remarks - * Send a re-INVITE with new offer indicating "hold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - hold(): Promise; - /** - * Unhold call. - * @remarks - * Send a re-INVITE with new offer indicating "unhold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - unhold(): Promise; - /** - * Hold state. - * @remarks - * True if session media is on hold. - */ - isHeld(): boolean; - /** - * Mute call. - * @remarks - * Disable sender's media tracks. - */ - mute(): void; - /** - * Unmute call. - * @remarks - * Enable sender's media tracks. - */ - unmute(): void; - /** - * Mute state. - * @remarks - * True if sender's media track is disabled. - */ - isMuted(): boolean; - /** - * Send DTMF. - * @remarks - * Send an INFO request with content type application/dtmf-relay. - * @param tone - Tone to send. - */ - sendDTMF(tone: string): Promise; - /** - * Send a message. - * @remarks - * Send a MESSAGE request. - * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. - */ - message(destination: string, message: string): Promise; - /** Media constraints. */ - private get constraints(); - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - private attemptReconnection; - /** Helper function to remove media from html elements. */ - private cleanupMedia; - /** Helper function to enable/disable media tracks. */ - private enableSenderTracks; - /** - * Setup session delegate and state change handler. - * @param session - Session to setup - * @param referralInviterOptions - Options for any Inviter created as result of a REFER. - */ - private initSession; - /** Helper function to init send then send invite. */ - private sendInvite; - /** - * Puts Session on hold. - * @param hold - Hold on if true, off if false. - */ - private setHold; - /** - * Puts Session on mute. - * @param mute - Mute on if true, off if false. - */ - private setMute; - /** Helper function to attach local media to html elements. */ - private setupLocalMedia; - /** Helper function to attach remote media to html elements. */ - private setupRemoteMedia; - /** - * End a session. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when Session is terminated. - */ - private terminate; -} -//# sourceMappingURL=simple-user.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user.d.ts.map b/lib/platform/web/simple-user/simple-user.d.ts.map deleted file mode 100644 index b57e9c833..000000000 --- a/lib/platform/web/simple-user/simple-user.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simple-user.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/simple-user/simple-user.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAEvB,oBAAoB,EACpB,cAAc,EAKd,iBAAiB,EACjB,yBAAyB,EAEzB,2BAA2B,EAQ5B,MAAM,cAAc,CAAC;AAKtB,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;;;;;;;GAQG;AACH,qBAAa,UAAU;IACrB,gBAAgB;IACT,QAAQ,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAEhD,OAAO,CAAC,sBAAsB,CAAS;IACvC,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,OAAO,CAAkC;IACjD,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;OAIG;gBACS,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB;IAoJ3D;;;OAGG;IACH,IAAI,EAAE,IAAI,MAAM,CAEf;IAED,8DAA8D;IAC9D,IAAI,gBAAgB,IAAI,WAAW,GAAG,SAAS,CAS9C;IAED,+DAA+D;IAC/D,IAAI,iBAAiB,IAAI,WAAW,GAAG,SAAS,CAS/C;IAED;;;OAGG;IACH,IAAI,eAAe,IAAI,gBAAgB,GAAG,SAAS,CAElD;IAED;;;OAGG;IACH,IAAI,eAAe,IAAI,gBAAgB,GAAG,SAAS,CAElD;IAED;;;OAGG;IACH,IAAI,gBAAgB,IAAI,gBAAgB,GAAG,SAAS,CAEnD;IAED;;;OAGG;IACH,IAAI,gBAAgB,IAAI,gBAAgB,GAAG,SAAS,CAEnD;IAED;;;;OAIG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAS/B;;;;OAIG;IACI,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAMlC;;OAEG;IACI,WAAW,IAAI,OAAO;IAI7B;;;;;OAKG;IACI,QAAQ,CACb,iBAAiB,CAAC,EAAE,iBAAiB,EACrC,yBAAyB,CAAC,EAAE,yBAAyB,GACpD,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;;OAKG;IACI,UAAU,CAAC,2BAA2B,CAAC,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC;IAa3F;;;;;;;;;OASG;IACI,IAAI,CACT,WAAW,EAAE,MAAM,EACnB,cAAc,CAAC,EAAE,cAAc,EAC/B,oBAAoB,CAAC,EAAE,oBAAoB,GAC1C,OAAO,CAAC,IAAI,CAAC;IAgChB;;;;;;OAMG;IACI,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;;;;;;OAOG;IACI,MAAM,CAAC,uBAAuB,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC;IAyB/E;;;;;;OAMG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAc/B;;;;;;;OAOG;IACI,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B;;;;;;;OAOG;IACI,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;;;OAIG;IACI,MAAM,IAAI,OAAO;IAIxB;;;;OAIG;IACI,IAAI,IAAI,IAAI;IAKnB;;;;OAIG;IACI,MAAM,IAAI,IAAI;IAKrB;;;;OAIG;IACI,OAAO,IAAI,OAAO;IAKzB;;;;;OAKG;IACI,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6C5C;;;;;OAKG;IACI,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUnE,yBAAyB;IACzB,OAAO,KAAK,WAAW,GAMtB;IAED;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA0D3B,0DAA0D;IAC1D,OAAO,CAAC,YAAY;IAqBpB,sDAAsD;IACtD,OAAO,CAAC,kBAAkB;IAsB1B;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAkInB,qDAAqD;IACrD,OAAO,CAAC,UAAU;IAclB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAiDf;;;OAGG;IACH,OAAO,CAAC,OAAO;IAcf,8DAA8D;IAC9D,OAAO,CAAC,eAAe;IAoBvB,+DAA+D;IAC/D,OAAO,CAAC,gBAAgB;IA6BxB;;;;;;OAMG;IACH,OAAO,CAAC,SAAS;CA+ClB"} \ No newline at end of file diff --git a/lib/platform/web/simple-user/simple-user.js b/lib/platform/web/simple-user/simple-user.js deleted file mode 100644 index 9c548906c..000000000 --- a/lib/platform/web/simple-user/simple-user.js +++ /dev/null @@ -1,907 +0,0 @@ -import { Invitation, Inviter, Messager, Registerer, RegistererState, RequestPendingError, SessionState, UserAgent, UserAgentState } from "../../../api"; -import { holdModifier } from "../modifiers"; -import { SessionDescriptionHandler } from "../session-description-handler"; -import { Transport } from "../transport"; -/** - * A simple SIP user class. - * @remarks - * While this class is completely functional for simple use cases, it is not intended - * to provide an interface which is suitable for most (must less all) applications. - * While this class has many limitations (for example, it only handles a single concurrent session), - * it is, however, intended to serve as a simple example of using the SIP.js API. - * @public - */ -export class SimpleUser { - /** - * Constructs a new instance of the `SimpleUser` class. - * @param server - SIP WebSocket Server URL. - * @param options - Options bucket. See {@link SimpleUserOptions} for details. - */ - constructor(server, options = {}) { - this.attemptingReconnection = false; - this.connectRequested = false; - this.held = false; - this.registerer = undefined; - this.registerRequested = false; - this.session = undefined; - // Delegate - this.delegate = options.delegate; - // Copy options - this.options = Object.assign({}, options); - // UserAgentOptions - const userAgentOptions = Object.assign({}, options.userAgentOptions); - // Transport - if (!userAgentOptions.transportConstructor) { - userAgentOptions.transportConstructor = Transport; - } - // TransportOptions - if (!userAgentOptions.transportOptions) { - userAgentOptions.transportOptions = { - server - }; - } - // URI - if (!userAgentOptions.uri) { - // If an AOR was provided, convert it to a URI - if (options.aor) { - const uri = UserAgent.makeURI(options.aor); - if (!uri) { - throw new Error(`Failed to create valid URI from ${options.aor}`); - } - userAgentOptions.uri = uri; - } - } - // UserAgent - this.userAgent = new UserAgent(userAgentOptions); - // UserAgent's delegate - this.userAgent.delegate = { - // Handle connection with server established - onConnect: () => { - this.logger.log(`[${this.id}] Connected`); - if (this.delegate && this.delegate.onServerConnect) { - this.delegate.onServerConnect(); - } - if (this.registerer && this.registerRequested) { - this.logger.log(`[${this.id}] Registering...`); - this.registerer.register().catch((e) => { - this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`); - this.logger.error(e.toString()); - }); - } - }, - // Handle connection with server lost - onDisconnect: (error) => { - this.logger.log(`[${this.id}] Disconnected`); - if (this.delegate && this.delegate.onServerDisconnect) { - this.delegate.onServerDisconnect(error); - } - if (this.session) { - this.logger.log(`[${this.id}] Hanging up...`); - this.hangup() // cleanup hung calls - .catch((e) => { - this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`); - this.logger.error(e.toString()); - }); - } - if (this.registerer) { - this.logger.log(`[${this.id}] Unregistering...`); - this.registerer - .unregister() // cleanup invalid registrations - .catch((e) => { - this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`); - this.logger.error(e.toString()); - }); - } - // Only attempt to reconnect if network/server dropped the connection. - if (error) { - this.attemptReconnection(); - } - }, - // Handle incoming invitations - onInvite: (invitation) => { - this.logger.log(`[${this.id}] Received INVITE`); - // Guard against a pre-existing session. This implementation only supports one session at a time. - // However an incoming INVITE request may be received at any time and/or while in the process - // of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases. - if (this.session) { - this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`); - invitation - .reject() - .then(() => { - this.logger.log(`[${this.id}] Rejected INVITE`); - }) - .catch((error) => { - this.logger.error(`[${this.id}] Failed to reject INVITE`); - this.logger.error(error.toString()); - }); - return; - } - // Use our configured constraints as options for any Inviter created as result of a REFER - const referralInviterOptions = { - sessionDescriptionHandlerOptions: { constraints: this.constraints } - }; - // Initialize our session - this.initSession(invitation, referralInviterOptions); - // Delegate - if (this.delegate && this.delegate.onCallReceived) { - this.delegate.onCallReceived(); - } - else { - this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`); - invitation - .reject() - .then(() => { - this.logger.log(`[${this.id}] Rejected INVITE`); - }) - .catch((error) => { - this.logger.error(`[${this.id}] Failed to reject INVITE`); - this.logger.error(error.toString()); - }); - } - }, - // Handle incoming messages - onMessage: (message) => { - message.accept().then(() => { - if (this.delegate && this.delegate.onMessageReceived) { - this.delegate.onMessageReceived(message.request.body); - } - }); - } - }; - // Use the SIP.js logger - this.logger = this.userAgent.getLogger("sip.SimpleUser"); - // Monitor network connectivity and attempt reconnection when we come online - window.addEventListener("online", () => { - this.logger.log(`[${this.id}] Online`); - this.attemptReconnection(); - }); - } - /** - * Instance identifier. - * @internal - */ - get id() { - return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous"; - } - /** The local media stream. Undefined if call not answered. */ - get localMediaStream() { - var _a; - const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; - if (!sdh) { - return undefined; - } - if (!(sdh instanceof SessionDescriptionHandler)) { - throw new Error("Session description handler not instance of web SessionDescriptionHandler"); - } - return sdh.localMediaStream; - } - /** The remote media stream. Undefined if call not answered. */ - get remoteMediaStream() { - var _a; - const sdh = (_a = this.session) === null || _a === void 0 ? void 0 : _a.sessionDescriptionHandler; - if (!sdh) { - return undefined; - } - if (!(sdh instanceof SessionDescriptionHandler)) { - throw new Error("Session description handler not instance of web SessionDescriptionHandler"); - } - return sdh.remoteMediaStream; - } - /** - * The local audio track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localAudioTrack() { - var _a; - return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); - } - /** - * The local video track, if available. - * @deprecated Use localMediaStream and get track from the stream. - */ - get localVideoTrack() { - var _a; - return (_a = this.localMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); - } - /** - * The remote audio track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteAudioTrack() { - var _a; - return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "audio"); - } - /** - * The remote video track, if available. - * @deprecated Use remoteMediaStream and get track from the stream. - */ - get remoteVideoTrack() { - var _a; - return (_a = this.remoteMediaStream) === null || _a === void 0 ? void 0 : _a.getTracks().find((track) => track.kind === "video"); - } - /** - * Connect. - * @remarks - * Start the UserAgent's WebSocket Transport. - */ - connect() { - this.logger.log(`[${this.id}] Connecting UserAgent...`); - this.connectRequested = true; - if (this.userAgent.state !== UserAgentState.Started) { - return this.userAgent.start(); - } - return this.userAgent.reconnect(); - } - /** - * Disconnect. - * @remarks - * Stop the UserAgent's WebSocket Transport. - */ - disconnect() { - this.logger.log(`[${this.id}] Disconnecting UserAgent...`); - this.connectRequested = false; - return this.userAgent.stop(); - } - /** - * Return true if connected. - */ - isConnected() { - return this.userAgent.isConnected(); - } - /** - * Start receiving incoming calls. - * @remarks - * Send a REGISTER request for the UserAgent's AOR. - * Resolves when the REGISTER request is sent, otherwise rejects. - */ - register(registererOptions, registererRegisterOptions) { - this.logger.log(`[${this.id}] Registering UserAgent...`); - this.registerRequested = true; - if (!this.registerer) { - this.registerer = new Registerer(this.userAgent, registererOptions); - this.registerer.stateChange.addListener((state) => { - switch (state) { - case RegistererState.Initial: - break; - case RegistererState.Registered: - if (this.delegate && this.delegate.onRegistered) { - this.delegate.onRegistered(); - } - break; - case RegistererState.Unregistered: - if (this.delegate && this.delegate.onUnregistered) { - this.delegate.onUnregistered(); - } - break; - case RegistererState.Terminated: - this.registerer = undefined; - break; - default: - throw new Error("Unknown registerer state."); - } - }); - } - return this.registerer.register(registererRegisterOptions).then(() => { - return; - }); - } - /** - * Stop receiving incoming calls. - * @remarks - * Send an un-REGISTER request for the UserAgent's AOR. - * Resolves when the un-REGISTER request is sent, otherwise rejects. - */ - unregister(registererUnregisterOptions) { - this.logger.log(`[${this.id}] Unregistering UserAgent...`); - this.registerRequested = false; - if (!this.registerer) { - return Promise.resolve(); - } - return this.registerer.unregister(registererUnregisterOptions).then(() => { - return; - }); - } - /** - * Make an outgoing call. - * @remarks - * Send an INVITE request to create a new Session. - * Resolves when the INVITE request is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if Session is established. - * @param destination - The target destination to call. A SIP address to send the INVITE to. - * @param inviterOptions - Optional options for Inviter constructor. - * @param inviterInviteOptions - Optional options for Inviter.invite(). - */ - call(destination, inviterOptions, inviterInviteOptions) { - this.logger.log(`[${this.id}] Beginning Session...`); - if (this.session) { - return Promise.reject(new Error("Session already exists.")); - } - const target = UserAgent.makeURI(destination); - if (!target) { - return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); - } - // Use our configured constraints as InviterOptions if none provided - if (!inviterOptions) { - inviterOptions = {}; - } - if (!inviterOptions.sessionDescriptionHandlerOptions) { - inviterOptions.sessionDescriptionHandlerOptions = {}; - } - if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) { - inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; - } - // Create a new Inviter for the outgoing Session - const inviter = new Inviter(this.userAgent, target, inviterOptions); - // Send INVITE - return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => { - return; - }); - } - /** - * Hangup a call. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - hangup() { - this.logger.log(`[${this.id}] Hangup...`); - return this.terminate(); - } - /** - * Answer an incoming call. - * @remarks - * Accept an incoming INVITE request creating a new Session. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallAnswered` delegate method to determine if and when call is established. - * @param invitationAcceptOptions - Optional options for Inviter.accept(). - */ - answer(invitationAcceptOptions) { - this.logger.log(`[${this.id}] Accepting Invitation...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - if (!(this.session instanceof Invitation)) { - return Promise.reject(new Error("Session not instance of Invitation.")); - } - // Use our configured constraints as InvitationAcceptOptions if none provided - if (!invitationAcceptOptions) { - invitationAcceptOptions = {}; - } - if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) { - invitationAcceptOptions.sessionDescriptionHandlerOptions = {}; - } - if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) { - invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints; - } - return this.session.accept(invitationAcceptOptions); - } - /** - * Decline an incoming call. - * @remarks - * Reject an incoming INVITE request. - * Resolves with the response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when call is ended. - */ - decline() { - this.logger.log(`[${this.id}] rejecting Invitation...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - if (!(this.session instanceof Invitation)) { - return Promise.reject(new Error("Session not instance of Invitation.")); - } - return this.session.reject(); - } - /** - * Hold call - * @remarks - * Send a re-INVITE with new offer indicating "hold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - hold() { - this.logger.log(`[${this.id}] holding session...`); - return this.setHold(true); - } - /** - * Unhold call. - * @remarks - * Send a re-INVITE with new offer indicating "unhold". - * Resolves when the re-INVITE request is sent, otherwise rejects. - * Use `onCallHold` delegate method to determine if request is accepted or rejected. - * See: https://tools.ietf.org/html/rfc6337 - */ - unhold() { - this.logger.log(`[${this.id}] unholding session...`); - return this.setHold(false); - } - /** - * Hold state. - * @remarks - * True if session media is on hold. - */ - isHeld() { - return this.held; - } - /** - * Mute call. - * @remarks - * Disable sender's media tracks. - */ - mute() { - this.logger.log(`[${this.id}] disabling media tracks...`); - this.setMute(true); - } - /** - * Unmute call. - * @remarks - * Enable sender's media tracks. - */ - unmute() { - this.logger.log(`[${this.id}] enabling media tracks...`); - this.setMute(false); - } - /** - * Mute state. - * @remarks - * True if sender's media track is disabled. - */ - isMuted() { - const track = this.localAudioTrack || this.localVideoTrack; - return track ? !track.enabled : false; - } - /** - * Send DTMF. - * @remarks - * Send an INFO request with content type application/dtmf-relay. - * @param tone - Tone to send. - */ - sendDTMF(tone) { - this.logger.log(`[${this.id}] sending DTMF...`); - // As RFC 6086 states, sending DTMF via INFO is not standardized... - // - // Companies have been using INFO messages in order to transport - // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are - // proprietary and have not been standardized. - // https://tools.ietf.org/html/rfc6086#section-2 - // - // It is however widely supported based on this draft: - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 - // Validate tone - if (!/^[0-9A-D#*,]$/.exec(tone)) { - return Promise.reject(new Error("Invalid DTMF tone.")); - } - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - // The UA MUST populate the "application/dtmf-relay" body, as defined - // earlier, with the button pressed and the duration it was pressed - // for. Technically, this actually requires the INFO to be generated - // when the user *releases* the button, however if the user has still - // not released a button after 5 seconds, which is the maximum duration - // supported by this mechanism, the UA should generate the INFO at that - // time. - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3 - this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`); - const dtmf = tone; - const duration = 2000; - const body = { - contentDisposition: "render", - contentType: "application/dtmf-relay", - content: "Signal=" + dtmf + "\r\nDuration=" + duration - }; - const requestOptions = { body }; - return this.session.info({ requestOptions }).then(() => { - return; - }); - } - /** - * Send a message. - * @remarks - * Send a MESSAGE request. - * @param destination - The target destination for the message. A SIP address to send the MESSAGE to. - */ - message(destination, message) { - this.logger.log(`[${this.id}] sending message...`); - const target = UserAgent.makeURI(destination); - if (!target) { - return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`)); - } - return new Messager(this.userAgent, target, message).message(); - } - /** Media constraints. */ - get constraints() { - var _a; - let constraints = { audio: true, video: false }; // default to audio only calls - if ((_a = this.options.media) === null || _a === void 0 ? void 0 : _a.constraints) { - constraints = Object.assign({}, this.options.media.constraints); - } - return constraints; - } - /** - * Attempt reconnection up to `maxReconnectionAttempts` times. - * @param reconnectionAttempt - Current attempt number. - */ - attemptReconnection(reconnectionAttempt = 1) { - const reconnectionAttempts = this.options.reconnectionAttempts || 3; - const reconnectionDelay = this.options.reconnectionDelay || 4; - if (!this.connectRequested) { - this.logger.log(`[${this.id}] Reconnection not currently desired`); - return; // If intentionally disconnected, don't reconnect. - } - if (this.attemptingReconnection) { - this.logger.log(`[${this.id}] Reconnection attempt already in progress`); - } - if (reconnectionAttempt > reconnectionAttempts) { - this.logger.log(`[${this.id}] Reconnection maximum attempts reached`); - return; - } - if (reconnectionAttempt === 1) { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`); - } - else { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`); - } - this.attemptingReconnection = true; - setTimeout(() => { - if (!this.connectRequested) { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`); - this.attemptingReconnection = false; - return; // If intentionally disconnected, don't reconnect. - } - this.userAgent - .reconnect() - .then(() => { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`); - this.attemptingReconnection = false; - }) - .catch((error) => { - this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`); - this.logger.error(error.message); - this.attemptingReconnection = false; - this.attemptReconnection(++reconnectionAttempt); - }); - }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000); - } - /** Helper function to remove media from html elements. */ - cleanupMedia() { - if (this.options.media) { - if (this.options.media.local) { - if (this.options.media.local.video) { - this.options.media.local.video.srcObject = null; - this.options.media.local.video.pause(); - } - } - if (this.options.media.remote) { - if (this.options.media.remote.audio) { - this.options.media.remote.audio.srcObject = null; - this.options.media.remote.audio.pause(); - } - if (this.options.media.remote.video) { - this.options.media.remote.video.srcObject = null; - this.options.media.remote.video.pause(); - } - } - } - } - /** Helper function to enable/disable media tracks. */ - enableSenderTracks(enable) { - if (!this.session) { - throw new Error("Session does not exist."); - } - const sessionDescriptionHandler = this.session.sessionDescriptionHandler; - if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { - throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); - } - const peerConnection = sessionDescriptionHandler.peerConnection; - if (!peerConnection) { - throw new Error("Peer connection closed."); - } - peerConnection.getSenders().forEach((sender) => { - if (sender.track) { - sender.track.enabled = enable; - } - }); - } - /** - * Setup session delegate and state change handler. - * @param session - Session to setup - * @param referralInviterOptions - Options for any Inviter created as result of a REFER. - */ - initSession(session, referralInviterOptions) { - // Set session - this.session = session; - // Call session created callback - if (this.delegate && this.delegate.onCallCreated) { - this.delegate.onCallCreated(); - } - // Setup session state change handler - this.session.stateChange.addListener((state) => { - if (this.session !== session) { - return; // if our session has changed, just return - } - this.logger.log(`[${this.id}] session state changed to ${state}`); - switch (state) { - case SessionState.Initial: - break; - case SessionState.Establishing: - break; - case SessionState.Established: - this.setupLocalMedia(); - this.setupRemoteMedia(); - if (this.delegate && this.delegate.onCallAnswered) { - this.delegate.onCallAnswered(); - } - break; - case SessionState.Terminating: - // fall through - case SessionState.Terminated: - this.session = undefined; - this.cleanupMedia(); - if (this.delegate && this.delegate.onCallHangup) { - this.delegate.onCallHangup(); - } - break; - default: - throw new Error("Unknown session state."); - } - }); - // Setup delegate - this.session.delegate = { - onInfo: (info) => { - // As RFC 6086 states, sending DTMF via INFO is not standardized... - // - // Companies have been using INFO messages in order to transport - // Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are - // proprietary and have not been standardized. - // https://tools.ietf.org/html/rfc6086#section-2 - // - // It is however widely supported based on this draft: - // https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00 - var _a; - // FIXME: TODO: We should reject correctly... - // - // If a UA receives an INFO request associated with an Info Package that - // the UA has not indicated willingness to receive, the UA MUST send a - // 469 (Bad Info Package) response (see Section 11.6), which contains a - // Recv-Info header field with Info Packages for which the UA is willing - // to receive INFO requests. - // https://tools.ietf.org/html/rfc6086#section-4.2.2 - // No delegate - if (((_a = this.delegate) === null || _a === void 0 ? void 0 : _a.onCallDTMFReceived) === undefined) { - info.reject(); - return; - } - // Invalid content type - const contentType = info.request.getHeader("content-type"); - if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) { - info.reject(); - return; - } - // Invalid body - const body = info.request.body.split("\r\n", 2); - if (body.length !== 2) { - info.reject(); - return; - } - // Invalid tone - let tone; - const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/; - if (toneRegExp.test(body[0])) { - tone = body[0].replace(toneRegExp, "$2"); - } - if (!tone) { - info.reject(); - return; - } - // Invalid duration - let duration; - const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - if (durationRegExp.test(body[1])) { - duration = parseInt(body[1].replace(durationRegExp, "$2"), 10); - } - if (!duration) { - info.reject(); - return; - } - info - .accept() - .then(() => { - if (this.delegate && this.delegate.onCallDTMFReceived) { - if (!tone || !duration) { - throw new Error("Tone or duration undefined."); - } - this.delegate.onCallDTMFReceived(tone, duration); - } - }) - .catch((error) => { - this.logger.error(error.message); - }); - }, - onRefer: (referral) => { - referral - .accept() - .then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions)) - .catch((error) => { - this.logger.error(error.message); - }); - } - }; - } - /** Helper function to init send then send invite. */ - sendInvite(inviter, inviterOptions, inviterInviteOptions) { - // Initialize our session - this.initSession(inviter, inviterOptions); - // Send the INVITE - return inviter.invite(inviterInviteOptions).then(() => { - this.logger.log(`[${this.id}] sent INVITE`); - }); - } - /** - * Puts Session on hold. - * @param hold - Hold on if true, off if false. - */ - setHold(hold) { - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - // Just resolve if we are already in correct state - if (this.held === hold) { - return Promise.resolve(); - } - const sessionDescriptionHandler = this.session.sessionDescriptionHandler; - if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) { - throw new Error("Session's session description handler not instance of SessionDescriptionHandler."); - } - const options = { - requestDelegate: { - onAccept: () => { - this.held = hold; - if (this.delegate && this.delegate.onCallHold) { - this.delegate.onCallHold(this.held); - } - }, - onReject: () => { - this.logger.warn(`[${this.id}] re-invite request was rejected`); - if (this.delegate && this.delegate.onCallHold) { - this.delegate.onCallHold(this.held); - } - } - } - }; - // Use hold modifier to produce the appropriate SDP offer to place call on hold - options.sessionDescriptionHandlerModifiers = hold ? [holdModifier] : []; - // Send re-INVITE - return this.session - .invite(options) - .then(() => { - this.enableSenderTracks(!hold); // mute/unmute - }) - .catch((error) => { - if (error instanceof RequestPendingError) { - this.logger.error(`[${this.id}] A hold request is already in progress.`); - } - throw error; - }); - } - /** - * Puts Session on mute. - * @param mute - Mute on if true, off if false. - */ - setMute(mute) { - if (!this.session) { - this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`); - return; - } - if (this.session.state !== SessionState.Established) { - this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`); - return; - } - this.enableSenderTracks(!mute); - } - /** Helper function to attach local media to html elements. */ - setupLocalMedia() { - var _a, _b; - if (!this.session) { - throw new Error("Session does not exist."); - } - const mediaElement = (_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.local) === null || _b === void 0 ? void 0 : _b.video; - if (mediaElement) { - const localStream = this.localMediaStream; - if (!localStream) { - throw new Error("Local media stream undefiend."); - } - mediaElement.srcObject = localStream; - mediaElement.volume = 0; - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play local media`); - this.logger.error(error.message); - }); - } - } - /** Helper function to attach remote media to html elements. */ - setupRemoteMedia() { - var _a, _b, _c, _d; - if (!this.session) { - throw new Error("Session does not exist."); - } - const mediaElement = ((_b = (_a = this.options.media) === null || _a === void 0 ? void 0 : _a.remote) === null || _b === void 0 ? void 0 : _b.video) || ((_d = (_c = this.options.media) === null || _c === void 0 ? void 0 : _c.remote) === null || _d === void 0 ? void 0 : _d.audio); - if (mediaElement) { - const remoteStream = this.remoteMediaStream; - if (!remoteStream) { - throw new Error("Remote media stream undefiend."); - } - mediaElement.autoplay = true; // Safari hack, because you cannot call .play() from a non user action - mediaElement.srcObject = remoteStream; - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play remote media`); - this.logger.error(error.message); - }); - remoteStream.onaddtrack = () => { - this.logger.log(`[${this.id}] Remote media onaddtrack`); - mediaElement.load(); // Safari hack, as it doesn't work otheriwse - mediaElement.play().catch((error) => { - this.logger.error(`[${this.id}] Failed to play remote media`); - this.logger.error(error.message); - }); - }; - } - } - /** - * End a session. - * @remarks - * Send a BYE request, CANCEL request or reject response to end the current Session. - * Resolves when the request/response is sent, otherwise rejects. - * Use `onCallTerminated` delegate method to determine if and when Session is terminated. - */ - terminate() { - this.logger.log(`[${this.id}] Terminating...`); - if (!this.session) { - return Promise.reject(new Error("Session does not exist.")); - } - switch (this.session.state) { - case SessionState.Initial: - if (this.session instanceof Inviter) { - return this.session.cancel().then(() => { - this.logger.log(`[${this.id}] Inviter never sent INVITE (canceled)`); - }); - } - else if (this.session instanceof Invitation) { - return this.session.reject().then(() => { - this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); - }); - } - else { - throw new Error("Unknown session type."); - } - case SessionState.Establishing: - if (this.session instanceof Inviter) { - return this.session.cancel().then(() => { - this.logger.log(`[${this.id}] Inviter canceled (sent CANCEL)`); - }); - } - else if (this.session instanceof Invitation) { - return this.session.reject().then(() => { - this.logger.log(`[${this.id}] Invitation rejected (sent 480)`); - }); - } - else { - throw new Error("Unknown session type."); - } - case SessionState.Established: - return this.session.bye().then(() => { - this.logger.log(`[${this.id}] Session ended (sent BYE)`); - }); - case SessionState.Terminating: - break; - case SessionState.Terminated: - break; - default: - throw new Error("Unknown state"); - } - this.logger.log(`[${this.id}] Terminating in state ${this.session.state}, no action taken`); - return Promise.resolve(); - } -} diff --git a/lib/platform/web/transport/index.d.ts b/lib/platform/web/transport/index.d.ts deleted file mode 100644 index 9744fd081..000000000 --- a/lib/platform/web/transport/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * A Transport implementation for web browsers. - * @packageDocumentation - */ -export * from "./transport"; -export * from "./transport-options"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/transport/index.d.ts.map b/lib/platform/web/transport/index.d.ts.map deleted file mode 100644 index 8147590c0..000000000 --- a/lib/platform/web/transport/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/transport/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC"} \ No newline at end of file diff --git a/lib/platform/web/transport/index.js b/lib/platform/web/transport/index.js deleted file mode 100644 index a7ef71939..000000000 --- a/lib/platform/web/transport/index.js +++ /dev/null @@ -1,6 +0,0 @@ -/** - * A Transport implementation for web browsers. - * @packageDocumentation - */ -export * from "./transport"; -export * from "./transport-options"; diff --git a/lib/platform/web/transport/transport-options.d.ts b/lib/platform/web/transport/transport-options.d.ts deleted file mode 100644 index 7c8b34088..000000000 --- a/lib/platform/web/transport/transport-options.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Transport options. - * @public - */ -export interface TransportOptions { - /** - * URL of WebSocket server to connect with. For example, "wss://localhost:8080". - */ - server: string; - /** - * Seconds to wait for WebSocket to connect before giving up. - * @defaultValue `5` - */ - connectionTimeout?: number; - /** - * Keep alive - needs review. - * @internal - */ - keepAliveInterval?: number; - /** - * Keep alive - needs review. - * @internal - */ - keepAliveDebounce?: number; - /** - * If true, messages sent and received by the transport are logged. - * @defaultValue `true` - */ - traceSip?: boolean; -} -//# sourceMappingURL=transport-options.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/transport/transport-options.d.ts.map b/lib/platform/web/transport/transport-options.d.ts.map deleted file mode 100644 index 2d23e8cfc..000000000 --- a/lib/platform/web/transport/transport-options.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport-options.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/transport/transport-options.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB"} \ No newline at end of file diff --git a/lib/platform/web/transport/transport-options.js b/lib/platform/web/transport/transport-options.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/platform/web/transport/transport.d.ts b/lib/platform/web/transport/transport.d.ts deleted file mode 100644 index 31621fbf2..000000000 --- a/lib/platform/web/transport/transport.d.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { Emitter } from "../../../api/emitter"; -import { Transport as TransportDefinition } from "../../../api/transport"; -import { TransportState } from "../../../api/transport-state"; -import { Logger } from "../../../core"; -import { TransportOptions } from "./transport-options"; -/** - * Transport for SIP over secure WebSocket (WSS). - * @public - */ -export declare class Transport implements TransportDefinition { - private static defaultOptions; - onConnect: (() => void) | undefined; - onDisconnect: ((error?: Error) => void) | undefined; - onMessage: ((message: string) => void) | undefined; - private _protocol; - private _state; - private _stateEventEmitter; - private _ws; - private configuration; - private connectPromise; - private connectResolve; - private connectReject; - private connectTimeout; - private disconnectPromise; - private disconnectResolve; - private disconnectReject; - private keepAliveInterval; - private keepAliveDebounceTimeout; - private logger; - private transitioningState; - constructor(logger: Logger, options?: TransportOptions); - dispose(): Promise; - /** - * The protocol. - * - * @remarks - * Formatted as defined for the Via header sent-protocol transport. - * https://tools.ietf.org/html/rfc3261#section-20.42 - */ - get protocol(): string; - /** - * The URL of the WebSocket Server. - */ - get server(): string; - /** - * Transport state. - */ - get state(): TransportState; - /** - * Transport state change emitter. - */ - get stateChange(): Emitter; - /** - * The WebSocket. - */ - get ws(): WebSocket | undefined; - /** - * Connect to network. - * Resolves once connected. Otherwise rejects with an Error. - */ - connect(): Promise; - /** - * Disconnect from network. - * Resolves once disconnected. Otherwise rejects with an Error. - */ - disconnect(): Promise; - /** - * Returns true if the `state` equals "Connected". - * @remarks - * This is equivalent to `state === TransportState.Connected`. - */ - isConnected(): boolean; - /** - * Sends a message. - * Resolves once message is sent. Otherwise rejects with an Error. - * @param message - Message to send. - */ - send(message: string): Promise; - private _connect; - private _disconnect; - private _send; - /** - * WebSocket "onclose" event handler. - * @param ev - Event. - */ - private onWebSocketClose; - /** - * WebSocket "onerror" event handler. - * @param ev - Event. - */ - private onWebSocketError; - /** - * WebSocket "onmessage" event handler. - * @param ev - Event. - */ - private onWebSocketMessage; - /** - * WebSocket "onopen" event handler. - * @param ev - Event. - */ - private onWebSocketOpen; - /** - * Helper function to generate an Error. - * @param state - State transitioning to. - */ - private transitionLoopDetectedError; - /** - * Transition transport state. - * @internal - */ - private transitionState; - private clearKeepAliveTimeout; - /** - * Send a keep-alive (a double-CRLF sequence). - */ - private sendKeepAlive; - /** - * Start sending keep-alives. - */ - private startSendingKeepAlives; - /** - * Stop sending keep-alives. - */ - private stopSendingKeepAlives; -} -//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/lib/platform/web/transport/transport.d.ts.map b/lib/platform/web/transport/transport.d.ts.map deleted file mode 100644 index 89e8b2ec9..000000000 --- a/lib/platform/web/transport/transport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../../src/platform/web/transport/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAe,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,SAAS,IAAI,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAW,MAAM,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;GAGG;AACH,qBAAa,SAAU,YAAW,mBAAmB;IACnD,OAAO,CAAC,MAAM,CAAC,cAAc,CAM3B;IAEK,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IACpC,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACpD,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAE1D,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,MAAM,CAA+C;IAC7D,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,GAAG,CAAwB;IAEnC,OAAO,CAAC,aAAa,CAA6B;IAElD,OAAO,CAAC,cAAc,CAA4B;IAClD,OAAO,CAAC,cAAc,CAA2B;IACjD,OAAO,CAAC,aAAa,CAAuC;IAC5D,OAAO,CAAC,cAAc,CAAqB;IAE3C,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,iBAAiB,CAA2B;IACpD,OAAO,CAAC,gBAAgB,CAAwC;IAEhE,OAAO,CAAC,iBAAiB,CAAqB;IAC9C,OAAO,CAAC,wBAAwB,CAAqB;IAErD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,kBAAkB,CAAS;gBAEvB,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB;IA0D/C,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B;;;;;;OAMG;IACH,IAAW,QAAQ,IAAI,MAAM,CAE5B;IAED;;OAEG;IACH,IAAW,MAAM,IAAI,MAAM,CAE1B;IAED;;OAEG;IACH,IAAW,KAAK,IAAI,cAAc,CAEjC;IAED;;OAEG;IACH,IAAW,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAEhD;IAED;;OAEG;IACH,IAAW,EAAE,IAAI,SAAS,GAAG,SAAS,CAErC;IAED;;;OAGG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B;;;OAGG;IACI,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAIlC;;;;OAIG;IACI,WAAW,IAAI,OAAO;IAI7B;;;;OAIG;IACI,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB3C,OAAO,CAAC,QAAQ;IA+FhB,OAAO,CAAC,WAAW;IA+EnB,OAAO,CAAC,KAAK;IA2Bb;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAmBxB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAOxB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA8D1B;;;OAGG;IACH,OAAO,CAAC,eAAe;IAUvB;;;OAGG;IACH,OAAO,CAAC,2BAA2B;IAQnC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAiKvB,OAAO,CAAC,qBAAqB;IAO7B;;OAEG;IACH,OAAO,CAAC,aAAa;IAarB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAe9B;;OAEG;IACH,OAAO,CAAC,qBAAqB;CAU9B"} \ No newline at end of file diff --git a/lib/platform/web/transport/transport.js b/lib/platform/web/transport/transport.js deleted file mode 100644 index ae7600e49..000000000 --- a/lib/platform/web/transport/transport.js +++ /dev/null @@ -1,648 +0,0 @@ -import { EmitterImpl } from "../../../api/emitter"; -import { StateTransitionError } from "../../../api/exceptions"; -import { TransportState } from "../../../api/transport-state"; -import { Grammar } from "../../../core"; -/** - * Transport for SIP over secure WebSocket (WSS). - * @public - */ -export class Transport { - constructor(logger, options) { - this._state = TransportState.Disconnected; - this.transitioningState = false; - // state emitter - this._stateEventEmitter = new EmitterImpl(); - // logger - this.logger = logger; - // guard deprecated options (remove this in version 16.x) - if (options) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const optionsDeprecated = options; - const wsServersDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.wsServers; - const maxReconnectionAttemptsDeprecated = optionsDeprecated === null || optionsDeprecated === void 0 ? void 0 : optionsDeprecated.maxReconnectionAttempts; - if (wsServersDeprecated !== undefined) { - const deprecatedMessage = `The transport option "wsServers" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - if (maxReconnectionAttemptsDeprecated !== undefined) { - const deprecatedMessage = `The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. ` + - "It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly."; - this.logger.warn(deprecatedMessage); - } - // hack - if (wsServersDeprecated && !options.server) { - if (typeof wsServersDeprecated === "string") { - options.server = wsServersDeprecated; - } - if (wsServersDeprecated instanceof Array) { - options.server = wsServersDeprecated[0]; - } - } - } - // initialize configuration - this.configuration = Object.assign(Object.assign({}, Transport.defaultOptions), options); - // validate server URL - const url = this.configuration.server; - const parsed = Grammar.parse(url, "absoluteURI"); - if (parsed === -1) { - this.logger.error(`Invalid WebSocket Server URL "${url}"`); - throw new Error("Invalid WebSocket Server URL"); - } - if (!["wss", "ws", "udp"].includes(parsed.scheme)) { - this.logger.error(`Invalid scheme in WebSocket Server URL "${url}"`); - throw new Error("Invalid scheme in WebSocket Server URL"); - } - this._protocol = parsed.scheme.toUpperCase(); - } - dispose() { - return this.disconnect(); - } - /** - * The protocol. - * - * @remarks - * Formatted as defined for the Via header sent-protocol transport. - * https://tools.ietf.org/html/rfc3261#section-20.42 - */ - get protocol() { - return this._protocol; - } - /** - * The URL of the WebSocket Server. - */ - get server() { - return this.configuration.server; - } - /** - * Transport state. - */ - get state() { - return this._state; - } - /** - * Transport state change emitter. - */ - get stateChange() { - return this._stateEventEmitter; - } - /** - * The WebSocket. - */ - get ws() { - return this._ws; - } - /** - * Connect to network. - * Resolves once connected. Otherwise rejects with an Error. - */ - connect() { - return this._connect(); - } - /** - * Disconnect from network. - * Resolves once disconnected. Otherwise rejects with an Error. - */ - disconnect() { - return this._disconnect(); - } - /** - * Returns true if the `state` equals "Connected". - * @remarks - * This is equivalent to `state === TransportState.Connected`. - */ - isConnected() { - return this.state === TransportState.Connected; - } - /** - * Sends a message. - * Resolves once message is sent. Otherwise rejects with an Error. - * @param message - Message to send. - */ - send(message) { - // Error handling is independent of whether the message was a request or - // response. - // - // If the transport user asks for a message to be sent over an - // unreliable transport, and the result is an ICMP error, the behavior - // depends on the type of ICMP error. Host, network, port or protocol - // unreachable errors, or parameter problem errors SHOULD cause the - // transport layer to inform the transport user of a failure in sending. - // Source quench and TTL exceeded ICMP errors SHOULD be ignored. - // - // If the transport user asks for a request to be sent over a reliable - // transport, and the result is a connection failure, the transport - // layer SHOULD inform the transport user of a failure in sending. - // https://tools.ietf.org/html/rfc3261#section-18.4 - return this._send(message); - } - _connect() { - this.logger.log(`Connecting ${this.server}`); - switch (this.state) { - case TransportState.Connecting: - // If `state` is "Connecting", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting)); - } - if (!this.connectPromise) { - throw new Error("Connect promise must be defined."); - } - return this.connectPromise; // Already connecting - case TransportState.Connected: - // If `state` is "Connected", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting)); - } - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - return Promise.resolve(); // Already connected - case TransportState.Disconnecting: - // If `state` is "Disconnecting", `state` MUST transition to "Connecting" before returning - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - try { - this.transitionState(TransportState.Connecting); - } - catch (e) { - if (e instanceof StateTransitionError) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case TransportState.Disconnected: - // If `state` is "Disconnected" `state` MUST transition to "Connecting" before returning - if (this.connectPromise) { - throw new Error("Connect promise must not be defined."); - } - try { - this.transitionState(TransportState.Connecting); - } - catch (e) { - if (e instanceof StateTransitionError) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - default: - throw new Error("Unknown state"); - } - let ws; - try { - // WebSocket() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket - ws = new WebSocket(this.server, "sip"); - ws.binaryType = "arraybuffer"; // set data type of received binary messages - ws.addEventListener("close", (ev) => this.onWebSocketClose(ev, ws)); - ws.addEventListener("error", (ev) => this.onWebSocketError(ev, ws)); - ws.addEventListener("open", (ev) => this.onWebSocketOpen(ev, ws)); - ws.addEventListener("message", (ev) => this.onWebSocketMessage(ev, ws)); - this._ws = ws; - } - catch (error) { - this._ws = undefined; - this.logger.error("WebSocket construction failed."); - this.logger.error(error); - return new Promise((resolve, reject) => { - this.connectResolve = resolve; - this.connectReject = reject; - // The `state` MUST transition to "Disconnecting" or "Disconnected" before rejecting - this.transitionState(TransportState.Disconnected, error); - }); - } - this.connectPromise = new Promise((resolve, reject) => { - this.connectResolve = resolve; - this.connectReject = reject; - this.connectTimeout = setTimeout(() => { - this.logger.warn("Connect timed out. " + - "Exceeded time set in configuration.connectionTimeout: " + - this.configuration.connectionTimeout + - "s."); - ws.close(1000); // careful here to use a local reference instead of this._ws - }, this.configuration.connectionTimeout * 1000); - }); - return this.connectPromise; - } - _disconnect() { - this.logger.log(`Disconnecting ${this.server}`); - switch (this.state) { - case TransportState.Connecting: - // If `state` is "Connecting", `state` MUST transition to "Disconnecting" before returning. - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - try { - this.transitionState(TransportState.Disconnecting); - } - catch (e) { - if (e instanceof StateTransitionError) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case TransportState.Connected: - // If `state` is "Connected", `state` MUST transition to "Disconnecting" before returning. - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - try { - this.transitionState(TransportState.Disconnecting); - } - catch (e) { - if (e instanceof StateTransitionError) { - return Promise.reject(e); // Loop detected - } - throw e; - } - break; - case TransportState.Disconnecting: - // If `state` is "Disconnecting", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting)); - } - if (!this.disconnectPromise) { - throw new Error("Disconnect promise must be defined."); - } - return this.disconnectPromise; // Already disconnecting - case TransportState.Disconnected: - // If `state` is "Disconnected", `state` MUST NOT transition before returning. - if (this.transitioningState) { - return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting)); - } - if (this.disconnectPromise) { - throw new Error("Disconnect promise must not be defined."); - } - return Promise.resolve(); // Already disconnected - default: - throw new Error("Unknown state"); - } - if (!this._ws) { - throw new Error("WebSocket must be defined."); - } - const ws = this._ws; - this.disconnectPromise = new Promise((resolve, reject) => { - this.disconnectResolve = resolve; - this.disconnectReject = reject; - try { - // WebSocket.close() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close - ws.close(1000); // careful here to use a local reference instead of this._ws - } - catch (error) { - // Treating this as a coding error as it apparently can only happen - // if you pass close() invalid parameters (so it should never happen) - this.logger.error("WebSocket close failed."); - this.logger.error(error); - throw error; - } - }); - return this.disconnectPromise; - } - _send(message) { - if (this.configuration.traceSip === true) { - this.logger.log("Sending WebSocket message:\n\n" + message + "\n"); - } - if (this._state !== TransportState.Connected) { - return Promise.reject(new Error("Not connected.")); - } - if (!this._ws) { - throw new Error("WebSocket undefined."); - } - try { - // WebSocket.send() - // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send - this._ws.send(message); - } - catch (error) { - if (error instanceof Error) { - return Promise.reject(error); - } - return Promise.reject(new Error("WebSocket send failed.")); - } - return Promise.resolve(); - } - /** - * WebSocket "onclose" event handler. - * @param ev - Event. - */ - onWebSocketClose(ev, ws) { - if (ws !== this._ws) { - return; - } - const message = `WebSocket closed ${this.server} (code: ${ev.code})`; - const error = !this.disconnectPromise ? new Error(message) : undefined; - if (error) { - this.logger.warn("WebSocket closed unexpectedly"); - } - this.logger.log(message); - // We are about to transition to disconnected, so clear our web socket - this._ws = undefined; - // The `state` MUST transition to "Disconnected" before resolving (assuming `state` is not already "Disconnected"). - this.transitionState(TransportState.Disconnected, error); - } - /** - * WebSocket "onerror" event handler. - * @param ev - Event. - */ - onWebSocketError(ev, ws) { - if (ws !== this._ws) { - return; - } - this.logger.error("WebSocket error occurred."); - } - /** - * WebSocket "onmessage" event handler. - * @param ev - Event. - */ - onWebSocketMessage(ev, ws) { - if (ws !== this._ws) { - return; - } - const data = ev.data; - let finishedData; - // CRLF Keep Alive response from server. Clear our keep alive timeout. - if (/^(\r\n)+$/.test(data)) { - this.clearKeepAliveTimeout(); - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket message with CRLF Keep Alive response"); - } - return; - } - if (!data) { - this.logger.warn("Received empty message, discarding..."); - return; - } - if (typeof data !== "string") { - // WebSocket binary message. - try { - finishedData = new TextDecoder().decode(new Uint8Array(data)); - // TextDecoder (above) is not supported by old browsers, but it correctly decodes UTF-8. - // The line below is an ISO 8859-1 (Latin 1) decoder, so just UTF-8 code points that are 1 byte. - // It's old code and works in old browsers (IE), so leaving it here in a comment in case someone needs it. - // finishedData = String.fromCharCode.apply(null, (new Uint8Array(data) as unknown as Array)); - } - catch (err) { - this.logger.error(err); - this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded"); - return; - } - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket binary message:\n\n" + finishedData + "\n"); - } - } - else { - // WebSocket text message. - finishedData = data; - if (this.configuration.traceSip === true) { - this.logger.log("Received WebSocket text message:\n\n" + finishedData + "\n"); - } - } - if (this.state !== TransportState.Connected) { - this.logger.warn("Received message while not connected, discarding..."); - return; - } - if (this.onMessage) { - try { - this.onMessage(finishedData); - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onMessage callback"); - throw e; // rethrow unhandled exception - } - } - } - /** - * WebSocket "onopen" event handler. - * @param ev - Event. - */ - onWebSocketOpen(ev, ws) { - if (ws !== this._ws) { - return; - } - if (this._state === TransportState.Connecting) { - this.logger.log(`WebSocket opened ${this.server}`); - this.transitionState(TransportState.Connected); - } - } - /** - * Helper function to generate an Error. - * @param state - State transitioning to. - */ - transitionLoopDetectedError(state) { - let message = `A state transition loop has been detected.`; - message += ` An attempt to transition from ${this._state} to ${state} before the prior transition completed.`; - message += ` Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?`; - this.logger.error(message); - return new StateTransitionError("Loop detected."); - } - /** - * Transition transport state. - * @internal - */ - transitionState(newState, error) { - const invalidTransition = () => { - throw new Error(`Invalid state transition from ${this._state} to ${newState}`); - }; - if (this.transitioningState) { - throw this.transitionLoopDetectedError(newState); - } - this.transitioningState = true; - // Validate state transition - switch (this._state) { - case TransportState.Connecting: - if (newState !== TransportState.Connected && - newState !== TransportState.Disconnecting && - newState !== TransportState.Disconnected) { - invalidTransition(); - } - break; - case TransportState.Connected: - if (newState !== TransportState.Disconnecting && newState !== TransportState.Disconnected) { - invalidTransition(); - } - break; - case TransportState.Disconnecting: - if (newState !== TransportState.Connecting && newState !== TransportState.Disconnected) { - invalidTransition(); - } - break; - case TransportState.Disconnected: - if (newState !== TransportState.Connecting) { - invalidTransition(); - } - break; - default: - throw new Error("Unknown state."); - } - // Update state - const oldState = this._state; - this._state = newState; - // Local copies of connect promises (guarding against callbacks changing them indirectly) - // const connectPromise = this.connectPromise; - const connectResolve = this.connectResolve; - const connectReject = this.connectReject; - // Reset connect promises if no longer connecting - if (oldState === TransportState.Connecting) { - this.connectPromise = undefined; - this.connectResolve = undefined; - this.connectReject = undefined; - } - // Local copies of disconnect promises (guarding against callbacks changing them indirectly) - // const disconnectPromise = this.disconnectPromise; - const disconnectResolve = this.disconnectResolve; - const disconnectReject = this.disconnectReject; - // Reset disconnect promises if no longer disconnecting - if (oldState === TransportState.Disconnecting) { - this.disconnectPromise = undefined; - this.disconnectResolve = undefined; - this.disconnectReject = undefined; - } - // Clear any outstanding connect timeout - if (this.connectTimeout) { - clearTimeout(this.connectTimeout); - this.connectTimeout = undefined; - } - this.logger.log(`Transitioned from ${oldState} to ${this._state}`); - this._stateEventEmitter.emit(this._state); - // Transition to Connected - if (newState === TransportState.Connected) { - this.startSendingKeepAlives(); - if (this.onConnect) { - try { - this.onConnect(); - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onConnect callback"); - throw e; // rethrow unhandled exception - } - } - } - // Transition from Connected - if (oldState === TransportState.Connected) { - this.stopSendingKeepAlives(); - if (this.onDisconnect) { - try { - if (error) { - this.onDisconnect(error); - } - else { - this.onDisconnect(); - } - } - catch (e) { - this.logger.error(e); - this.logger.error("Exception thrown by onDisconnect callback"); - throw e; // rethrow unhandled exception - } - } - } - // Complete connect promise - if (oldState === TransportState.Connecting) { - if (!connectResolve) { - throw new Error("Connect resolve undefined."); - } - if (!connectReject) { - throw new Error("Connect reject undefined."); - } - newState === TransportState.Connected ? connectResolve() : connectReject(error || new Error("Connect aborted.")); - } - // Complete disconnect promise - if (oldState === TransportState.Disconnecting) { - if (!disconnectResolve) { - throw new Error("Disconnect resolve undefined."); - } - if (!disconnectReject) { - throw new Error("Disconnect reject undefined."); - } - newState === TransportState.Disconnected - ? disconnectResolve() - : disconnectReject(error || new Error("Disconnect aborted.")); - } - this.transitioningState = false; - } - // TODO: Review "KeepAlive Stuff". - // It is not clear if it works and there are no tests for it. - // It was blindly lifted the keep alive code unchanged from earlier transport code. - // - // From the RFC... - // - // SIP WebSocket Clients and Servers may keep their WebSocket - // connections open by sending periodic WebSocket "Ping" frames as - // described in [RFC6455], Section 5.5.2. - // ... - // The indication and use of the CRLF NAT keep-alive mechanism defined - // for SIP connection-oriented transports in [RFC5626], Section 3.5.1 or - // [RFC6223] are, of course, usable over the transport defined in this - // specification. - // https://tools.ietf.org/html/rfc7118#section-6 - // - // and... - // - // The Ping frame contains an opcode of 0x9. - // https://tools.ietf.org/html/rfc6455#section-5.5.2 - // - // ============================== - // KeepAlive Stuff - // ============================== - clearKeepAliveTimeout() { - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveDebounceTimeout = undefined; - } - /** - * Send a keep-alive (a double-CRLF sequence). - */ - sendKeepAlive() { - if (this.keepAliveDebounceTimeout) { - // We already have an outstanding keep alive, do not send another. - return Promise.resolve(); - } - this.keepAliveDebounceTimeout = setTimeout(() => { - this.clearKeepAliveTimeout(); - }, this.configuration.keepAliveDebounce * 1000); - return this.send("\r\n\r\n"); - } - /** - * Start sending keep-alives. - */ - startSendingKeepAlives() { - // Compute an amount of time in seconds to wait before sending another keep-alive. - const computeKeepAliveTimeout = (upperBound) => { - const lowerBound = upperBound * 0.8; - return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound); - }; - if (this.configuration.keepAliveInterval && !this.keepAliveInterval) { - this.keepAliveInterval = setInterval(() => { - this.sendKeepAlive(); - this.startSendingKeepAlives(); - }, computeKeepAliveTimeout(this.configuration.keepAliveInterval)); - } - } - /** - * Stop sending keep-alives. - */ - stopSendingKeepAlives() { - if (this.keepAliveInterval) { - clearInterval(this.keepAliveInterval); - } - if (this.keepAliveDebounceTimeout) { - clearTimeout(this.keepAliveDebounceTimeout); - } - this.keepAliveInterval = undefined; - this.keepAliveDebounceTimeout = undefined; - } -} -Transport.defaultOptions = { - server: "", - connectionTimeout: 5, - keepAliveInterval: 0, - keepAliveDebounce: 10, - traceSip: true -}; diff --git a/lib/version.d.ts b/lib/version.d.ts deleted file mode 100644 index 17fba946d..000000000 --- a/lib/version.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const LIBRARY_VERSION = "0.17.1"; -//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/lib/version.d.ts.map b/lib/version.d.ts.map deleted file mode 100644 index fb526ad54..000000000 --- a/lib/version.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,WAAW,CAAC"} \ No newline at end of file diff --git a/lib/version.js b/lib/version.js deleted file mode 100644 index 46ab1a9d2..000000000 --- a/lib/version.js +++ /dev/null @@ -1 +0,0 @@ -export const LIBRARY_VERSION = "0.17.1";