ue-softphone-sdk-beta 4.0.42 → 4.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("js-base64"),require("js-md5"),require("jsencrypt")):"function"==typeof define&&define.amd?define(["js-base64","js-md5","jsencrypt"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ueSoftphone=t(e.Base64,e.md5,e.JSEncrypt)}(this,(function(e,t,n){"use strict";var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)};function r(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var s=function(){return s=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},s.apply(this,arguments)};function o(e,t,n,i){return new(n||(n=Promise))((function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}function a(e,t){var n,i,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(r=2&a[0]?i.return:a[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,a[1])).done)return r;switch(i=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(r=s.trys,(r=r.length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;const c=Object.create(null);c.open="0",c.close="1",c.ping="2",c.pong="3",c.message="4",c.upgrade="5",c.noop="6";const u=Object.create(null);Object.keys(c).forEach((e=>{u[c[e]]=e}));const l={type:"error",data:"parser error"},d="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),h="function"==typeof ArrayBuffer,p=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,g=({type:e,data:t},n,i)=>d&&t instanceof Blob?n?i(t):f(t,i):h&&(t instanceof ArrayBuffer||p(t))?n?i(t):f(new Blob([t]),i):i(c[e]+(t||"")),f=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function m(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let v;const y="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)y["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;const b="function"==typeof ArrayBuffer,w=(e,t)=>{if("string"!=typeof e)return{type:"message",data:S(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:T(e.substring(1),t)}:u[n]?e.length>1?{type:u[n],data:e.substring(1)}:{type:u[n]}:l},T=(e,t)=>{if(b){const n=(e=>{let t,n,i,r,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const u=new ArrayBuffer(o),l=new Uint8Array(u);for(t=0;t<a;t+=4)n=y[e.charCodeAt(t)],i=y[e.charCodeAt(t+1)],r=y[e.charCodeAt(t+2)],s=y[e.charCodeAt(t+3)],l[c++]=n<<2|i>>4,l[c++]=(15&i)<<4|r>>2,l[c++]=(3&r)<<6|63&s;return u})(e);return S(n,t)}return{base64:!0,data:e}},S=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,E=String.fromCharCode(30);function I(){return new TransformStream({transform(e,t){!function(e,t){d&&e.data instanceof Blob?e.data.arrayBuffer().then(m).then(t):h&&(e.data instanceof ArrayBuffer||p(e.data))?t(m(e.data)):g(e,!1,(e=>{v||(v=new TextEncoder),t(v.encode(e))}))}(e,(n=>{const i=n.length;let r;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);const e=new DataView(r.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{r=new Uint8Array(9);const e=new DataView(r.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(n)}))}})}let R;function k(e){return e.reduce(((e,t)=>e+t.length),0)}function C(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let i=0;for(let r=0;r<t;r++)n[r]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),n}function A(e){if(e)return function(e){for(var t in A.prototype)e[t]=A.prototype[t];return e}(e)}A.prototype.on=A.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},A.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},A.prototype.off=A.prototype.removeListener=A.prototype.removeAllListeners=A.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<i.length;r++)if((n=i[r])===t||n.fn===t){i.splice(r,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},A.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(n){i=0;for(var r=(n=n.slice(0)).length;i<r;++i)n[i].apply(this,t)}return this},A.prototype.emitReserved=A.prototype.emit,A.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},A.prototype.hasListeners=function(e){return!!this.listeners(e).length};const P="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function _(e,...t){return t.reduce(((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t)),{})}const D=P.setTimeout,q=P.clearTimeout;function O(e,t){t.useNativeTimers?(e.setTimeoutFn=D.bind(P),e.clearTimeoutFn=q.bind(P)):(e.setTimeoutFn=P.setTimeout.bind(P),e.clearTimeoutFn=P.clearTimeout.bind(P))}class H extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}let $=class extends A{constructor(e){super(),this.writable=!1,O(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new H(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=w(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}};const x="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),N={};let M,j=0,U=0;function F(e){let t="";do{t=x[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function L(){const e=F(+new Date);return e!==M?(j=0,M=e):e+"."+F(j++)}for(;U<64;U++)N[x[U]]=U;let B=!1;try{B="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(c){}const V=B;function G(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||V))return new XMLHttpRequest}catch(e){}if(!t)try{return new(P[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function W(){}const K=null!=new G({xdomain:!1}).responseType;class z extends A{constructor(e,t){super(),O(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=_(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const n=this.xhr=new G(t);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof n.status?n.status:0)}),0))},n.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=z.requestsCount++,z.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=W,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete z.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function Y(){for(let e in z.requests)z.requests.hasOwnProperty(e)&&z.requests[e].abort()}z.requestsCount=0,z.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Y):"function"==typeof addEventListener&&addEventListener("onpagehide"in P?"pagehide":"unload",Y,!1));const J="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Z=P.WebSocket||P.MozWebSocket,Q="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),X={websocket:class extends ${constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=Q?{}:_(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=Q?new Z(e,t,n):t?new Z(e,t):new Z(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;g(n,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&J((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=L()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Z}},webtransport:class extends ${get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){R||(R=new TextDecoder);const n=[];let i=0,r=-1,s=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(0===i){if(k(n)<1)break;const e=C(n,1);s=!(128&~e[0]),r=127&e[0],i=r<126?3:126===r?1:2}else if(1===i){if(k(n)<2)break;const e=C(n,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(k(n)<8)break;const e=C(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(l);break}r=s*Math.pow(2,32)+t.getUint32(4),i=3}else{if(k(n)<r)break;const e=C(n,r);a.enqueue(w(s?e:R.decode(e),t)),i=0}if(0===r||r>e){a.enqueue(l);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=I();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const r=()=>{n.read().then((({done:e,value:t})=>{e||(this.onPacket(t),r())})).catch((e=>{}))};r();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this.writer.write(n).then((()=>{i&&J((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends ${constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=K&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(E),i=[];for(let e=0;e<n.length;e++){const r=w(n[e],t);if(i.push(r),"error"===r.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,i=new Array(n);let r=0;e.forEach(((e,s)=>{g(e,!1,(e=>{i[s]=e,++r===n&&t(i.join(E))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=L()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new z(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},ee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,te=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ne(e){const t=e,n=e.indexOf("["),i=e.indexOf("]");-1!=n&&-1!=i&&(e=e.substring(0,n)+e.substring(n,i).replace(/:/g,";")+e.substring(i,e.length));let r=ee.exec(e||""),s={},o=14;for(;o--;)s[te[o]]=r[o]||"";return-1!=n&&-1!=i&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,s.path),s.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,i){t&&(n[t]=i)})),n}(0,s.query),s}class ie extends A{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=ne(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=ne(t.host).host),O(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,i=n.length;e<i;e++){let i=n[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new X[e](n)}open(){let e;if(this.opts.rememberUpgrade&&ie.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),n=!1;ie.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ie.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{n||"closed"!==this.readyState&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function r(){n||(n=!0,u(),t.close(),t=null)}const s=e=>{const n=new Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&r()}const u=()=>{t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{n||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",ie.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(e+="string"==typeof(t=i)?function(e){let t=0,n=0;for(let i=0,r=e.length;i<r;i++)t=e.charCodeAt(i),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}var t;return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():e()})):this.upgrading?n():e()),this}onError(e){ie.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const i=e.length;for(;n<i;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}ie.protocol=4;const re="function"==typeof ArrayBuffer,se=Object.prototype.toString,oe="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===se.call(Blob),ae="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===se.call(File);function ce(e){return re&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||oe&&e instanceof Blob||ae&&e instanceof File}function ue(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ue(e[t]))return!0;return!1}if(ce(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ue(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ue(e[t]))return!0;return!1}function le(e){const t=[],n=e.data,i=e;return i.data=de(n,t),i.attachments=t.length,{packet:i,buffers:t}}function de(e,t){if(!e)return e;if(ce(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let i=0;i<e.length;i++)n[i]=de(e[i],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=de(e[i],t));return n}return e}function he(e,t){return e.data=pe(e.data,t),delete e.attachments,e}function pe(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=pe(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=pe(e[n],t));return e}const ge=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var fe;function me(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(fe||(fe={}));class ve extends A{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===fe.BINARY_EVENT;n||t.type===fe.BINARY_ACK?(t.type=n?fe.EVENT:fe.ACK,this.reconstructor=new ye(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!ce(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===fe[n.type])throw new Error("unknown packet type "+n.type);if(n.type===fe.BINARY_EVENT||n.type===fe.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const r=e.substring(i,t);if(r!=Number(r)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(r)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(i,t)}else n.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!ve.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case fe.CONNECT:return me(t);case fe.DISCONNECT:return void 0===t;case fe.CONNECT_ERROR:return"string"==typeof t||me(t);case fe.EVENT:case fe.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ge.indexOf(t[0]));case fe.ACK:case fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ye{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=he(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var be=Object.freeze({__proto__:null,protocol:5,get PacketType(){return fe},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==fe.EVENT&&e.type!==fe.ACK||!ue(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===fe.EVENT?fe.BINARY_EVENT:fe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==fe.BINARY_EVENT&&e.type!==fe.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=le(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}},Decoder:ve});function we(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Te=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Se extends A{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[we(e,"open",this.onopen.bind(this)),we(e,"packet",this.onpacket.bind(this)),we(e,"error",this.onerror.bind(this)),we(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Te.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:fe.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),n.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const r=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,[null,...e])}}emitWithAck(e,...t){const n=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((i,r)=>{t.push(((e,t)=>n?e?r(e):i(t):i(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...i)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue()})),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:fe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case fe.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case fe.EVENT:case fe.BINARY_EVENT:this.onevent(e);break;case fe.ACK:case fe.BINARY_ACK:this.onack(e);break;case fe.DISCONNECT:this.ondisconnect();break;case fe.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:fe.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:fe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function Ee(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ee.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},Ee.prototype.reset=function(){this.attempts=0},Ee.prototype.setMin=function(e){this.ms=e},Ee.prototype.setMax=function(e){this.max=e},Ee.prototype.setJitter=function(e){this.jitter=e};class Ie extends A{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,O(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Ee({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||be;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ie(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=we(t,"open",(function(){n.onopen(),e&&e()})),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=we(t,"error",r);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn((()=>{i(),r(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}return this.subs.push(i),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(we(e,"ping",this.onping.bind(this)),we(e,"data",this.ondata.bind(this)),we(e,"error",this.onerror.bind(this)),we(e,"close",this.onclose.bind(this)),we(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){J((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Se(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Re={};function ke(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let i=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),i=ne(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const r=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+t,i.href=i.protocol+"://"+r+(n&&n.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=n.source,r=n.id,s=n.path,o=Re[r]&&s in Re[r].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Ie(i,t):(Re[r]||(Re[r]=new Ie(i,t)),a=Re[r]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(ke,{Manager:Ie,Socket:Se,io:ke,connect:ke});var Ce={notOpenAudioMsg:"麦克风没有开启",notOpenAudioCode:403,notOpenAudioMsgEn:"Permission dismissed"},Ae={forbiddenAudioMsg:"请先检查您的麦克风是否开启",forbiddenAudioCode:0,forbiddenAudioMsgEn:"Permission denied"},Pe=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!(!e||void 0===this.parameters[e.toLowerCase()])},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.hasParam(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}(),_e=function(e){function t(t,n,i){var r=e.call(this,i)||this;return r.uri=t,r._displayName=n,r}return r(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!1,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(Pe),De=function(e){function t(t,n,i,r,s,o){void 0===t&&(t="sip");var a=e.call(this,s||{})||this;if(a.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(var c in o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:n,host:i,port:r},a.normal={scheme:t.toLowerCase(),user:n,host:i.toLowerCase(),port:r},a}return r(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!1,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!1,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var n in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(n)&&(t+=";"+n,null!==this.parameters[n]&&(t+="="+this.parameters[n]));var i=[];for(var r in this.headers)if(this.headers.hasOwnProperty(r))for(var s in this.headers[r])this.headers[r].hasOwnProperty(s)&&i.push(r+"="+this.headers[r][s]);return i.length>0&&(t+="?"+i.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),i=n.length,r="",s=0;s<i;s++)0!==s&&(r+="-"),r+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[r]&&(r=t[r]),r},t}(Pe);function qe(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){var n=Object.keys(e.parameters),i=Object.keys(t.parameters),r=n.filter((function(e){return i.includes(e)}));return!!r.every((function(n){return e.parameters[n]===t.parameters[n]}))&&(!!["user","ttl","method","transport"].every((function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)}))&&!!["maddr"].every((function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)})))}(e,t))return!1;var n=Object.keys(e.headers),i=Object.keys(t.headers);if(0!==n.length||0!==i.length){if(n.length!==i.length)return!1;var r=n.filter((function(e){return i.includes(e)}));if(r.length!==i.length)return!1;if(!r.every((function(n){return e.headers[n].length&&t.headers[n].length&&e.headers[n][0]===t.headers[n][0]})))return!1}return!0}var Oe=function(e){function t(n,i,r,s){var o=e.call(this)||this;return o.message=n,o.expected=i,o.found=r,o.location=s,o.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(o,t),o}return r(t,e),t.buildMessage=function(e,t){function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function i(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,(function(e){return"\\x0"+n(e)})).replace(/[\x10-\x1F\x7F-\x9F]/g,(function(e){return"\\x"+n(e)}))}function r(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,(function(e){return"\\x0"+n(e)})).replace(/[\x10-\x1F\x7F-\x9F]/g,(function(e){return"\\x"+n(e)}))}function s(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":var t=e.parts.map((function(e){return Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(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){var t,n,i=e.map(s);if(i.sort(),i.length>0){for(t=1,n=1;t<i.length;t++)i[t-1]!==i[t]&&(i[n]=i[t],n++);i.length=n}switch(i.length){case 1:return i[0];case 2:return i[0]+" or "+i[1];default:return i.slice(0,-1).join(", ")+", or "+i[i.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o},t}(Error);var He,$e,xe=function(e,t){t=void 0!==t?t:{};var n,i,r,s,o={},a={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},c=119,u=["\r\n",b("\r\n",!1),/^[0-9]/,w([["0","9"]],!1,!1),/^[a-zA-Z]/,w([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,w([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,w([["\0","ÿ"]],!1,!1),/^["]/,w(['"'],!1,!1)," ",b(" ",!1),"\t",b("\t",!1),/^[a-zA-Z0-9]/,w([["a","z"],["A","Z"],["0","9"]],!1,!1),";",b(";",!1),"/",b("/",!1),"?",b("?",!1),":",b(":",!1),"@",b("@",!1),"&",b("&",!1),"=",b("=",!1),"+",b("+",!1),"$",b("$",!1),",",b(",",!1),"-",b("-",!1),"_",b("_",!1),".",b(".",!1),"!",b("!",!1),"~",b("~",!1),"*",b("*",!1),"'",b("'",!1),"(",b("(",!1),")",b(")",!1),"%",b("%",!1),function(){return" "},function(){return":"},/^[!-~]/,w([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,w([["€","￿"]],!1,!1),/^[\x80-\xBF]/,w([["€","¿"]],!1,!1),/^[a-f]/,w([["a","f"]],!1,!1),"`",b("`",!1),"<",b("<",!1),">",b(">",!1),"\\",b("\\",!1),"[",b("[",!1),"]",b("]",!1),"{",b("{",!1),"}",b("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,w([["!","'"]],!1,!1),/^[*-[]/,w([["*","["]],!1,!1),/^[\]-~]/,w([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,w([["#","["]],!1,!1),/^[\0-\t]/,w([["\0","\t"]],!1,!1),/^[\x0B-\f]/,w([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,w([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new De(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 De(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",b("sips",!0),"sip",b("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_\-]/,w([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,w([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",b("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",b("25",!1),/^[0-5]/,w([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,w([["0","4"]],!1,!1),"1",b("1",!1),/^[1-9]/,w([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",b("transport=",!0),"udp",b("udp",!0),"tcp",b("tcp",!0),"sctp",b("sctp",!0),"tls",b("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",b("user=",!0),"phone",b("phone",!0),"ip",b("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",b("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",b("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",b("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",b("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,n){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),n=null===n?void 0:n[1],t.data.uri_params[e.toLowerCase()]=n},function(e,n){e=e.join("").toLowerCase(),n=n.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(n):t.data.uri_headers[e]=[n]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new De(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)},"//",b("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},b("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",b("INVITE",!1),"ACK",b("ACK",!1),"VXACH",b("VXACH",!1),"OPTIONS",b("OPTIONS",!1),"BYE",b("BYE",!1),"CANCEL",b("CANCEL",!1),"REGISTER",b("REGISTER",!1),"SUBSCRIBE",b("SUBSCRIBE",!1),"NOTIFY",b("NOTIFY",!1),"REFER",b("REFER",!1),"PUBLISH",b("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,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new _e(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:d,offset:y().start.offset,parsed:e})},function(e){'"'===(e=v().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",b("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",b("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",b("0",!1),function(){return parseFloat(v())},function(e,n){(t=t||{data:{}}).data.params||(t.data.params={}),n=null===n?void 0:n[1],t.data.params[e.toLowerCase()]=n},"render",b("render",!0),"session",b("session",!0),"icon",b("icon",!0),"alert",b("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=v().toLowerCase())},"handling",b("handling",!0),"optional",b("optional",!0),"required",b("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=v()},"text",b("text",!0),"image",b("image",!0),"audio",b("audio",!0),"video",b("video",!0),"application",b("application",!0),"message",b("message",!0),"multipart",b("multipart",!0),"x-",b("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new _e(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",b("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new _e(t.data.uri,t.data.displayName,t.data.params)},"digest",b("Digest",!0),"realm",b("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",b("domain",!0),"nonce",b("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",b("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",b("stale",!0),"true",b("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",b("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",b("algorithm",!0),"md5",b("MD5",!0),"md5-sess",b("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",b("qop",!0),"auth-int",b("auth-int",!0),"auth",b("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new _e(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:d,offset:y().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new _e(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",b("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",b("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",b("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",b("active",!0),"pending",b("pending",!0),"terminated",b("terminated",!0),function(){(t=t||{data:{}}).data.state=v()},"reason",b("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",b("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",b("deactivated",!0),"probation",b("probation",!0),"rejected",b("rejected",!0),"timeout",b("timeout",!0),"giveup",b("giveup",!0),"noresource",b("noresource",!0),"invariant",b("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new _e(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",b("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",b("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",b("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",b("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",b("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},b("UDP",!0),b("TCP",!0),b("TLS",!0),b("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=v()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",b("refresher",!1),"uas",b("uas",!1),"uac",b("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",b("stuns",!0),"stun",b("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",b("?transport=",!1),"turns",b("turns",!0),"turn",b("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=v()},"Referred-By",b("Referred-By",!1),"b",b("b",!1),"cid",b("cid",!1)],l=[I('2 ""6 7!'),I('4"""5!7#'),I('4$""5!7%'),I('4&""5!7\''),I(";'.# &;("),I('4(""5!7)'),I('4*""5!7+'),I('2,""6,7-'),I('2.""6.7/'),I('40""5!71'),I('22""6273.‰ &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'),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#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),I(';.." &"'),I("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),I('%%$;2/&#0#*;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('%$;).• &2F""6F7G.‰ &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/ž#0›*;).• &2F""6F7G.‰ &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('%$;).‰ &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/’#0*;).‰ &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.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273.› &28""6879. &2j""6j7k.ƒ &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),I('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &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""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),I("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),I("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),I(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),I('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),I("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),I("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),I('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),I('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),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!:–! )'),I('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:—! )"),I('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),I('$4™""5!7š/,#0)*4™""5!7š&&&#'),I('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),I('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),I('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),I('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),I("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),I('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),I('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),I(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),I('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),I('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),I('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),I('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),I('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),I('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),I('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),I('%$;j/&#0#*;j&&&#/"!&,)'),I('%$;j/&#0#*;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#:Î#"" )(#\'#("\'#&\'#'),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(";‘.# &;r"),I("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),I(";M.# &;t"),I("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),I('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),I('%24""6475/,#;{/#$+")("\'#&\'#'),I("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),I(";*.) &;+.# &;-"),I(';+. &;-.‰ &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('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),I(";.# &;‚"),I('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),I('$;+.ƒ &;-.} &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/Œ#0‰*;+.ƒ &;-.} &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’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),I('2Õ""6Õ7Ö'),I('2×""6×7Ø'),I('2Ù""6Ù7Ú'),I('2Û""6Û7Ü'),I('2Ý""6Ý7Þ'),I('2ß""6ß7à'),I('2á""6á7â'),I('2ã""6ã7ä'),I('2å""6å7æ'),I('2ç""6ç7è'),I('2é""6é7ê'),I("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),I("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%;“/' 8!:ì!! )"),I("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),I("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),I("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),I("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),I("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),I("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),I("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),I(";œ.) &;.# &; "),I("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),I("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),I('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),I('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),I(";6.) &;T.# &;H"),I("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),I(";¥.# &; "),I('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),I("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),I("%;©/& 8!:č! )"),I("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I(";«.# &;¬"),I('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),I('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),I(";6.# &;®"),I('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),I(";­.# &;6"),I("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),I(";6.# &;H"),I("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),I("%;ž/' 8!:ğ!! )"),I('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),I('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),I(";¹.# &; "),I("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),I("%;ž/' 8!:Ħ!! )"),I("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),I(";¾"),I("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),I("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),I(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),I("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),I("%;I/' 8!:Ĭ!! )"),I("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),I(";t.# &;w"),I("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),I("%;I/' 8!:ı!! )"),I("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),I('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),I('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),I('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),I('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),I("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),I("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),I("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),I('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),I("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),I("%;–/& 8!:Ő! )"),I('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),I('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),I("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),I("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),I("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),I('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),I(';1." &"'),I('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),I("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),I(";¹.# &; "),I("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),I("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),I("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),I("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),I("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),I("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),I("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),I('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),I('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),I('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),I('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),I(";¾"),I('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),I(";ô.# &; "),I('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),I('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),I("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),I("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),I("$;%0#*;%&"),I("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),I('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),I('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),I(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),I('2L""6L7M.• &2B""6B7C.‰ &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),I('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),I('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),I("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),I("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),I("%;ă/,#;ă/#$+\")(\"'#&'#"),I("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),I("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),I('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),I(";™.# &;L"),I("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),I("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")],d=0,h=0,p=[{line:1,column:1}],g=0,f=[],m=0;if(void 0!==t.startRule){if(!(t.startRule in a))throw new Error("Can't start parsing from rule \""+t.startRule+'".');c=a[t.startRule]}function v(){return e.substring(h,d)}function y(){return S(h,d)}function b(e,t){return{type:"literal",text:e,ignoreCase:t}}function w(e,t,n){return{type:"class",parts:e,inverted:t,ignoreCase:n}}function T(t){var n,i=p[t];if(i)return i;for(n=t-1;!p[n];)n--;for(i={line:(i=p[n]).line,column:i.column};n<t;)10===e.charCodeAt(n)?(i.line++,i.column=1):i.column++,n++;return p[t]=i,i}function S(e,t){var n=T(e),i=T(t);return{start:{offset:e,line:n.line,column:n.column},end:{offset:t,line:i.line,column:i.column}}}function E(e){d<g||(d>g&&(g=d,f=[]),f.push(e))}function I(e){return e.split("").map((function(e){return e.charCodeAt(0)-32}))}if(t.data={},n=function t(n){for(var i,r=l[n],s=0,a=[],c=r.length,p=[],g=[];;){for(;s<c;)switch(r[s]){case 0:g.push(u[r[s+1]]),s+=2;break;case 1:g.push(void 0),s++;break;case 2:g.push(null),s++;break;case 3:g.push(o),s++;break;case 4:g.push([]),s++;break;case 5:g.push(d),s++;break;case 6:g.pop(),s++;break;case 7:d=g.pop(),s++;break;case 8:g.length-=r[s+1],s+=2;break;case 9:g.splice(-2,1),s++;break;case 10:g[g.length-2].push(g.pop()),s++;break;case 11:g.push(g.splice(g.length-r[s+1],r[s+1])),s+=2;break;case 12:g.push(e.substring(g.pop(),d)),s++;break;case 13:p.push(c),a.push(s+3+r[s+1]+r[s+2]),g[g.length-1]?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 14:p.push(c),a.push(s+3+r[s+1]+r[s+2]),g[g.length-1]===o?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 15:p.push(c),a.push(s+3+r[s+1]+r[s+2]),g[g.length-1]!==o?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 16:g[g.length-1]!==o?(p.push(c),a.push(s),c=s+2+r[s+1],s+=2):s+=2+r[s+1];break;case 17:p.push(c),a.push(s+3+r[s+1]+r[s+2]),e.length>d?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 18:p.push(c),a.push(s+4+r[s+2]+r[s+3]),e.substr(d,u[r[s+1]].length)===u[r[s+1]]?(c=s+4+r[s+2],s+=4):(c=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 19:p.push(c),a.push(s+4+r[s+2]+r[s+3]),e.substr(d,u[r[s+1]].length).toLowerCase()===u[r[s+1]]?(c=s+4+r[s+2],s+=4):(c=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 20:p.push(c),a.push(s+4+r[s+2]+r[s+3]),u[r[s+1]].test(e.charAt(d))?(c=s+4+r[s+2],s+=4):(c=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 21:g.push(e.substr(d,r[s+1])),d+=r[s+1],s+=2;break;case 22:g.push(u[r[s+1]]),d+=u[r[s+1]].length,s+=2;break;case 23:g.push(o),0===m&&E(u[r[s+1]]),s+=2;break;case 24:h=g[g.length-1-r[s+1]],s+=2;break;case 25:h=d,s++;break;case 26:i=r.slice(s+4,s+4+r[s+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-r[s+2],r[s+2],u[r[s+1]].apply(null,i)),s+=4+r[s+3];break;case 27:g.push(t(r[s+1])),s+=2;break;case 28:m++,s++;break;case 29:m--,s++;break;default:throw new Error("Invalid opcode: "+r[s]+".")}if(!(p.length>0))break;c=p.pop(),s=a.pop()}return g[0]}(c),n!==o&&d===e.length)return n;throw n!==o&&d<e.length&&E({type:"end"}),i=f,r=g<e.length?e.charAt(g):null,s=g<e.length?S(g,g+1):S(g,g),new Oe(Oe.buildMessage(i,r),i,r,s)};!function(e){e.parse=function(e,t){var n={startRule:t};try{xe(e,n)}catch(e){n.data=-1}return n.data},e.nameAddrHeaderParse=function(t){var n=e.parse(t,"Name_Addr_Header");return-1!==n?n:void 0},e.URIParse=function(t){var n=e.parse(t,"SIP_URI");return-1!==n?n:void 0}}(He||(He={})),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"}($e||($e={}));var Ne={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 Me(e,t){void 0===t&&(t=32);for(var n="",i=0;i<e;i++){n+=Math.floor(Math.random()*t).toString(t)}return n}function je(e){return Ne[e]||""}function Ue(){return Me(10)}function Fe(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),i=n.length,r="",s=0;s<i;s++)0!==s&&(r+="-"),r+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[r]&&(r=t[r]),r}function Le(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}var Be=function(){function e(){this.headers={}}return e.prototype.addHeader=function(e,t){var n={raw:t};e=Fe(e),this.headers[e]?this.headers[e].push(n):this.headers[e]=[n]},e.prototype.getHeader=function(e){var t=this.headers[Fe(e)];if(t)return t[0]?t[0].raw:void 0},e.prototype.getHeaders=function(e){var t=this.headers[Fe(e)],n=[];if(!t)return[];for(var i=0,r=t;i<r.length;i++){var s=r[i];n.push(s.raw)}return n},e.prototype.hasHeader=function(e){return!!this.headers[Fe(e)]},e.prototype.parseHeader=function(e,t){if(void 0===t&&(t=0),e=Fe(e),this.headers[e]&&!(t>=this.headers[e].length)){var n=this.headers[e][t],i=n.raw;if(n.parsed)return n.parsed;var r=He.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(n.parsed=r,r)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[Fe(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}(),Ve=function(e){function t(){return e.call(this)||this}return r(t,e),t}(Be),Ge=function(e){function t(){return e.call(this)||this}return r(t,e),t}(Be),We=function(){function e(t,n,i,r,o,a,c){this.headers={},this.extraHeaders=[],this.options=e.getDefaultOptions(),o&&(this.options=s(s({},this.options),o),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),a&&a.length&&(this.extraHeaders=a.slice()),c&&(this.body={body:c.content,contentType:c.contentType}),this.method=t,this.ruri=n.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Ue(),this.from=e.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=r.clone(),this.toTag=this.options.toTag,this.to=e.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+Me(15),this.cseq=this.options.cseq,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")}return e.getDefaultOptions=function(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}},e.makeNameAddrHeader=function(e,t,n){var i={};return n&&(i.tag=n),new _e(e,t,i)},e.prototype.getHeader=function(e){var t=this.headers[Fe(e)];if(t){if(t[0])return t[0]}else for(var n=new RegExp("^\\s*"+e+"\\s*:","i"),i=0,r=this.extraHeaders;i<r.length;i++){var s=r[i];if(n.test(s))return s.substring(s.indexOf(":")+1).trim()}},e.prototype.getHeaders=function(e){var t=[],n=this.headers[Fe(e)];if(n)for(var i=0,r=n;i<r.length;i++){var s=r[i];t.push(s)}else for(var o=new RegExp("^\\s*"+e+"\\s*:","i"),a=0,c=this.extraHeaders;a<c.length;a++){var u=c[a];o.test(u)&&t.push(u.substring(u.indexOf(":")+1).trim())}return t},e.prototype.hasHeader=function(e){if(this.headers[Fe(e)])return!0;for(var t=new RegExp("^\\s*"+e+"\\s*:","i"),n=0,i=this.extraHeaders;n<i.length;n++){var r=i[n];if(t.test(r))return!0}return!1},e.prototype.setHeader=function(e,t){this.headers[Fe(e)]=t instanceof Array?t:[t]},e.prototype.setViaHeader=function(e,t){this.options.hackViaTcp&&(t="TCP");var n="SIP/2.0/"+t;n+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(n+=";rport"),this.setHeader("via",n),this.branch=e},e.prototype.toString=function(){var e="";for(var t in e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n",this.headers)if(this.headers[t])for(var n=0,i=this.headers[t];n<i.length;n++){e+=t+": "+i[n]+"\r\n"}for(var r=0,s=this.extraHeaders;r<s.length;r++){e+=(t=s[r]).trim()+"\r\n"}return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+Le(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+Le(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e},e}();function Ke(e){return"application/sdp"===e?"session":"render"}function ze(e){var t="string"==typeof e?e:e.body,n="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ke(n),contentType:n,content:t}}function Ye(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Je(e){var t,n,i,r;e instanceof Ve&&(e.body&&(t=(r=e.parseHeader("Content-Disposition"))?r.type:void 0,n=e.parseHeader("Content-Type"),i=e.body));e instanceof Ge&&(e.body&&(t=(r=e.parseHeader("Content-Disposition"))?r.type:void 0,n=e.parseHeader("Content-Type"),i=e.body));if(e instanceof We&&e.body)if(t=e.getHeader("Content-Disposition"),n=e.getHeader("Content-Type"),"string"==typeof e.body){if(!n)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(n&&n!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");n=e.body.contentType,i=e.body.body}if(Ye(e)&&(t=e.contentDisposition,n=e.contentType,i=e.content),i){if(n&&!t&&(t=Ke(n)),!t)throw new Error("Content disposition undefined.");if(!n)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:n,content:i}}}var Ze=function(){function e(){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()}return e.hashStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendStr(e).end(t)},e.hashAsciiStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendAsciiStr(e).end(t)},e._hex=function(t){var n,i,r,s,o=e.hexChars,a=e.hexOut;for(s=0;s<4;s+=1)for(i=8*s,n=t[s],r=0;r<8;r+=2)a[i+1+r]=o.charAt(15&n),n>>>=4,a[i+0+r]=o.charAt(15&n),n>>>=4;return a.join("")},e._md5cycle=function(e,t){var n=e[0],i=e[1],r=e[2],s=e[3];i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[0]-680876936|0)<<7|n>>>25)+i|0)&i|~n&r)+t[1]-389564586|0)<<12|s>>>20)+n|0)&n|~s&i)+t[2]+606105819|0)<<17|r>>>15)+s|0)&s|~r&n)+t[3]-1044525330|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[4]-176418897|0)<<7|n>>>25)+i|0)&i|~n&r)+t[5]+1200080426|0)<<12|s>>>20)+n|0)&n|~s&i)+t[6]-1473231341|0)<<17|r>>>15)+s|0)&s|~r&n)+t[7]-45705983|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[8]+1770035416|0)<<7|n>>>25)+i|0)&i|~n&r)+t[9]-1958414417|0)<<12|s>>>20)+n|0)&n|~s&i)+t[10]-42063|0)<<17|r>>>15)+s|0)&s|~r&n)+t[11]-1990404162|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[12]+1804603682|0)<<7|n>>>25)+i|0)&i|~n&r)+t[13]-40341101|0)<<12|s>>>20)+n|0)&n|~s&i)+t[14]-1502002290|0)<<17|r>>>15)+s|0)&s|~r&n)+t[15]+1236535329|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[1]-165796510|0)<<5|n>>>27)+i|0)&r|i&~r)+t[6]-1069501632|0)<<9|s>>>23)+n|0)&i|n&~i)+t[11]+643717713|0)<<14|r>>>18)+s|0)&n|s&~n)+t[0]-373897302|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[5]-701558691|0)<<5|n>>>27)+i|0)&r|i&~r)+t[10]+38016083|0)<<9|s>>>23)+n|0)&i|n&~i)+t[15]-660478335|0)<<14|r>>>18)+s|0)&n|s&~n)+t[4]-405537848|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[9]+568446438|0)<<5|n>>>27)+i|0)&r|i&~r)+t[14]-1019803690|0)<<9|s>>>23)+n|0)&i|n&~i)+t[3]-187363961|0)<<14|r>>>18)+s|0)&n|s&~n)+t[8]+1163531501|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[13]-1444681467|0)<<5|n>>>27)+i|0)&r|i&~r)+t[2]-51403784|0)<<9|s>>>23)+n|0)&i|n&~i)+t[7]+1735328473|0)<<14|r>>>18)+s|0)&n|s&~n)+t[12]-1926607734|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[5]-378558|0)<<4|n>>>28)+i|0)^i^r)+t[8]-2022574463|0)<<11|s>>>21)+n|0)^n^i)+t[11]+1839030562|0)<<16|r>>>16)+s|0)^s^n)+t[14]-35309556|0)<<23|i>>>9)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[1]-1530992060|0)<<4|n>>>28)+i|0)^i^r)+t[4]+1272893353|0)<<11|s>>>21)+n|0)^n^i)+t[7]-155497632|0)<<16|r>>>16)+s|0)^s^n)+t[10]-1094730640|0)<<23|i>>>9)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[13]+681279174|0)<<4|n>>>28)+i|0)^i^r)+t[0]-358537222|0)<<11|s>>>21)+n|0)^n^i)+t[3]-722521979|0)<<16|r>>>16)+s|0)^s^n)+t[6]+76029189|0)<<23|i>>>9)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[9]-640364487|0)<<4|n>>>28)+i|0)^i^r)+t[12]-421815835|0)<<11|s>>>21)+n|0)^n^i)+t[15]+530742520|0)<<16|r>>>16)+s|0)^s^n)+t[2]-995338651|0)<<23|i>>>9)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[0]-198630844|0)<<6|n>>>26)+i|0)|~r))+t[7]+1126891415|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[14]-1416354905|0)<<15|r>>>17)+s|0)|~n))+t[5]-57434055|0)<<21|i>>>11)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[12]+1700485571|0)<<6|n>>>26)+i|0)|~r))+t[3]-1894986606|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[10]-1051523|0)<<15|r>>>17)+s|0)|~n))+t[1]-2054922799|0)<<21|i>>>11)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[8]+1873313359|0)<<6|n>>>26)+i|0)|~r))+t[15]-30611744|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[6]-1560198380|0)<<15|r>>>17)+s|0)|~n))+t[13]+1309151649|0)<<21|i>>>11)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[4]-145523070|0)<<6|n>>>26)+i|0)|~r))+t[11]-1120210379|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[2]+718787259|0)<<15|r>>>17)+s|0)|~n))+t[9]-343485551|0)<<21|i>>>11)+r|0,e[0]=n+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=s+e[3]|0},e.prototype.start=function(){return this._dataLength=0,this._bufferLength=0,this._state.set(e.stateIdentity),this},e.prototype.appendStr=function(t){var n,i,r=this._buffer8,s=this._buffer32,o=this._bufferLength;for(i=0;i<t.length;i+=1){if((n=t.charCodeAt(i))<128)r[o++]=n;else if(n<2048)r[o++]=(n>>>6)+192,r[o++]=63&n|128;else if(n<55296||n>56319)r[o++]=(n>>>12)+224,r[o++]=n>>>6&63|128,r[o++]=63&n|128;else{if((n=1024*(n-55296)+(t.charCodeAt(++i)-56320)+65536)>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");r[o++]=(n>>>18)+240,r[o++]=n>>>12&63|128,r[o++]=n>>>6&63|128,r[o++]=63&n|128}o>=64&&(this._dataLength+=64,e._md5cycle(this._state,s),o-=64,s[0]=s[16])}return this._bufferLength=o,this},e.prototype.appendAsciiStr=function(t){for(var n,i=this._buffer8,r=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)i[s++]=t.charCodeAt(o++);if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,r),s=0}return this._bufferLength=s,this},e.prototype.appendByteArray=function(t){for(var n,i=this._buffer8,r=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)i[s++]=t[o++];if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,r),s=0}return this._bufferLength=s,this},e.prototype.getState=function(){var e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}},e.prototype.setState=function(e){var t,n=e.buffer,i=e.state,r=this._state;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],t=0;t<n.length;t+=1)this._buffer8[t]=n.charCodeAt(t)},e.prototype.end=function(t){void 0===t&&(t=!1);var n,i=this._bufferLength,r=this._buffer8,s=this._buffer32,o=1+(i>>2);if(this._dataLength+=i,r[i]=128,r[i+1]=r[i+2]=r[i+3]=0,s.set(e.buffer32Identity.subarray(o),o),i>55&&(e._md5cycle(this._state,s),s.set(e.buffer32Identity)),(n=8*this._dataLength)<=4294967295)s[14]=n;else{var a=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===a)return;var c=parseInt(a[2],16),u=parseInt(a[1],16)||0;s[14]=c,s[15]=u}return e._md5cycle(this._state,s),t?this._state:e._hex(this._state)},e.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),e.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),e.hexChars="0123456789abcdef",e.hexOut=[],e.onePassHasher=new e,e}();function Qe(e){return Ze.hashStr(e)}"5d41402abc4b2a76b9719d911017c592"!==Ze.hashStr("hello")&&console.error("Md5 self test failed.");var Xe,et=function(){function e(e,t,n,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=n,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}return e.prototype.authenticate=function(e,t,n){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=Me(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(n),!0},e.prototype.toString=function(){var 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(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,n;""!==(t=this.ha1)&&void 0!==t||(t=Qe(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(n=Qe(this.method+":"+this.uri),this.response=Qe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=Qe(this.method+":"+this.uri+":"+Qe(e||"")),this.response=Qe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):void 0===this.qop&&(n=Qe(this.method+":"+this.uri),this.response=Qe(t+":"+this.nonce+":"+n))},e}();function tt(e,t){var n="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);var i=t.reasonPhrase?t.reasonPhrase:je(t.statusCode),r="SIP/2.0 "+t.statusCode+" "+i+n;t.statusCode>=100&&t.statusCode,t.statusCode;var s="From: "+e.getHeader("From")+n,o="Call-ID: "+e.callId+n,a="CSeq: "+e.cseq+" "+e.method+n,c=e.getHeaders("via").reduce((function(e,t){return e+"Via: "+t+n}),""),u="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var l=t.toTag;l||(l=Ue()),u+=";tag="+l}u+=n;var d="";t.supported&&(d="Supported: "+t.supported.join(", ")+n);var h="";t.userAgent&&(h="User-Agent: "+t.userAgent+n);var p="";return t.extraHeaders&&(p=t.extraHeaders.reduce((function(e,t){return e+t.trim()+n}),"")),r+=c,r+=s,r+=u,r+=a,r+=o,r+=d,r+=h,r+=p,t.body?(r+="Content-Type: "+t.body.contentType+n,r+="Content-Length: "+Le(t.body.content)+n+n,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){var n=t,i=0,r=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===i;){if(-1===(r=e.indexOf("\r\n",n)))return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?n=r+2:i=r}return i}function n(e,t,n,i){var r,s=t.indexOf(":",n),o=t.substring(n,s).trim(),a=t.substring(s+1,i).trim();switch(o.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(r=e.parseHeader("Via"))&&(e.via=r,e.viaBranch=r.branch):r=0;break;case"from":case"f":e.setHeader("from",a),(r=e.parseHeader("from"))&&(e.from=r,e.fromTag=r.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),(r=e.parseHeader("to"))&&(e.to=r,e.toTag=r.getParam("tag"));break;case"record-route":if(-1===(r=He.parse(a,"Record_Route"))){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach((function(t){e.addHeader("record-route",a.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",a),(r=e.parseHeader("call-id"))&&(e.callId=a);break;case"contact":case"m":if(-1===(r=He.parse(a,"Contact"))){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach((function(t){e.addHeader("contact",a.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",a),r=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),r=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),(r=e.parseHeader("cseq"))&&(e.cseq=r.value),e instanceof Ge&&(e.method=r.method);break;case"max-forwards":e.setHeader("max-forwards",a),r=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),r=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),r=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),(r=e.parseHeader("refer-to"))&&(e.referTo=r);break;default:e.addHeader(o.toLowerCase(),a),r=0}return void 0!==r||{error:"error parsing header '"+o+"'"}}e.getHeader=t,e.parseHeader=n,e.parseMessage=function(e,i){var r=0,s=e.indexOf("\r\n");if(-1!==s){var o,a=e.substring(0,s),c=He.parse(a,"Request_Response");if(-1!==c){var u;for(c.status_code?((o=new Ge).statusCode=c.status_code,o.reasonPhrase=c.reason_phrase):((o=new Ve).method=c.method,o.ruri=c.uri),o.data=e,r=s+2;;){if(-2===(s=t(e,r))){u=r+2;break}if(-1===s)return void i.error("malformed message");var l=n(o,e,r,s);if(l&&!0!==l)return void i.error(l.error);r=s+2}return o.hasHeader("content-length")?o.body=e.substr(u,Number(o.getHeader("content-length"))):o.body=e.substring(u),o}i.warn('error parsing first line of SIP message: "'+a+'"')}else i.warn("no CRLF found, not a SIP message, discarded")}}(Xe||(Xe={}));var nt,it,rt=function(){function e(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}return e.initialDialogStateForUserAgentClient=function(e,t){var n=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");var r=i.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");var u=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:u,remoteURI:l,remoteTarget:r,routeSet:n,secure:!1}},e.initialDialogStateForUserAgentServer=function(e,t,n){void 0===n&&(n=!1);var i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");var s=r.uri,o=e.cseq,a=e.callId,c=t,u=e.fromTag,l=e.from.uri;return{id:a+c+u,early:n,callId:a,localTag:c,remoteTag:u,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:l,remoteTarget:s,routeSet:i,secure:!1}},e.prototype.dispose=function(){this.core.dialogs.delete(this.id)},Object.defineProperty(e.prototype,"id",{get:function(){return this.dialogState.id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"early",{get:function(){return this.dialogState.early},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"callId",{get:function(){return this.dialogState.callId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localTag",{get:function(){return this.dialogState.localTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTag",{get:function(){return this.dialogState.remoteTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localSequenceNumber",{get:function(){return this.dialogState.localSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteSequenceNumber",{get:function(){return this.dialogState.remoteSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localURI",{get:function(){return this.dialogState.localURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteURI",{get:function(){return this.dialogState.remoteURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTarget",{get:function(){return this.dialogState.remoteTarget},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"routeSet",{get:function(){return this.dialogState.routeSet},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"secure",{get:function(){return this.dialogState.secure},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this.core},enumerable:!1,configurable:!0}),e.prototype.confirm=function(){this.dialogState.early=!1},e.prototype.receiveRequest=function(e){if(e.method!==$e.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)}},e.prototype.recomputeRouteSet=function(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()},e.prototype.createOutgoingRequestMessage=function(e,t){var n,i=this.remoteURI,r=this.remoteTag,s=this.localURI,o=this.localTag,a=this.callId;n=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;var c=this.remoteTarget,u=this.routeSet,l=t&&t.extraHeaders,d=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,s,i,{callId:a,cseq:n,fromTag:o,toTag:r,routeSet:u},l,d)},e.prototype.incrementLocalSequenceNumber=function(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1},e.prototype.sequenceGuard=function(e){return e.method===$e.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))},e}();!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(nt||(nt={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(it||(it={}));var st,ot=500,at=5e3,ct={T1:ot,T2:4e3,T4:at,TIMER_B:32e3,TIMER_D:0,TIMER_F:3e3,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},ut=function(e){function t(t){var n=this.constructor,i=e.call(this,t)||this;return Object.setPrototypeOf(i,n.prototype),i}return r(t,e),t}(Error),lt=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return r(t,e),t}(ut),dt=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return r(t,e),t}(ut),ht=function(){function e(e,t,n,i,r){this._transport=e,this._user=t,this._id=n,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,n),this.logger.debug("Constructing ".concat(this.typeToString()," with id ").concat(this.id,"."))}return e.prototype.dispose=function(){this.logger.debug("Destroyed ".concat(this.typeToString()," with id ").concat(this.id,"."))},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),e.prototype.addStateChangeListener=function(e,t){var n=this,i=function(){n.removeStateChangeListener(i),e()};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)},e.prototype.notifyStateChangeListeners=function(){this.listeners.slice().forEach((function(e){return e()}))},e.prototype.removeStateChangeListener=function(e){this.listeners=this.listeners.filter((function(t){return t!==e}))},e.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in ".concat(this.typeToString()," with id ").concat(this.id,".")),this.logger.error(t)},e.prototype.send=function(e){var t=this;return this.transport.send(e).catch((function(e){if(e instanceof dt)throw t.onTransportError(e),e;var n;throw n=e&&"string"==typeof e.message?new dt(e.message):new dt,t.onTransportError(n),n}))},e.prototype.setState=function(e){this.logger.debug('State change to "'.concat(e,'" on ').concat(this.typeToString()," with id ").concat(this.id,".")),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()},e.prototype.typeToString=function(){return"UnknownType"},e}(),pt=function(e){function t(n,i,r,s,o){var a=e.call(this,i,r,t.makeId(n),s,o)||this;return a._request=n,a.user=r,n.setViaHeader(a.id,i.protocol),a}return r(t,e),t.makeId=function(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())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(ht);!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(st||(st={}));var gt=function(e){function t(t,n,i){var r=e.call(this,t,n,i,st.Calling,"sip.transaction.ict")||this;return r.ackRetransmissionCache=new Map,r.B=setTimeout((function(){return r.timerB()}),ct.TIMER_B),r.send(t.toString()).catch((function(e){r.logTransportError(e,"Failed to send initial outgoing request.")})),r}return r(t,e),t.prototype.dispose=function(){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),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ict"},enumerable:!1,configurable:!0}),t.prototype.ackResponse=function(e){var t=this,n=e.toTag;if(!n)throw new Error("To tag undefined.");var i="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(i,this.transport.protocol),this.ackRetransmissionCache.set(n,e),this.send(e.toString()).catch((function(e){t.logTransportError(e,"Failed to send ACK to 2xx response.")}))},t.prototype.receiveResponse=function(e){var t=this,n=e.statusCode;if(!n||n<100||n>699)throw new Error("Invalid status code ".concat(n));switch(this.state){case st.Calling:if(n>=100&&n<=199)return this.stateTransition(st.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(st.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(st.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Proceeding:if(n>=100&&n<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(st.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(st.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Accepted:if(n>=200&&n<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var i=this.ackRetransmissionCache.get(e.toTag);return i?void this.send(i.toString()).catch((function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case st.Completed:if(n>=300&&n<=699)return void this.ack(e);break;case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var r="Received unexpected ".concat(n," response while in state ").concat(this.state,".");this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(st.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,n=this.request.ruri,i=this.request.callId,r=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK ".concat(n," SIP/2.0\r\n");c&&(u+="Route: ".concat(c,"\r\n")),u+="Via: ".concat(a,"\r\n"),u+="To: ".concat(o,"\r\n"),u+="From: ".concat(s,"\r\n"),u+="Call-ID: ".concat(i,"\r\n"),u+="CSeq: ".concat(r," ACK\r\n"),u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch((function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")}))},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case st.Calling:i();break;case st.Proceeding:this.state!==st.Calling&&i();break;case st.Accepted:case st.Completed:this.state!==st.Calling&&this.state!==st.Proceeding&&i();break;case st.Terminated:this.state!==st.Calling&&this.state!==st.Accepted&&this.state!==st.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),st.Proceeding,e===st.Completed&&(this.D=setTimeout((function(){return n.timerD()}),ct.TIMER_D)),e===st.Accepted&&(this.M=setTimeout((function(){return n.timerM()}),ct.TIMER_M)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerA=function(){},t.prototype.timerB=function(){this.logger.debug("Timer B expired for INVITE client transaction ".concat(this.id,".")),this.state===st.Calling&&(this.onRequestTimeout(),this.stateTransition(st.Terminated))},t.prototype.timerD=function(){this.logger.debug("Timer D expired for INVITE client transaction ".concat(this.id,".")),this.state===st.Completed&&this.stateTransition(st.Terminated)},t.prototype.timerM=function(){this.logger.debug("Timer M expired for INVITE client transaction ".concat(this.id,".")),this.state===st.Accepted&&this.stateTransition(st.Terminated)},t}(pt),ft=function(e){function t(t,n,i,r,s){var o=e.call(this,n,i,t.viaBranch,r,s)||this;return o._request=t,o.user=i,o}return r(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t}(ht),mt=function(e){function t(t,n,i){return e.call(this,t,n,i,st.Proceeding,"sip.transaction.ist")||this}return r(t,e),t.prototype.dispose=function(){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),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case st.Proceeding:if(e.method===$e.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case st.Accepted:if(e.method===$e.INVITE)return;break;case st.Completed:if(e.method===$e.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===$e.ACK)return void this.stateTransition(st.Confirmed);break;case st.Confirmed:case st.Terminated:if(e.method===$e.INVITE||e.method===$e.ACK)return;break;default:throw new Error("Invalid state ".concat(this.state))}var n="INVITE server transaction received unexpected ".concat(e.method," request while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));switch(this.state){case st.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(st.Accepted),void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(st.Completed),void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send non-2xx final response.")}));break;case st.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send 2xx response.")}));break;case st.Completed:case st.Confirmed:case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var i="INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(i),new Error(i)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===st.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((function(t){e.logTransportError(t,"Failed to send 2xx response.")}))},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t.state," to ").concat(e))};switch(e){case st.Proceeding:n();break;case st.Accepted:case st.Completed:this.state!==st.Proceeding&&n();break;case st.Confirmed:this.state!==st.Completed&&n();break;case st.Terminated:this.state!==st.Accepted&&this.state!==st.Completed&&this.state!==st.Confirmed&&n();break;default:n()}this.stopProgressExtensionTimer(),e===st.Accepted&&(this.L=setTimeout((function(){return t.timerL()}),ct.TIMER_L)),e===st.Completed&&(this.H=setTimeout((function(){return t.timerH()}),ct.TIMER_H)),e===st.Confirmed&&(this.I=setTimeout((function(){return t.timerI()}),ct.TIMER_I)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction ".concat(e.id,".")),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch((function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")}))}),ct.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timerG=function(){},t.prototype.timerH=function(){this.logger.debug("Timer H expired for INVITE server transaction ".concat(this.id,".")),this.state===st.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(st.Terminated))},t.prototype.timerI=function(){this.logger.debug("Timer I expired for INVITE server transaction ".concat(this.id,".")),this.stateTransition(st.Terminated)},t.prototype.timerL=function(){this.logger.debug("Timer L expired for INVITE server transaction ".concat(this.id,".")),this.state===st.Accepted&&this.stateTransition(st.Terminated)},t}(ft),vt=function(e){function t(t,n,i){var r=e.call(this,t,n,i,st.Trying,"sip.transaction.nict")||this;return r.F=setTimeout((function(){return r.timerF()}),ct.TIMER_F),r.send(t.toString()).catch((function(e){r.logTransportError(e,"Failed to send initial outgoing request.")})),r}return r(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!1,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code ".concat(t));switch(this.state){case st.Trying:if(t>=100&&t<=199)return this.stateTransition(st.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(st.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(st.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Completed:case st.Terminated:return;default:throw new Error("Invalid state ".concat(this.state))}var n="Non-INVITE client transaction received unexpected ".concat(t," response while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(st.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case st.Trying:i();break;case st.Proceeding:this.state!==st.Trying&&i();break;case st.Completed:this.state!==st.Trying&&this.state!==st.Proceeding&&i();break;case st.Terminated:this.state!==st.Trying&&this.state!==st.Proceeding&&this.state!==st.Completed&&(t||i());break;default:i()}e===st.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((function(){return n.timerK()}),ct.TIMER_K)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerF=function(){this.logger.debug("Timer F expired for non-INVITE client transaction ".concat(this.id,".")),this.state!==st.Trying&&this.state!==st.Proceeding||(this.onRequestTimeout(),this.stateTransition(st.Terminated))},t.prototype.timerK=function(){this.state===st.Completed&&this.stateTransition(st.Terminated)},t}(pt),yt=function(e){function t(t,n,i){return e.call(this,t,n,i,st.Trying,"sip.transaction.nist")||this}return r(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case st.Trying:break;case st.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case st.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((function(e){t.logTransportError(e,"Failed to send retransmission of final response.")}));break;case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case st.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(st.Proceeding),void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(st.Completed),void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send final response.")}));break;case st.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(st.Completed),void this.send(t).catch((function(e){n.logTransportError(e,"Failed to send final response.")}));break;case st.Completed:return;case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var i="Non-INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(i),new Error(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(st.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case st.Trying:i();break;case st.Proceeding:this.state!==st.Trying&&i();break;case st.Completed:this.state!==st.Trying&&this.state!==st.Proceeding&&i();break;case st.Terminated:this.state!==st.Proceeding&&this.state!==st.Completed&&(t||i());break;default:i()}e===st.Completed&&(this.J=setTimeout((function(){return n.timerJ()}),ct.TIMER_J)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerJ=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction ".concat(this.id,".")),this.state===st.Completed&&this.stateTransition(st.Terminated)},t}(ft),bt=function(){function e(e,t,n,i){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.cancel=function(t,n){var i=this;if(void 0===n&&(n={}),!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.");var r=this.core.makeOutgoingRequestMessage($e.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},n.extraHeaders);return r.branch=this.message.branch,this.message.headers.Route&&(r.headers.Route=this.message.headers.Route),t&&r.setHeader("Reason",t),this.transaction.state===st.Proceeding?new e(vt,this.core,r):this.transaction.addStateChangeListener((function(){i.transaction&&i.transaction.state===st.Proceeding&&new e(vt,i.core,r)}),{once:!0}),r},e.prototype.authenticationGuard=function(e,t){var n,i,r=e.statusCode;if(!r)throw new Error("Response status code undefined.");if(401!==r&&407!==r)return!0;if(401===r?(n=e.parseHeader("www-authenticate"),i="authorization"):(n=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!n)return this.logger.warn(r+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(r+" 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,n))return!0;this.challenged=!0,n.stale&&(this.stale=!0);var s=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),s=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",s+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new Ge;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new Ge;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var 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 ".concat(t))}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===st.Terminated&&(e.core.userAgentClients.delete(i),n===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var i=n.id+n.request.method;this.core.userAgentClients.set(i,this)},e}(),wt=function(e){function t(t,n,i){var r,s=t.createOutgoingRequestMessage($e.BYE,i);return r=e.call(this,vt,t.userAgentCore,s,n)||this,t.dispose(),r}return r(t,e),t}(bt),Tt=function(){function e(e,t,n,i){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=n.toTag?n.toTag:Ue(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new lt("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new lt("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new lt("".concat(this.message.method," not redirectable in state ").concat(this.transaction.state,"."));var n=t.statusCode;if(n<300||n>399)throw new TypeError("Invalid statusCode: ".concat(n));var i=new Array;return e.forEach((function(e){return i.push("Contact: ".concat(e.toString()))})),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new lt("".concat(this.message.method," not rejectable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new lt("".concat(this.message.method," not tryingable in state ").concat(this.transaction.state,"."));return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding||this.transaction.state===st.Accepted;if(this.transaction instanceof yt)return this.transaction.state===st.Trying||this.transaction.state===st.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return!1;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return this.transaction.state===st.Trying||this.transaction.state===st.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return this.transaction.state===st.Trying||this.transaction.state===st.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return this.transaction.state===st.Trying;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),e.prototype.reply=function(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;var t=tt(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===st.Terminated&&(e.core.userAgentServers.delete(i),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var i=n.id;this.core.userAgentServers.set(n.id,this)},e}(),St=function(e){function t(t,n,i){return e.call(this,yt,t.userAgentCore,n,i)||this}return r(t,e),t}(Tt),Et=function(e){function t(t,n,i){var r=t.createOutgoingRequestMessage($e.INFO,i);return e.call(this,vt,t.userAgentCore,r,n)||this}return r(t,e),t}(bt),It=function(e){function t(t,n,i){return e.call(this,yt,t.userAgentCore,n,i)||this}return r(t,e),t}(Tt),Rt=function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}return r(t,e),t}(bt),kt=function(e){function t(t,n,i){return e.call(this,yt,t,n,i)||this}return r(t,e),t}(Tt),Ct=function(e){function t(t,n,i){var r=t.createOutgoingRequestMessage($e.NOTIFY,i);return e.call(this,vt,t.userAgentCore,r,n)||this}return r(t,e),t}(bt);var At=function(e){function t(t,n,i){var r=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,yt,r,n,i)||this}return r(t,e),t}(Tt),Pt=function(e){function t(t,n,i){var r,s=t.createOutgoingRequestMessage($e.PRACK,i);return r=e.call(this,vt,t.userAgentCore,s,n)||this,t.signalingStateTransition(s),r}return r(t,e),t}(bt),_t=function(e){function t(t,n,i){var r=e.call(this,yt,t.userAgentCore,n,i)||this;return t.signalingStateTransition(n),r.dialog=t,r}return r(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(Tt),Dt=function(e){function t(t,n,i){var r=this,s=t.createOutgoingRequestMessage($e.INVITE,i);return(r=e.call(this,gt,t.userAgentCore,s,n)||this).delegate=n,t.signalingStateTransition(s),t.reinviteUserAgentClient=r,r.dialog=t,r}return r(t,e),t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e,this.dialog)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(n):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(n):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(n):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(n):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 ".concat(n))}}},t}(bt),qt=function(e){function t(t,n,i){var r=e.call(this,mt,t.userAgentCore,n,i)||this;return t.reinviteUserAgentServer=r,r.dialog=t,r}return r(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map((function(e){return"Record-Route: ".concat(e)})));var n=e.prototype.accept.call(this,t),i=this.dialog,r=s(s({},n),{session:i});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),r},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var n=e.prototype.progress.call(this,t),i=this.dialog,r=s(s({},n),{session:i});return t.body&&this.dialog.signalingStateTransition(t.body),r},t.prototype.redirect=function(e,t){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(Tt),Ot=function(e){function t(t,n,i){var r=t.createOutgoingRequestMessage($e.REFER,i);return e.call(this,vt,t.userAgentCore,r,n)||this}return r(t,e),t}(bt);var Ht,$t=function(e){function t(t,n,i){var r=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,yt,r,n,i)||this}return r(t,e),t}(Tt),xt=function(e){function t(t,n,i,r){var s=e.call(this,n,i)||this;return s.initialTransaction=t,s._signalingState=it.Initial,s.ackWait=!1,s.ackProcessing=!1,s.delegate=r,t instanceof mt&&(s.ackWait=!0),s.early||s.start2xxRetransmissionTimer(),s.signalingStateTransition(t.request),s.logger=n.loggerFactory.getLogger("sip.invite-dialog"),s.logger.log("INVITE dialog ".concat(s.id," constructed")),s}return r(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=it.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?nt.Early:this.ackWait?nt.AckWait:this._signalingState===it.Closed?nt.Terminated:nt.Confirmed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!1,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog ".concat(this.id," sending ACK request")),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof gt))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof gt))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}var n=this.createOutgoingRequestMessage($e.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(n),this.signalingStateTransition(n),{message:n}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending BYE request")),this.initialTransaction instanceof mt){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==st.Terminated)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.")}return new wt(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INFO request")),this.early)throw new Error("Dialog not confirmed.");return new Et(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INVITE request")),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new Dt(this,e,t)},t.prototype.message=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending MESSAGE request")),this.early)throw new Error("Dialog not confirmed.");var n=this.createOutgoingRequestMessage($e.MESSAGE,t);return new Rt(this.core,n,e)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending NOTIFY request")),this.early)throw new Error("Dialog not confirmed.");return new Ct(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog ".concat(this.id," sending PRACK request")),new Pt(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending REFER request")),this.early)throw new Error("Dialog not confirmed.");return new Ot(this,e,t)},t.prototype.receiveRequest=function(t){var n=this;if(this.logger.log("INVITE dialog ".concat(this.id," received ").concat(t.method," request")),t.method!==$e.ACK)if(this.sequenceGuard(t)){if(e.prototype.receiveRequest.call(this,t),t.method===$e.INVITE){var i=function(){var e=n.ackWait?"waiting for initial ACK":"processing initial ACK";n.logger.warn("INVITE dialog ".concat(n.id," received re-INVITE while ").concat(e));n.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.")},r=Math.floor(10*Math.random())+1,s=["Retry-After: ".concat(r)];if(this.ackProcessing)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void i();if(this.ackWait&&this.signalingState!==it.Stable)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void i();if(this.reinviteUserAgentServer)return void this.core.replyStateless(t,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(t.method===$e.INVITE){var o=t.parseHeader("contact");if(!o)throw new Error("Contact undefined.");if(!(o instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=o.uri}switch(t.method){case $e.BYE:var a=new St(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(a):a.accept(),this.dispose();break;case $e.INFO:a=new It(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(a):a.reject({statusCode:469,extraHeaders:["Recv-Info:"]});break;case $e.INVITE:a=new qt(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(a):a.reject({statusCode:488});break;case $e.MESSAGE:a=new kt(this.core,t);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(a):a.accept();break;case $e.NOTIFY:a=new At(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(a):a.accept();break;case $e.PRACK:a=new _t(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(a):a.accept();break;case $e.REFER:a=new $t(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(a):a.reject();break;default:this.logger.log("INVITE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."));else{if(this.ackWait){if(this.initialTransaction instanceof gt)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(t),this.delegate&&this.delegate.onAck){var c=this.delegate.onAck({message:t});c instanceof Promise&&(this.ackProcessing=!0,c.then((function(){return n.ackProcessing=!1})).catch((function(){return n.ackProcessing=!1})))}}},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var n=e.getHeader("require"),i=e.getHeader("rseq"),r=n&&n.includes("100rel")&&i?Number(i):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==it.HaveLocalOffer&&this.signalingState!==it.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=it.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=Je(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===it.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Ve)switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:this._signalingState=it.Stable,this._answer=t;break;case it.HaveRemoteOffer:case it.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Ge)switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:this._signalingState=it.Stable,this._answer=t;break;case it.HaveRemoteOffer:case it.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof We)switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:break;case it.HaveRemoteOffer:this._signalingState=it.Stable,this._answer=t;break;case it.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Ye(e))switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:break;case it.HaveRemoteOffer:this._signalingState=it.Stable,this._answer=t;break;case it.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof mt){var t=this.initialTransaction,n=ct.T1,i=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,ct.T2),e.invite2xxTimer=setTimeout(i,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,n);var r=function(){t.state===st.Terminated&&(t.removeStateChangeListener(r),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addStateChangeListener(r)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof mt){var t=this.reinviteUserAgentServer.transaction,n=ct.T1,i=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,ct.T2),e.invite2xxTimer=setTimeout(i,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,n);var r=function(){t.state===st.Terminated&&(t.removeStateChangeListener(r),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addStateChangeListener(r)}},t}(rt);!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(Ht||(Ht={}));var Nt,Mt=[$e.ACK,$e.BYE,$e.CANCEL,$e.INFO,$e.INVITE,$e.MESSAGE,$e.NOTIFY,$e.OPTIONS,$e.PRACK,$e.REFER,$e.REGISTER,$e.SUBSCRIBE],jt=function(e){function t(t,n,i){var r=this,s=t.createOutgoingRequestMessage($e.SUBSCRIBE,i);return(r=e.call(this,vt,t.userAgentCore,s,n)||this).dialog=t,r}return r(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var i=Number(n);this.dialog.subscriptionExpires>i&&(this.dialog.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(bt),Ut=function(e){function t(t,n,i,r,s,o){var a=e.call(this,r,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=n,a._subscriptionExpiresInitial=n,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=i,a.logger=r.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog ".concat(a.id," constructed")),a}return r(t,e),t.initialDialogStateForSubscription=function(e,t){var n=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");var r=i.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:n,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog ".concat(this.id," received ").concat(t.method," request")),this.sequenceGuard(t))if(e.prototype.receiveRequest.call(this,t),t.method===$e.NOTIFY)this.onNotify(t);else this.logger.log("SUBSCRIBE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501});else this.logger.log("SUBSCRIBE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."))},t.prototype.refresh=function(){var e="Allow: "+Mt.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)},t.prototype.subscribe=function(e,t){var n=this;if(void 0===t&&(t={}),this.subscriptionState!==Ht.Pending&&this.subscriptionState!==Ht.Active)throw new Error("Invalid state ".concat(this.subscriptionState,'. May only re-subscribe while in state "pending" or "active".'));this.logger.log("SUBSCRIBE dialog ".concat(this.id," sending SUBSCRIBE request"));var i=new jt(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout((function(){return n.timerN()}),ct.TIMER_N),i},t.prototype.terminate=function(){this.stateTransition(Ht.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+Mt.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)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var n=e.parseHeader("Subscription-State");if(n&&n.state){var i=n.state,r=n.expires?Math.max(n.expires,0):void 0;switch(i){case"pending":this.stateTransition(Ht.Pending,r);break;case"active":this.stateTransition(Ht.Active,r);break;case"terminated":this.stateTransition(Ht.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}var s=new At(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())}),t)}},t.prototype.stateTransition=function(e,t){var n=this,i=function(){n.logger.warn("Invalid subscription state transition from ".concat(n.subscriptionState," to ").concat(e))};switch(e){case Ht.Initial:case Ht.NotifyWait:return void i();case Ht.Pending:if(this.subscriptionState!==Ht.NotifyWait&&this.subscriptionState!==Ht.Pending)return void i();break;case Ht.Active:case Ht.Terminated:if(this.subscriptionState!==Ht.NotifyWait&&this.subscriptionState!==Ht.Pending&&this.subscriptionState!==Ht.Active)return void i();break;default:return void i()}e===Ht.Pending&&t&&(this.subscriptionExpires=t),e===Ht.Active&&t&&(this.subscriptionExpires=t),e===Ht.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timerN=function(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==Ht.Terminated&&(this.stateTransition(Ht.Terminated),this.onTerminated())},t}(rt);!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(Nt||(Nt={}));var Ft=function(){function e(e,t,n){this.logger=e,this.category=t,this.label=n}return e.prototype.error=function(e){this.genericLog(Nt.error,e)},e.prototype.warn=function(e){this.genericLog(Nt.warn,e)},e.prototype.log=function(e){this.genericLog(Nt.log,e)},e.prototype.debug=function(e){this.genericLog(Nt.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},Object.defineProperty(e.prototype,"level",{get:function(){return this.logger.level},set:function(e){this.logger.level=e},enumerable:!1,configurable:!0}),e}(),Lt=function(){function e(){this.builtinEnabled=!0,this._level=Nt.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:Nt.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new Ft(this,e,t);if(this.loggers[e])return this.loggers[e];var n=new Ft(this,e);return this.loggers[e]=n,n},e.prototype.genericLog=function(e,t,n,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,n,i),this.connector&&this.connector(Nt[e],t,n,i)},e.prototype.print=function(e,t,n,i){if("string"==typeof i){var r=[new Date,t];n&&r.push(n),i=r.concat(i).join(" | ")}switch(e){case Nt.error:console.error(i);break;case Nt.warn:console.warn(i);break;case Nt.log:console.log(i);break;case Nt.debug:console.debug(i)}},e}();!function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}r(t,e)}(bt);var Bt=function(e){function t(t,n,i){var r=e.call(this,gt,t,n,i)||this;return r.confirmedDialogAcks=new Map,r.confirmedDialogs=new Map,r.earlyDialogs=new Map,r.delegate=i,r}return r(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.onTransportError=function(t){if(this.transaction.state===st.Calling)return e.prototype.onTransportError.call(this,t);this.logger.error(t.message),this.logger.error("User agent client request transport error while sending ACK.")},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(n):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.");var i=rt.initialDialogStateForUserAgentClient(this.message,e),r=this.earlyDialogs.get(i.id);if(!r){if(!((a=this.transaction)instanceof gt))throw new Error("Transaction not instance of InviteClientTransaction.");r=new xt(a,this.core,i),this.earlyDialogs.set(r.id,r)}if(!r.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");r.signalingState!==it.Initial&&r.signalingState!==it.HaveLocalOffer||r.signalingStateTransition(e);var s=r;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:s,prack:function(e){return s.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(n):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.");i=rt.initialDialogStateForUserAgentClient(this.message,e);var o=this.confirmedDialogs.get(i.id);if(o){if(u=this.confirmedDialogAcks.get(i.id)){if(!((a=this.transaction)instanceof gt))throw new Error("Client transaction not instance of InviteClientTransaction.");a.ackResponse(u.message)}return}if(o=this.earlyDialogs.get(i.id))o.confirm(),o.recomputeRouteSet(e),this.earlyDialogs.delete(o.id),this.confirmedDialogs.set(o.id,o);else{var a;if(!((a=this.transaction)instanceof gt))throw new Error("Transaction not instance of InviteClientTransaction.");o=new xt(a,this.core,i),this.confirmedDialogs.set(o.id,o)}o.signalingState!==it.Initial&&o.signalingState!==it.HaveLocalOffer||o.signalingStateTransition(e);var c=o;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:c,ack:function(e){var n=c.ack(e);return t.confirmedDialogAcks.set(c.id,n),n}});else{var u=c.ack();this.confirmedDialogAcks.set(c.id,u)}return;case/^3[0-9]{2}$/.test(n):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(n):return this.earlyDialogs.forEach((function(e){return e.dispose()})),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code ".concat(n))}}},t}(bt),Vt=function(e){function t(t,n,i){var r=e.call(this,mt,t,n,i)||this;return r.core=t,r}return r(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new lt("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var n=this.transaction;if(!(n instanceof mt))throw new Error("Transaction not instance of InviteClientTransaction.");var i=rt.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new xt(n,this.core,i)}var r=this.message.getHeaders("record-route").map((function(e){return"Record-Route: ".concat(e)})),o="Contact: ".concat(this.core.configuration.contact.toString()),a="Allow: "+Mt.toString();if(!t.body)if(this.confirmedDialog.signalingState===it.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===it.Initial||this.confirmedDialog.signalingState===it.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(r),t.extraHeaders.push(a),t.extraHeaders.push(o);var c=e.prototype.accept.call(this,t),u=this.confirmedDialog,l=s(s({},c),{session:u});return t.body&&this.confirmedDialog.signalingState!==it.Stable&&this.confirmedDialog.signalingStateTransition(t.body),l},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new lt("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));if(!this.earlyDialog){var n=this.transaction;if(!(n instanceof mt))throw new Error("Transaction not instance of InviteClientTransaction.");var i=rt.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new xt(n,this.core,i)}var r=this.message.getHeaders("record-route").map((function(e){return"Record-Route: ".concat(e)})),o="Contact: ".concat(this.core.configuration.contact);t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(r),t.extraHeaders.push(o);var a=e.prototype.progress.call(this,t),c=this.earlyDialog,u=s(s({},a),{session:c});return t.body&&this.earlyDialog.signalingState!==it.Stable&&this.earlyDialog.signalingStateTransition(t.body),u},t.prototype.redirect=function(t,n){return void 0===n&&(n={statusCode:302}),e.prototype.redirect.call(this,t,n)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(Tt),Gt=function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}return r(t,e),t}(bt);!function(e){function t(t,n,i){return e.call(this,yt,t.userAgentCore,n,i)||this}r(t,e)}(Tt);var Wt,Kt=function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}return r(t,e),t}(bt),zt=function(e){function t(t,n,i){var r=e.call(this,yt,t,n,i)||this;return r.core=t,r}return r(t,e),t}(Tt),Yt=function(e){function t(t,n,i){var r=this,s=n.getHeader("Event");if(!s)throw new Error("Event undefined");var o=n.getHeader("Expires");if(!o)throw new Error("Expires undefined");return(r=e.call(this,vt,t,n,i)||this).delegate=i,r.subscriberId=n.callId+n.fromTag+s,r.subscriptionExpiresRequested=r.subscriptionExpires=Number(o),r.subscriptionEvent=s,r.subscriptionState=Ht.NotifyWait,r.waitNotifyStart(),r}return r(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var n=e.message.parseHeader("Subscription-State");if(!n||!n.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var i=n.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state ".concat(i)),void e.reject({statusCode:489})}if("terminated"!==i&&!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=n.expires?Math.min(this.subscriptionExpires,Math.max(n.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=Ht.Pending;break;case"active":this.subscriptionState=Ht.Active;break;case"terminated":this.subscriptionState=Ht.Terminated;break;default:throw new Error("Unrecognized state ".concat(i,"."))}if(this.subscriptionState!==Ht.Terminated){var r=Ut.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Ut(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,r)}if(this.delegate&&this.delegate.onNotify){var s=e,o=this.dialog;this.delegate.onNotify({request:s,subscription:o})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((function(){return e.timerN()}),ct.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var i=Number(n);i>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),i<this.subscriptionExpires&&(this.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timerN=function(){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()},t}(bt),Jt=function(e){function t(t,n,i){var r=e.call(this,yt,t,n,i)||this;return r.core=t,r}return r(t,e),t}(Tt),Zt=["application/sdp","application/dtmf-relay"],Qt=function(){function e(e,t){void 0===t&&(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")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach((function(e){return e.dispose()})),this.dialogs.clear(),this.subscribers.forEach((function(e){return e.dispose()})),this.subscribers.clear(),this.userAgentClients.forEach((function(e){return e.dispose()})),this.userAgentClients.clear(),this.userAgentServers.forEach((function(e){return e.dispose()})),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!1,configurable:!0}),e.prototype.invite=function(e,t){return new Bt(this,e,t)},e.prototype.message=function(e,t){return new Rt(this,e,t)},e.prototype.publish=function(e,t){return new Gt(this,e,t)},e.prototype.register=function(e,t){return new Kt(this,e,t)},e.prototype.subscribe=function(e,t){return new Yt(this,e,t)},e.prototype.request=function(e,t){return new bt(vt,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,n,i,r,o,a){var c=this.configuration.sipjsId,u=this.configuration.displayName,l=this.configuration.viaForceRport,d=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===$e.REGISTER&&h.push("path","gruu"),e===$e.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");var p=this.configuration.routeSet,g=this.configuration.userAgentHeaderFieldValue,f=this.configuration.viaHost,m=s(s({},{callIdPrefix:c,forceRport:l,fromDisplayName:u,hackViaTcp:d,optionTags:h,routeSet:p,userAgentString:g,viaHost:f}),r);return new We(e,t,n,i,m,o,a)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var n=this,i=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=s(s({},t),{userAgent:i,supported:r});var o=tt(e,t);return this.transport.send(o.message).catch((function(t){t instanceof Error&&n.logger.error(t.message),n.logger.error("Transport error occurred sending stateless reply to ".concat(e.method," request."))})),o},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,n=this.userAgentServers.get(t);e.method===$e.ACK&&n&&n.transaction.state===st.Accepted&&n instanceof Vt?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction ".concat(t,".")):e.method!==$e.CANCEL?n?n.transaction.receiveRequest(e):this.receiveRequest(e):n?(this.replyStateless(e,{statusCode:200}),n.transaction instanceof mt&&n.transaction.state===st.Proceeding&&n instanceof Vt&&n.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(Mt.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,n=function(e){return!!e&&e.user===t.user};if(!n(this.configuration.aor)&&!(n(this.configuration.contact.uri)||n(this.configuration.contact.pubGruu)||n(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==$e.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==$e.INVITE||e.hasHeader("Contact")){if(!e.toTag){var i=e.viaBranch;if(!this.userAgentServers.has(i))if(Array.from(this.userAgentServers.values()).some((function(t){return 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"})}else this.replyStateless(e,{statusCode:416})}else{var r="Allow: "+Mt.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[r]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===$e.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var n=e.callId+e.toTag+t.event,i=this.subscribers.get(n);if(i){var r=new At(this,e);return void i.onNotify(r)}}var s=e.callId+e.toTag+e.fromTag,o=this.dialogs.get(s);if(o){if(e.method===$e.OPTIONS){var a="Allow: "+Mt.toString(),c="Accept: "+Zt.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[a,c]})}o.receiveRequest(e)}else e.method!==$e.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case $e.ACK:break;case $e.BYE:this.replyStateless(e,{statusCode:481});break;case $e.CANCEL:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."));case $e.INFO:this.replyStateless(e,{statusCode:405});break;case $e.INVITE:var t=new Vt(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case $e.MESSAGE:t=new kt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case $e.NOTIFY:t=new At(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case $e.OPTIONS:var n="Allow: "+Mt.toString(),i="Accept: "+Zt.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[n,i]});break;case $e.REFER:t=new $t(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case $e.REGISTER:t=new zt(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case $e.SUBSCRIBE:t=new Jt(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."))}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,n=this.userAgentClients.get(t);n?n.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched ".concat(e.statusCode," response to ").concat(e.method," ").concat(t,"."))}},e}(),Xt=function(e){function t(t){return e.call(this,t||"Unsupported content type.")||this}return r(t,e),t}(ut),en=function(e){function t(t){return e.call(this,t||"Request pending.")||this}return r(t,e),t}(ut),tn=function(e){function t(t){return e.call(this,t||"Unspecified session description handler error.")||this}return r(t,e),t}(ut),nn=function(e){function t(){return e.call(this,"The session has terminated.")||this}return r(t,e),t}(ut),rn=function(e){function t(t){return e.call(this,t||"An error occurred during state transition.")||this}return r(t,e),t}(ut),sn=function(){function e(e){this.incomingAckRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingAckRequest.message},enumerable:!1,configurable:!0}),e}(),on=function(){function e(e){this.incomingByeRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingByeRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingByeRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingByeRequest.reject(e),Promise.resolve()},e}(),an=function(){function e(){this.listeners=new Array}return e.prototype.addListener=function(e,t){var n=this,i=function(t){n.removeListener(i),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)},e.prototype.emit=function(e){this.listeners.slice().forEach((function(t){return t(e)}))},e.prototype.removeAllListeners=function(){this.listeners=[]},e.prototype.removeListener=function(e){this.listeners=this.listeners.filter((function(t){return t!==e}))},e.prototype.on=function(e){return this.addListener(e)},e.prototype.off=function(e){return this.removeListener(e)},e.prototype.once=function(e){return this.addListener(e,{once:!0})},e}(),cn=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}(),un=function(){function e(e){this.incomingMessageRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingMessageRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingMessageRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingMessageRequest.reject(e),Promise.resolve()},e}(),ln=function(){function e(e){this.incomingNotifyRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingNotifyRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()},e}(),dn=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof _e))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){var e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var n=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&n.push("Replaces: "+decodeURIComponent(i));var r=this.referredBy;return r&&n.push("Referred-By: "+r),e.extraHeaders=n,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter},e}();!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(Wt||(Wt={}));var hn,pn=function(){function e(e,t){void 0===t&&(t={}),this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=Wt.Initial,this.delegate=t.delegate,this._stateEventEmitter=new an,this._userAgent=e}return e.prototype.dispose=function(){var e=this;switch(this.logger.log("Session ".concat(this.id," in state ").concat(this._state," is being disposed")),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case Wt.Initial:case Wt.Establishing:break;case Wt.Established:return new Promise((function(t){e._bye({onAccept:function(){return t()},onRedirect:function(){return t()},onReject:function(){return t()}})}));case Wt.Terminating:case Wt.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()},Object.defineProperty(e.prototype,"assertedIdentity",{get:function(){return this._assertedIdentity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replacee",{get:function(){return this._replacee},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandler",{get:function(){return this._sessionDescriptionHandler},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerFactory",{get:function(){return this.userAgent.configuration.sessionDescriptionHandlerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiers",{get:function(){return this._sessionDescriptionHandlerModifiers||[]},set:function(e){this._sessionDescriptionHandlerModifiers=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptions",{get:function(){return this._sessionDescriptionHandlerOptions||{}},set:function(e){this._sessionDescriptionHandlerOptions=s({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiersReInvite",{get:function(){return this._sessionDescriptionHandlerModifiersReInvite||[]},set:function(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptionsReInvite",{get:function(){return this._sessionDescriptionHandlerOptionsReInvite||{}},set:function(e){this._sessionDescriptionHandlerOptionsReInvite=s({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgent",{get:function(){return this._userAgent},enumerable:!1,configurable:!0}),e.prototype.bye=function(e){void 0===e&&(e={});var t="Session.bye() may only be called if established session.";switch(this.state){case Wt.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 Wt.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 Wt.Established:var n=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._bye(n,i);case Wt.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 Wt.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 ".concat(this.state)))},e.prototype.info=function(e){if(void 0===e&&(e={}),this.state!==Wt.Established){return this.logger.error("Session.info() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._info(t,n)},e.prototype.invite=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Session.invite"),this.state!==Wt.Established)return Promise.reject(new Error("Invalid session state ".concat(this.state)));if(this.pendingReinvite)return Promise.reject(new en("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);var n={onAccept:function(n){var i=Je(n.message);if(!i)return t.logger.error("Received 2xx response to re-INVITE without a session description"),t.ackAndBye(n,400,"Missing session description"),t.stateTransition(Wt.Terminated),void(t.pendingReinvite=!1);if(e.withoutSdp){var r={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setOfferAndGetAnswer(i,r).then((function(e){n.ack({body:e})})).catch((function(e){t.logger.error("Failed to handle offer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state===Wt.Terminated?n.ack():(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(Wt.Terminated))})).then((function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)}))}else{r={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setAnswer(i,r).then((function(){n.ack()})).catch((function(e){t.logger.error("Failed to handle answer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state!==Wt.Terminated?(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(Wt.Terminated)):n.ack()})).then((function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)}))}},onProgress:function(e){},onRedirect:function(e){},onReject:function(n){t.logger.warn("Received a non-2xx response to re-INVITE"),t.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n):t.rollbackOffer().catch((function(e){if(t.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),t.logger.error(e.message),t.state!==Wt.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");var n=[];n.push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(Wt.Terminated)}})).then((function(){e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)}))},onTrying:function(e){}},i=e.requestOptions||{};if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.extraHeaders.push("Allow: "+Mt.toString()),i.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(n,i))}var r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(r).then((function(e){if(!t.dialog)throw t.pendingReinvite=!1,new Error("Dialog undefined.");return i.body=e,t.dialog.invite(n,i)})).catch((function(e){throw t.logger.error(e.message),t.logger.error("Failed to send re-INVITE"),t.pendingReinvite=!1,e}))},e.prototype.message=function(e){if(void 0===e&&(e={}),this.state!==Wt.Established){return this.logger.error("Session.message() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._message(t,n)},e.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.state!==Wt.Established){return this.logger.error("Session.refer() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var n=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return i.extraHeaders=i.extraHeaders?i.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,n,i)},e.prototype._bye=function(e,t){var n=this;if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));var i=this.dialog;switch(i.sessionState){case nt.Initial:case nt.Early:throw new Error("Invalid dialog state ".concat(i.sessionState));case nt.AckWait:return this.stateTransition(Wt.Terminating),new Promise((function(r){i.delegate={onAck:function(){var s=i.bye(e,t);return n.stateTransition(Wt.Terminated),r(s),Promise.resolve()},onAckTimeout:function(){var s=i.bye(e,t);n.stateTransition(Wt.Terminated),r(s)}}}));case nt.Confirmed:var r=i.bye(e,t);return this.stateTransition(Wt.Terminated),Promise.resolve(r);case nt.Terminated:throw new Error("Invalid dialog state ".concat(i.sessionState));default:throw new Error("Unrecognized state.")}},e.prototype._info=function(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._message=function(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._refer=function(e,t,n){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,n))):Promise.reject(new Error("Session dialog undefined."))},e.prototype.ackAndBye=function(e,t,n){e.ack();var i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,n)),e.session.bye(void 0,{extraHeaders:i})},e.prototype.onAckRequest=function(e){var t=this;if(this.logger.log("Session.onAckRequest"),this.state!==Wt.Established&&this.state!==Wt.Terminating)return this.logger.error("ACK received while in state ".concat(this.state,", dropping request")),Promise.resolve();var n=this.dialog;if(!n)throw new Error("Dialog undefined.");var i={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){var r=new sn(e);this.delegate.onAck(r)}switch(this.pendingReinviteAck=!1,n.signalingState){case it.Initial:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));var s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(Wt.Terminated),Promise.resolve();case it.Stable:var o=Je(e.message);return o?"render"===o.contentDisposition?(this._renderbody=o.content,this._rendertype=o.contentType,Promise.resolve()):"session"!==o.contentDisposition?Promise.resolve():this.setAnswer(o,i).catch((function(e){t.logger.error(e.message);var i=["Reason: "+t.getReasonHeaderValue(488,"Bad Media Description")];n.bye(void 0,{extraHeaders:i}),t.stateTransition(Wt.Terminated)})):Promise.resolve();case it.HaveLocalOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(Wt.Terminated),Promise.resolve();case it.HaveRemoteOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(Wt.Terminated),Promise.resolve();case it.Closed:default:throw new Error("Invalid signaling state ".concat(n.signalingState,"."))}},e.prototype.onByeRequest=function(e){if(this.logger.log("Session.onByeRequest"),this.state===Wt.Established){if(this.delegate&&this.delegate.onBye){var t=new on(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(Wt.Terminated)}else this.logger.error("BYE received while in state ".concat(this.state,", dropping request"))},e.prototype.onInfoRequest=function(e){if(this.logger.log("Session.onInfoRequest"),this.state===Wt.Established)if(this.delegate&&this.delegate.onInfo){var t=new cn(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error("INFO received while in state ".concat(this.state,", dropping request"))},e.prototype.onInviteRequest=function(e){var t=this;if(this.logger.log("Session.onInviteRequest"),this.state===Wt.Established){this.pendingReinviteAck=!0;var n=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){var i=e.message.getHeader("P-Asserted-Identity");if(!i)throw new Error("Header undefined.");this._assertedIdentity=He.nameAddrHeaderParse(i)}var r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(r).then((function(i){var r=e.accept({statusCode:200,extraHeaders:n,body:i});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,r.message,200)})).catch((function(i){if(t.logger.error(i.message),t.logger.error("Failed to handle to re-INVITE request"),!t.dialog)throw new Error("Dialog undefined.");if(t.logger.error(t.dialog.signalingState),t.dialog.signalingState!==it.Stable)t.rollbackOffer().then((function(){var n=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,n.message,488)})).catch((function(i){t.logger.error(i.message),t.logger.error("Failed to rollback offer on re-INVITE request");var r=e.reject({statusCode:488});if(t.state!==Wt.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(Wt.Terminated)}t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,r.message,488)}));else{var r=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,r.message,488)}}))}else this.logger.error("INVITE received while in state ".concat(this.state,", dropping request"))},e.prototype.onMessageRequest=function(e){if(this.logger.log("Session.onMessageRequest"),this.state===Wt.Established)if(this.delegate&&this.delegate.onMessage){var t=new un(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error("MESSAGE received while in state ".concat(this.state,", dropping request"))},e.prototype.onNotifyRequest=function(e){if(this.logger.log("Session.onNotifyRequest"),this.state===Wt.Established)if(this.onNotify){var t=new ln(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){t=new ln(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error("NOTIFY received while in state ".concat(this.state,", dropping request"))},e.prototype.onPrackRequest=function(e){if(this.logger.log("Session.onPrackRequest"),this.state===Wt.Established)throw new Error("Unimplemented.");this.logger.error("PRACK received while in state ".concat(this.state,", dropping request"))},e.prototype.onReferRequest=function(e){var t=this;if(this.logger.log("Session.onReferRequest"),this.state===Wt.Established){if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();var n=new dn(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(n):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),n.accept().then((function(){return n.makeInviter(t._referralInviterOptions).invite()})).catch((function(e){t.logger.error(e.message)})))}else this.logger.error("REFER received while in state ".concat(this.state,", dropping request"))},e.prototype.generateResponseOfferAnswer=function(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);var n=Je(e.message);return n&&"session"===n.contentDisposition?this.setOfferAndGetAnswer(n,t):this.getOffer(t)},e.prototype.generateResponseOfferAnswerInDialog=function(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case it.Initial:return this.getOffer(e);case it.HaveLocalOffer:return Promise.resolve(void 0);case it.HaveRemoteOffer:if(!this.dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this.dialog.signalingState,"."));return this.setOfferAndGetAnswer(this.dialog.offer,e);case it.Stable:return this.state!==Wt.Established?Promise.resolve(void 0):this.getOffer(e);case it.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},e.prototype.getOffer=function(e){var t=this,n=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,r=e.sessionDescriptionHandlerModifiers;try{return n.getDescription(i,r).then((function(e){return ze(e)})).catch((function(e){t.logger.error("Session.getOffer: SDH getDescription rejected...");var n=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw t.logger.error(n.message),n}))}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");var s=e instanceof Error?e:new Error(e);return this.logger.error(s.message),Promise.reject(s)}},e.prototype.rollbackOffer=function(){var e=this,t=this.setupSessionDescriptionHandler();if(void 0===t.rollbackDescription)return Promise.resolve();try{return t.rollbackDescription().catch((function(t){e.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");var n=t instanceof Error?t:new Error("Session.rollbackOffer unknown error.");throw e.logger.error(n.message),n}))}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");var n=e instanceof Error?e:new Error(e);return this.logger.error(n.message),Promise.reject(n)}},e.prototype.setAnswer=function(e,t){var n=this,i=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Xt)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,r,s).catch((function(e){n.logger.error("Session.setAnswer: SDH setDescription rejected...");var t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw n.logger.error(t.message),t}))}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setOfferAndGetAnswer=function(e,t){var n=this,i=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Xt)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,r,s).then((function(){return i.getDescription(r,s)})).then((function(e){return ze(e)})).catch((function(e){n.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");var t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw n.logger.error(t.message),t}))}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setSessionDescriptionHandler=function(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e},e.prototype.setupSessionDescriptionHandler=function(){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},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case Wt.Initial:e!==Wt.Establishing&&e!==Wt.Established&&e!==Wt.Terminating&&e!==Wt.Terminated&&n();break;case Wt.Establishing:e!==Wt.Established&&e!==Wt.Terminating&&e!==Wt.Terminated&&n();break;case Wt.Established:e!==Wt.Terminating&&e!==Wt.Terminated&&n();break;case Wt.Terminating:e!==Wt.Terminated&&n();break;case Wt.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Session ".concat(this.id," transitioned to state ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===Wt.Terminated&&this.dispose()},e.prototype.copyRequestOptions=function(e){return void 0===e&&(e={}),{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}},e.prototype.getReasonHeaderValue=function(e,t){var n=e,i=je(e);return!i&&t&&(i=t),"SIP;cause="+n+';text="'+i+'"'},e.prototype.referExtraHeaders=function(e){var 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},e.prototype.referToString=function(e){var t;if(e instanceof De)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");var n=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,s=e.dialog.remoteTag,o=e.dialog.localTag,a=encodeURIComponent("".concat(r,";to-tag=").concat(s,";from-tag=").concat(o));t='"'.concat(n,'" <').concat(i,"?Replaces=").concat(a,">")}return t},e}();!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(hn||(hn={}));var gn,fn,mn={"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},vn=function(e){function t(t,n){var i=e.call(this,t)||this;i.incomingInviteRequest=n,i.disposed=!1,i.expiresTimer=void 0,i.isCanceled=!1,i.rel100="none",i.rseq=Math.floor(1e4*Math.random()),i.userNoAnswerTimer=void 0,i.waitingForPrack=!1,i.logger=t.getLogger("sip.Invitation");var r=i.incomingInviteRequest.message,s=r.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(i.rel100="required");var o=r.getHeader("supported");if(o&&o.toLowerCase().includes("100rel")&&(i.rel100="supported"),r.toTag=n.toTag,"string"!=typeof r.toTag)throw new TypeError("toTag should have been a string.");if(i.userNoAnswerTimer=setTimeout((function(){n.reject({statusCode:480}),i.stateTransition(Wt.Terminated)}),i.userAgent.configuration.noAnswerTimeout?1e3*i.userAgent.configuration.noAnswerTimeout:6e4),r.hasHeader("expires")){var a=1e3*Number(r.getHeader("expires")||0);i.expiresTimer=setTimeout((function(){i.state===Wt.Initial&&(n.reject({statusCode:487}),i.stateTransition(Wt.Terminated))}),a)}var c=i.request.getHeader("P-Asserted-Identity");c&&(i._assertedIdentity=He.nameAddrHeaderParse(c)),i._contact=i.userAgent.contact.toString();var u=r.parseHeader("Content-Disposition");return u&&"render"===u.type&&(i._renderbody=r.body,i._rendertype=r.getHeader("Content-Type")),i._id=r.callId+r.fromTag,i.userAgent._sessions[i._id]=i,i}return r(t,e),t.prototype.dispose=function(){var t=this;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 Wt.Initial:case Wt.Establishing:return this.reject().then((function(){return e.prototype.dispose.call(t)}));case Wt.Established:case Wt.Terminating:case Wt.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"body",{get:function(){return this.incomingInviteRequest.message.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.request.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.request.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.incomingInviteRequest.message},enumerable:!1,configurable:!0}),t.prototype.accept=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.accept"),this.state!==Wt.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(Wt.Establishing),this.sendAccept(e).then((function(e){e.message;var n=e.session;n.delegate={onAck:function(e){return t.onAckRequest(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},t._dialog=n,t.stateTransition(Wt.Established),t._replacee&&t._replacee._bye()})).catch((function(e){return t.handleResponseError(e)}))},t.prototype.progress=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.progress"),this.state!==Wt.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}var i=e.statusCode||180;if(i<100||i>199)throw new TypeError("Invalid statusCode: "+i);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((function(){})).catch((function(e){return t.handleResponseError(e)})):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===hn.Required?this.sendProgressReliableWaitForPrack(e).then((function(){})).catch((function(e){return t.handleResponseError(e)})):this.sendProgress(e).then((function(){})).catch((function(e){return t.handleResponseError(e)}))},t.prototype.reject=function(e){if(void 0===e&&(e={}),this.logger.log("Invitation.reject"),this.state!==Wt.Initial&&this.state!==Wt.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}var n=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:je(n),r=e.extraHeaders||[];if(n<300||n>699)throw new TypeError("Invalid statusCode: "+n);var s=e.body?ze(e.body):void 0;return n<400?this.incomingInviteRequest.redirect([],{statusCode:n,reasonPhrase:i,extraHeaders:r,body:s}):this.incomingInviteRequest.reject({statusCode:n,reasonPhrase:i,extraHeaders:r,body:s}),this.stateTransition(Wt.Terminated),Promise.resolve()},t.prototype._onCancel=function(e){this.logger.log("Invitation._onCancel"),this.state===Wt.Initial||this.state===Wt.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(Wt.Terminated)):this.logger.error("CANCEL received while in state ".concat(this.state,", dropping request"))},t.prototype.handlePrackOfferAnswer=function(e){if(!this.dialog)throw new Error("Dialog undefined.");var t=Je(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case it.Initial:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case it.Stable:return this.setAnswer(t,n).then((function(){}));case it.HaveLocalOffer:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case it.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,n);case it.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},t.prototype.handleResponseError=function(e){var t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof Xt?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof tn?this.logger.error("A session description handler occurred while sending response"):e instanceof nn?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof lt&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===Wt.Initial||this.state===Wt.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(Wt.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.")},t.prototype.onAckTimeout=function(){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(Wt.Terminated)},t.prototype.sendAccept=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then((function(){return clearTimeout(t.userNoAnswerTimer)})).then((function(){return t.generateResponseOfferAnswer(t.incomingInviteRequest,n)})).then((function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then((function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})})))},t.prototype.sendProgress=function(e){void 0===e&&(e={});var t=e.statusCode||180,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?ze(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{var s=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:n,extraHeaders:i,body:r});return this._dialog=s.session,Promise.resolve(s)}catch(e){return Promise.reject(e)}},t.prototype.sendProgressWithSDP=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,r=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then((function(e){return t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:e})})).then((function(e){return t._dialog=e.session,e}))},t.prototype.sendProgressReliable=function(e){return void 0===e&&(e={}),e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)},t.prototype.sendProgressReliableWaitForPrack=function(e){var t=this;void 0===e&&(e={});var n,i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.statusCode||183,s=e.reasonPhrase,o=(e.extraHeaders||[]).slice();return o.push("Require: 100rel"),o.push("RSeq: "+this.rseq++),new Promise((function(e,a){t.waitingForPrack=!0,t.generateResponseOfferAnswer(t.incomingInviteRequest,i).then((function(e){return n=e,t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:s,extraHeaders:o,body:n})})).then((function(i){var c,u;t._dialog=i.session,i.session.delegate={onPrack:function(n){c=n,clearTimeout(l),clearTimeout(p),t.waitingForPrack&&(t.waitingForPrack=!1,t.handlePrackOfferAnswer(c).then((function(n){try{u=c.accept({statusCode:200,body:n}),t.prackArrived(),e({prackRequest:c,prackResponse:u,progressResponse:i})}catch(e){a(e)}})).catch((function(e){return a(e)})))}};var l=setTimeout((function(){t.waitingForPrack&&(t.waitingForPrack=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(p),t.reject({statusCode:504}).then((function(){return a(new nn)})).catch((function(e){return a(e)})))}),64*ct.T1),d=function(){try{t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:s,extraHeaders:o,body:n})}catch(e){return t.waitingForPrack=!1,void a(e)}p=setTimeout(d,h*=2)},h=ct.T1,p=setTimeout(d,h)})).catch((function(e){t.waitingForPrack=!1,a(e)}))}))},t.prototype.sendProgressTrying=function(){try{var e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((function(t,n){e.waitingForPrackResolve=t,e.waitingForPrackReject=n})),this.waitingForPrackPromise},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new nn),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t}(pn),yn=function(e){function t(t,n,i){void 0===i&&(i={});var r=e.call(this,t,i)||this;r.disposed=!1,r.earlyMedia=!1,r.earlyMediaSessionDescriptionHandlers=new Map,r.isCanceled=!1,r.inviteWithoutSdp=!1,r.logger=t.getLogger("sip.Inviter"),r.earlyMedia=void 0!==i.earlyMedia?i.earlyMedia:r.earlyMedia,r.fromTag=Ue(),r.inviteWithoutSdp=void 0!==i.inviteWithoutSdp?i.inviteWithoutSdp:r.inviteWithoutSdp;var o=s({},i);o.params=s({},i.params);var a=i.anonymous||!1,c=t.contact.toString({anonymous:a,outbound:a?!t.contact.tempGruu:!t.contact.pubGruu});a&&t.configuration.uri&&(o.params.fromDisplayName="Anonymous",o.params.fromUri="sip:anonymous@anonymous.invalid");var u=t.userAgentCore.configuration.aor;if(o.params.fromUri&&(u="string"==typeof o.params.fromUri?He.URIParse(o.params.fromUri):o.params.fromUri),!u)throw new TypeError("Invalid from URI: "+o.params.fromUri);var l=n;if(o.params.toUri&&(l="string"==typeof o.params.toUri?He.URIParse(o.params.toUri):o.params.toUri),!l)throw new TypeError("Invalid to URI: "+o.params.toUri);var d=s({},o.params);d.fromTag=r.fromTag;var h=(o.extraHeaders||[]).slice();a&&t.configuration.uri&&(h.push("P-Preferred-Identity: "+t.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+c),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.sipExtension100rel===hn.Required&&h.push("Require: 100rel"),t.configuration.sipExtensionReplaces===hn.Required&&h.push("Require: replaces"),o.extraHeaders=h;return r.outgoingRequestMessage=t.userAgentCore.makeOutgoingRequestMessage($e.INVITE,n,u,l,d,h,undefined),r._contact=c,r._referralInviterOptions=o,r._renderbody=i.renderbody,r._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(r.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(r.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(r.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(r.sessionDescriptionHandlerOptionsReInvite=i.sessionDescriptionHandlerOptionsReInvite),r._id=r.outgoingRequestMessage.callId+r.fromTag,r.userAgent._sessions[r._id]=r,r}return r(t,e),t.prototype.dispose=function(){var t=this;if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case Wt.Initial:case Wt.Establishing:return this.cancel().then((function(){return e.prototype.dispose.call(t)}));case Wt.Established:case Wt.Terminating:case Wt.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"body",{get:function(){return this.outgoingRequestMessage.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.outgoingRequestMessage.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.outgoingRequestMessage.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.outgoingRequestMessage},enumerable:!1,configurable:!0}),t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.logger.log("Inviter.cancel"),this.state!==Wt.Initial&&this.state!==Wt.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}if(this.isCanceled=!0,this.stateTransition(Wt.Terminating),this.outgoingInviteRequest){var n=void 0;e.statusCode&&e.reasonPhrase&&(n=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(je(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(n,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(Wt.Terminated);return Promise.resolve()},t.prototype.invite=function(t){var n=this;if(void 0===t&&(t={}),this.logger.log("Inviter.invite"),this.state!==Wt.Initial)return e.prototype.invite.call(this,t);if(t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),t.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(Wt.Establishing),Promise.resolve(this.sendInvite(t));var i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(i).then((function(e){return n.outgoingRequestMessage.body={body:e.content,contentType:e.contentType},n.stateTransition(Wt.Establishing),n.sendInvite(t)})).catch((function(e){throw n.logger.log(e.message),n.stateTransition(Wt.Terminated),e}))},t.prototype.sendInvite=function(e){var t=this;return void 0===e&&(e={}),this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:function(n){return t.dialog?(t.logger.log("Additional confirmed dialog, sending ACK and BYE"),void t.ackAndBye(n)):t.isCanceled?(t.logger.log("Canceled session accepted, sending ACK and BYE"),t.ackAndBye(n),void t.stateTransition(Wt.Terminated)):(t.notifyReferer(n),void t.onAccept(n).then((function(){t.disposeEarlyMedia()})).catch((function(){t.disposeEarlyMedia()})).then((function(){e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})))},onProgress:function(n){t.isCanceled||(t.notifyReferer(n),t.onProgress(n).catch((function(){t.disposeEarlyMedia()})).then((function(){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(n)})))},onRedirect:function(n){t.notifyReferer(n),t.onRedirect(n),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n)},onReject:function(n){t.notifyReferer(n),t.onReject(n),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)},onTrying:function(n){t.notifyReferer(n),t.onTrying(n),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(n)}}),this.outgoingInviteRequest},t.prototype.disposeEarlyMedia=function(){this.earlyMediaSessionDescriptionHandlers.forEach((function(e){e.close()})),this.earlyMediaSessionDescriptionHandlers.clear()},t.prototype.notifyReferer=function(e){var t=this;if(this._referred){if(!(this._referred instanceof pn))throw new Error("Referred session not instance of session");if(this._referred.dialog){if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");var n=e.message.statusCode,i=e.message.reasonPhrase,r="SIP/2.0 ".concat(n," ").concat(i).trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:r}}).delegate={onReject:function(){t._referred=void 0}}}}},t.prototype.onAccept=function(e){var t=this;if(this.logger.log("Inviter.onAccept"),this.state!==Wt.Establishing)return this.logger.error("Accept received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));var n=e.message,i=e.session;switch(n.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=He.nameAddrHeaderParse(n.getHeader("P-Asserted-Identity"))),i.delegate={onAck:function(e){return t.onAckRequest(e)},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},this._dialog=i,i.signalingState){case it.Initial:case it.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(Wt.Terminated),Promise.reject(new Error("Bad Media Description"));case it.HaveRemoteOffer:if(!this._dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this._dialog.signalingState,"."));var r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,r).then((function(n){e.ack({body:n}),t.stateTransition(Wt.Established)})).catch((function(n){throw t.ackAndBye(e,488,"Invalid session description"),t.stateTransition(Wt.Terminated),n}));case it.Stable:if(this.earlyMediaSessionDescriptionHandlers.size>0){var s=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!s)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(s),this.earlyMediaSessionDescriptionHandlers.delete(i.id),e.ack(),this.stateTransition(Wt.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){if(this.earlyMedia){this.logger.error("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.")}var o=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(o.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(Wt.Terminated),Promise.reject(o)}return e.ack(),this.stateTransition(Wt.Established),Promise.resolve()}var a=i.answer;if(!a)throw new Error("Answer is undefined.");r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(a,r).then((function(){var n;t._renderbody&&t._rendertype&&(n={body:{contentDisposition:"render",contentType:t._rendertype,content:t._renderbody}}),e.ack(n),t.stateTransition(Wt.Established)})).catch((function(n){throw t.logger.error(n.message),t.ackAndBye(e,488,"Not Acceptable Here"),t.stateTransition(Wt.Terminated),n}));case it.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onProgress=function(e){var t,n=this;if(this.logger.log("Inviter.onProgress"),this.state!==Wt.Establishing)return this.logger.error("Progress received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");var i=e.message,r=e.session;i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=He.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity")));var s=i.getHeader("require"),o=i.getHeader("rseq"),a=!!(s&&s.includes("100rel")&&o?Number(o):void 0),c=[];switch(a&&c.push("RAck: "+i.getHeader("rseq")+" "+i.getHeader("cseq")),r.signalingState){case it.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:c})),Promise.resolve();case it.HaveLocalOffer:return a&&e.prack({extraHeaders:c}),Promise.resolve();case it.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();var u=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(u,!0),this.earlyMediaSessionDescriptionHandlers.set(r.id,u),u.setDescription(i.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then((function(){return u.getDescription(n.sessionDescriptionHandlerOptions,n.sessionDescriptionHandlerModifiers)})).then((function(t){var n={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:c,body:n})})).catch((function(e){throw n.stateTransition(Wt.Terminated),e}));case it.Stable:if(a&&e.prack({extraHeaders:c}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=r;var l=r.answer;if(!l)throw new Error("Answer is undefined.");var d={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(l,d).catch((function(e){throw n.stateTransition(Wt.Terminated),e}))}return Promise.resolve();case it.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onRedirect=function(e){this.logger.log("Inviter.onRedirect"),this.state===Wt.Establishing||this.state===Wt.Terminating?this.stateTransition(Wt.Terminated):this.logger.error("Redirect received while in state ".concat(this.state,", dropping response"))},t.prototype.onReject=function(e){this.logger.log("Inviter.onReject"),this.state===Wt.Establishing||this.state===Wt.Terminating?this.stateTransition(Wt.Terminated):this.logger.error("Reject received while in state ".concat(this.state,", dropping response"))},t.prototype.onTrying=function(e){this.logger.log("Inviter.onTrying"),this.state===Wt.Establishing||this.logger.error("Trying received while in state ".concat(this.state,", dropping response"))},t}(pn),bn=function(){function e(e,t,n,i,r){void 0===i&&(i="text/plain"),void 0===r&&(r={}),this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};var o=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(o="string"==typeof r.params.fromUri?He.URIParse(r.params.fromUri):r.params.fromUri),!o)throw new TypeError("Invalid from URI: "+r.params.fromUri);var a=t;if(r.params.toUri&&(a="string"==typeof r.params.toUri?He.URIParse(r.params.toUri):r.params.toUri),!a)throw new TypeError("Invalid to URI: "+r.params.toUri);var c=r.params?s({},r.params):{},u=(r.extraHeaders||[]).slice(),l={contentDisposition:"render",contentType:i,content:n};this.request=e.userAgentCore.makeOutgoingRequestMessage($e.MESSAGE,t,o,a,c,u,l),this.userAgent=e}return e.prototype.message=function(e){return void 0===e&&(e={}),this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()},e}();!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(gn||(gn={})),function(){function e(e,t,n,i){void 0===i&&(i={}),this.disposed=!1,this._state=gn.Initial,this._stateEventEmitter=new an,this.userAgent=e,i.extraHeaders=(i.extraHeaders||[]).slice(),i.contentType=i.contentType||"text/plain","number"!=typeof i.expires||i.expires%1!=0?i.expires=3600:i.expires=Number(i.expires),"boolean"!=typeof i.unpublishOnClose&&(i.unpublishOnClose=!0),this.target=t,this.event=n,this.options=i,this.pubRequestExpires=i.expires,this.logger=e.getLogger("sip.Publisher");var r,s=i.params||{},o=s.fromUri?s.fromUri:e.userAgentCore.configuration.aor,a=s.toUri?s.toUri:t;if(i.body&&i.contentType){r={contentDisposition:"render",contentType:i.contentType,content:i.body}}var c=(i.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage($e.PUBLISH,t,o,a,s,c,r),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}e.prototype.dispose=function(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Publisher ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===gn.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()))},Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.publish=function(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()},e.prototype.unpublish=function(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()},e.prototype.receiveResponse=function(e){var t=this,n=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(n.toString()):break;case/^2[0-9]{2}$/.test(n.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")){var i=Number(e.getHeader("Expires"));"number"==typeof i&&i>=0&&i<=this.pubRequestExpires?this.pubRequestExpires=i: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((function(){return t.refreshRequest()}),900*this.pubRequestExpires),this._state!==gn.Published&&this.stateTransition(gn.Published)):this.stateTransition(gn.Unpublished);break;case/^412$/.test(n.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(gn.Unpublished),this.stateTransition(gn.Terminated);break;case/^423$/.test(n.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var r=Number(e.getHeader("Min-Expires"));if("number"==typeof r||r>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=r,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(gn.Unpublished),this.stateTransition(gn.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(gn.Unpublished),this.stateTransition(gn.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(gn.Unpublished),this.stateTransition(gn.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},e.prototype.send=function(){var e=this;return this.userAgent.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}})},e.prototype.refreshRequest=function(){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()},e.prototype.sendPublishRequest=function(){var e=s({},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);var t,n,i=this.target,r=this.options.params||{};if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");t={body:this.pubRequestBody,contentType:this.options.contentType}}return t&&(n=ze(t)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage($e.PUBLISH,i,r.fromUri?r.fromUri:this.userAgent.userAgentCore.configuration.aor,r.toUri?r.toUri:this.target,r,e.extraHeaders,n),this.send()},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case gn.Initial:e!==gn.Published&&e!==gn.Unpublished&&e!==gn.Terminated&&n();break;case gn.Published:e!==gn.Unpublished&&e!==gn.Terminated&&n();break;case gn.Unpublished:e!==gn.Published&&e!==gn.Terminated&&n();break;case gn.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===gn.Terminated&&this.dispose()}}(),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(fn||(fn={}));var wn,Tn=function(){function e(t,n){void 0===n&&(n={});var i=this;this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=fn.Initial,this._waiting=!1,this._stateEventEmitter=new an,this._waitingEventEmitter=new an,this.userAgent=t;var r=t.configuration.uri.clone();if(r.user=void 0,this.options=s(s(s({},e.defaultOptions()),{registrar:r}),e.stripUndefinedProperties(n)),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=e.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===He.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");var o=this.options.registrar,a=this.options.params&&this.options.params.fromUri||t.userAgentCore.configuration.aor,c=this.options.params&&this.options.params.toUri||t.configuration.uri,u=this.options.params||{},l=(n.extraHeaders||[]).slice();if(this.request=t.userAgentCore.makeOutgoingRequestMessage($e.REGISTER,o,a,c,u,l,void 0),this.expires=this.options.expires||e.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||e.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=t.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach((function(e){var t=i.options[e];if("registrar"===e)i.logger.log("· "+e+": "+t);else i.logger.log("· "+e+": "+JSON.stringify(t))}))),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}return e.defaultOptions=function(){return{expires:e.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new De("sip","anonymous","anonymous.invalid"),refreshFrequency:e.defaultRefreshFrequency}},e.newUUID=function(){var e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)}));return e},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce((function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t}),{})},Object.defineProperty(e.prototype,"contacts",{get:function(){return this._contacts.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"retryAfter",{get:function(){return this._retryAfter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){var e=this;return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Registerer ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._registerers[this.id],new Promise((function(t){var n=function(){if(!e.waiting&&e._state===fn.Registered)return e.stateChange.addListener((function(){e.terminated(),t()}),{once:!0}),void e.unregister();e.terminated(),t()};e.waiting?e.waitingChange.addListener((function(){n()}),{once:!0}):n()})))},e.prototype.register=function(e){var t=this;if(void 0===e&&(e={}),this.state===fn.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();var n=new en("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}e.requestOptions&&(this.options=s(s({},this.options),e.requestOptions));var i=(this.options.extraHeaders||[]).slice();i.push("Contact: "+this.generateContactHeader(this.expires)),i.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=i,this.waitingToggle(!0);var r=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){var i;n.message.hasHeader("expires")&&(i=Number(n.message.getHeader("expires"))),t._contacts=n.message.getHeaders("contact");var r,s,o=t._contacts.length;if(!o)return t.logger.error("No Contact header in response to REGISTER, dropping response."),void t.unregistered();for(;o--;){if(!(r=n.message.parseHeader("contact",o)))throw new Error("Contact undefined");if(t.userAgent.contact.pubGruu&&qe(r.uri,t.userAgent.contact.pubGruu)){i=Number(r.getParam("expires"));break}if(""===t.userAgent.configuration.contactName){if(r.uri.user===t.userAgent.contact.uri.user){i=Number(r.getParam("expires"));break}}else if(qe(r.uri,t.userAgent.contact.uri)){i=Number(r.getParam("expires"));break}r=void 0}if(void 0===r)return t.logger.error("No Contact header pointing to us, dropping response"),t.unregistered(),void t.waitingToggle(!1);if(void 0===i)return t.logger.error("Contact pointing to us is missing expires parameter, dropping response"),t.unregistered(),void t.waitingToggle(!1);r.hasParam("temp-gruu")&&((s=r.getParam("temp-gruu"))&&(t.userAgent.contact.tempGruu=He.URIParse(s.replace(/"/g,""))));r.hasParam("pub-gruu")&&((s=r.getParam("pub-gruu"))&&(t.userAgent.contact.pubGruu=He.URIParse(s.replace(/"/g,""))));t.registered(i),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Redirect received. Not supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){if(423===n.message.statusCode)return n.message.hasHeader("min-expires")?(t.expires=Number(n.message.getHeader("min-expires")),t.waitingToggle(!1),void t.register()):(t.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),t.unregistered(),void t.waitingToggle(!1));t.logger.warn("Failed to register, status code ".concat(n.message.statusCode));var i=NaN;if(500===n.message.statusCode||503===n.message.statusCode){var r=n.message.getHeader("retry-after");r&&(i=Number.parseInt(r,void 0))}t._retryAfter=isNaN(i)?void 0:i,t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t._retryAfter=void 0,t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(r)},e.prototype.unregister=function(e){var t=this;if(void 0===e&&(e={}),this.state===fn.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==fn.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();var n=new en("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}this._state===fn.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");var i=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=i,e.all?(i.push("Contact: *"),i.push("Expires: 0")):i.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);var r=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){t._contacts=n.message.getHeaders("contact"),t.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Unregister redirected. Not currently supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){t.logger.error("Unregister rejected with status code ".concat(n.message.statusCode)),t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(r)},e.prototype.clearTimers=function(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)},e.prototype.generateContactHeader=function(e){var t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach((function(e){t+=";"+e})),t+=";expires="+e},e.prototype.registered=function(e){var t=this;this.clearTimers(),this.registrationTimer=setTimeout((function(){t.registrationTimer=void 0,t.register()}),this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout((function(){t.logger.warn("Registration expired"),t.unregistered()}),1e3*e),this._state!==fn.Registered&&this.stateTransition(fn.Registered)},e.prototype.unregistered=function(){this.clearTimers(),this._state!==fn.Unregistered&&this.stateTransition(fn.Unregistered)},e.prototype.terminated=function(){this.clearTimers(),this._state!==fn.Terminated&&this.stateTransition(fn.Terminated)},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case fn.Initial:e!==fn.Registered&&e!==fn.Unregistered&&e!==fn.Terminated&&n();break;case fn.Registered:e!==fn.Unregistered&&e!==fn.Terminated&&n();break;case fn.Unregistered:e!==fn.Registered&&e!==fn.Terminated&&n();break;case fn.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===fn.Terminated&&this.dispose()},Object.defineProperty(e.prototype,"waiting",{get:function(){return this._waiting},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"waitingChange",{get:function(){return this._waitingEventEmitter},enumerable:!1,configurable:!0}),e.prototype.waitingToggle=function(e){if(this._waiting===e)throw new Error("Invalid waiting transition from ".concat(this._waiting," to ").concat(e));this._waiting=e,this.logger.log("Waiting toggled to ".concat(this._waiting)),this._waitingEventEmitter.emit(this._waiting)},e.prototype.waitingWarning=function(){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.")},e.prototype.stateError=function(){var e=this.state===fn.Terminated?"is in 'Terminated' state":"has been disposed",t="An attempt was made to send a REGISTER request when the Registerer ".concat(e,".");t+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",t+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(t)},e.defaultExpires=600,e.defaultRefreshFrequency=99,e}();!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(wn||(wn={})),function(e){function t(t,n,i,r){void 0===r&&(r={});var s=e.call(this,t,r)||this;return s.body=void 0,s.logger=t.getLogger("sip.Subscriber"),r.body&&(s.body={body:r.body,contentType:r.contentType?r.contentType:"application/sdp"}),s.targetURI=n,s.event=i,void 0===r.expires?s.expires=3600:"number"!=typeof r.expires?(s.logger.warn('Option "expires" must be a number. Using default of 3600.'),s.expires=3600):s.expires=r.expires,s.extraHeaders=(r.extraHeaders||[]).slice(),s.subscriberRequest=s.initSubscriberRequest(),s.outgoingRequestMessage=s.subscriberRequest.message,s.id=s.outgoingRequestMessage.callId+s.outgoingRequestMessage.from.parameters.tag+s.event,s._userAgent._subscriptions[s.id]=s,s}r(t,e),t.prototype.dispose=function(){var t=this;return this.disposed?Promise.resolve():(this.logger.log("Subscription ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),e.prototype.dispose.call(this).then((function(){if(t.state===wn.Subscribed){if(!t._dialog)throw new Error("Dialog undefined.");if(t._dialog.subscriptionState===Ht.Pending||t._dialog.subscriptionState===Ht.Active){var e=t._dialog;return new Promise((function(t,n){e.delegate={onTerminated:function(){return t()}},e.unsubscribe()}))}}})))},t.prototype.subscribe=function(e){var t=this;switch(this.subscriberRequest.state){case Ht.Initial:this.state===wn.Initial&&this.stateTransition(wn.NotifyWait),this.subscriberRequest.subscribe().then((function(e){e.success?(e.success.subscription&&(t._dialog=e.success.subscription,t._dialog.delegate={onNotify:function(e){return t.onNotify(e)},onRefresh:function(e){return t.onRefresh(e)},onTerminated:function(){t.state!==wn.Terminated&&t.stateTransition(wn.Terminated)}}),t.onNotify(e.success.request)):e.failure&&t.unsubscribe()}));break;case Ht.NotifyWait:case Ht.Pending:break;case Ht.Active:if(this._dialog)this._dialog.refresh().delegate={onAccept:function(e){return t.onAccepted(e)},onRedirect:function(e){return t.unsubscribe()},onReject:function(e){return t.unsubscribe()}};case Ht.Terminated:}return Promise.resolve()},t.prototype.unsubscribe=function(e){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case Ht.Initial:case Ht.NotifyWait:break;case Ht.Pending:case Ht.Active:this._dialog&&this._dialog.unsubscribe();break;case Ht.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(wn.Terminated),Promise.resolve()},t.prototype._refresh=function(){return this.subscriberRequest.state===Ht.Active?this.subscribe():Promise.resolve()},t.prototype.onAccepted=function(e){},t.prototype.onNotify=function(e){var t=this;if(this.disposed)e.accept();else{if(this.state!==wn.Subscribed&&this.stateTransition(wn.Subscribed),this.delegate&&this.delegate.onNotify){var n=new ln(e);this.delegate.onNotify(n)}else e.accept();var i=e.message.parseHeader("Subscription-State");if(i&&i.state&&"terminated"===i.state){if(i.reason)switch(this.logger.log("Terminated subscription with reason ".concat(i.reason)),i.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(i.params&&i.params["retry-after"]?this.retryAfterTimer=setTimeout((function(){t.subscribe()}),i.params["retry-after"]):this.subscribe())}this.unsubscribe()}}},t.prototype.onRefresh=function(e){var t=this;e.delegate={onAccept:function(e){return t.onAccepted(e)}}},t.prototype.initSubscriberRequest=function(){var e=this,t={extraHeaders:this.extraHeaders,body:this.body?ze(this.body):void 0};return this.subscriberRequest=new In(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,t),this.subscriberRequest.delegate={onAccept:function(t){return e.onAccepted(t)}},this.subscriberRequest}}(function(){function e(e,t){void 0===t&&(t={}),this._disposed=!1,this._state=wn.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new an,this._userAgent=e,this.delegate=t.delegate}return e.prototype.dispose=function(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()},Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disposed",{get:function(){return this._disposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case wn.Initial:e!==wn.NotifyWait&&e!==wn.Terminated&&n();break;case wn.NotifyWait:e!==wn.Subscribed&&e!==wn.Terminated&&n();break;case wn.Subscribed:e!==wn.Terminated&&n();break;case wn.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log("Subscription ".concat(this._dialog?this._dialog.id:void 0," transitioned to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===wn.Terminated&&this.dispose())},e}());var Sn,En,In=function(){function e(e,t,n,i,r,s){this.core=e,this.target=t,this.event=n,this.expires=i,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=s;var o="Allow: "+Mt.toString(),a=(r&&r.extraHeaders||[]).slice();a.push(o),a.push("Event: "+this.event),a.push("Expires: "+this.expires),a.push("Contact: "+this.core.configuration.contact.toString());var c=r&&r.body;this.message=e.makeOutgoingRequestMessage($e.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},a,c)}return e.prototype.dispose=function(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)},Object.defineProperty(e.prototype,"state",{get:function(){return this.subscription?this.subscription.subscriptionState:this.subscribed?Ht.NotifyWait:Ht.Initial},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(){var e=this;return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise((function(t){if(!e.message)throw new Error("Message undefined.");e.request=e.core.subscribe(e.message,{onAccept:function(t){e.delegate&&e.delegate.onAccept&&e.delegate.onAccept(t)},onNotify:function(n){e.subscription=n.subscription,e.subscription&&(e.subscription.autoRefresh=!0),t({success:n})},onNotifyTimeout:function(){t({failure:{}})},onRedirect:function(e){t({failure:{response:e}})},onReject:function(e){t({failure:{response:e}})}})})))},e}();!function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(Sn||(Sn={})),function(e){e.Started="Started",e.Stopped="Stopped"}(En||(En={}));var Rn=function(){function e(e,t,n){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=n,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==n?void 0:n.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}return Object.defineProperty(e.prototype,"localMediaStream",{get:function(){return this._localMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){return this._remoteMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dataChannel},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnection",{get:function(){return this._peerConnection},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnectionDelegate",{get:function(){return this._peerConnectionDelegate},set:function(e){this._peerConnectionDelegate=e},enumerable:!1,configurable:!0}),e.dispatchAddTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))},e.dispatchRemoveTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))},e.prototype.close=function(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach((function(e){e.track&&e.track.stop()})),this._peerConnection.getSenders().forEach((function(e){e.track&&e.track.stop()})),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)},e.prototype.getDescription=function(e,t){var n,i,r=this;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;var s=null===(n=null==e?void 0:e.offerOptions)||void 0===n?void 0:n.iceRestart,o=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then((function(){return r.updateDirection(e)})).then((function(){return r.createDataChannel(e)})).then((function(){return r.createLocalOfferOrAnswer(e)})).then((function(e){return r.applyModifiers(e,t)})).then((function(e){return r.setLocalSessionDescription(e)})).then((function(){return r.waitForIceGatheringComplete(s,o)})).then((function(){return r.getLocalSessionDescription()})).then((function(e){return{body:e.sdp,contentType:"application/sdp"}})).catch((function(e){throw r.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e}))},e.prototype.hasDescription=function(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e},e.prototype.sendDtmf=function(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;var n=this._peerConnection.getSenders();if(0===n.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;var i=n[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;var r=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,s)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0},e.prototype.setDescription=function(e,t,n){var i=this;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;var r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then((function(){return i.applyModifiers({sdp:e,type:r},n)})).then((function(e){return i.setRemoteSessionDescription(e)})).catch((function(e){throw i.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e}))},e.prototype.applyModifiers=function(e,t){var n=this;return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((function(e,t){return e.then(t)}),Promise.resolve(e)).then((function(e){if(n.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)},e.prototype.createDataChannel=function(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();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.createLocalOfferOrAnswer=function(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);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.getLocalMediaStream=function(e){var t=this;if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var n=s({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(n.audio=n.audio||this.localMediaStreamConstraints.audio,n.video=n.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(n.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(n.video))return Promise.resolve()}else void 0===n.audio&&void 0===n.video&&(n={audio:!0});return this.localMediaStreamConstraints=n,this.mediaStreamFactory(n,this).then((function(e){return t.setLocalMediaStream(e)}))},e.prototype.setLocalMediaStream=function(t){var n=this;if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");var i=this._peerConnection,r=this._localMediaStream,s=[],o=function(t){var o=t.kind;if("audio"!==o&&"video"!==o)throw new Error("Unknown new track kind ".concat(o,"."));var a=i.getSenders().find((function(e){return e.track&&e.track.kind===o}));a?s.push(new Promise((function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - replacing sender ".concat(o," track")),e()})).then((function(){return a.replaceTrack(t).then((function(){var n=r.getTracks().find((function(e){return e.kind===o}));n&&(n.stop(),r.removeTrack(n),e.dispatchRemoveTrackEvent(r,n)),r.addTrack(t),e.dispatchAddTrackEvent(r,t)})).catch((function(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ".concat(o," track")),e}))}))):s.push(new Promise((function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - adding sender ".concat(o," track")),e()})).then((function(){try{i.addTrack(t,r)}catch(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to add sender ".concat(o," track")),e}r.addTrack(t),e.dispatchAddTrackEvent(r,t)})))},a=t.getAudioTracks();a.length&&o(a[0]);var c=t.getVideoTracks();return c.length&&o(c[0]),s.reduce((function(e,t){return e.then((function(){return t}))}),Promise.resolve())},e.prototype.getLocalSessionDescription=function(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))},e.prototype.setLocalSessionDescription=function(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)},e.prototype.setRemoteSessionDescription=function(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var t,n=e.sdp;switch(this._peerConnection.signalingState){case"stable":t="offer";break;case"have-local-offer":t="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return n?this._peerConnection.setRemoteDescription({sdp:n,type:t}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))},e.prototype.setRemoteTrack=function(t){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");var n=this._remoteMediaStream;n.getTrackById(t.id)?this.logger.debug("SessionDescriptionHandler.setRemoteTrack - have remote ".concat(t.kind," track")):"audio"===t.kind?(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getAudioTracks().forEach((function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)})),n.addTrack(t),e.dispatchAddTrackEvent(n,t)):"video"===t.kind&&(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getVideoTracks().forEach((function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)})),n.addTrack(t),e.dispatchAddTrackEvent(n,t))},e.prototype.updateDirection=function(e){var t=this;if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");this._peerConnection.getTransceivers().forEach((function(t){if(t.direction){var n=function(t){switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}}(t.direction);t.direction!==n&&(t.direction=n)}}));break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");var n=function(){var e=t._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");var n=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(n)switch(n[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"}(),i=function(){switch(n){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}}();this._peerConnection.getTransceivers().forEach((function(e){e.direction&&"stopped"!==e.direction&&e.direction!==i&&(e.direction=i)}));break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()},e.prototype.iceGatheringComplete=function(){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)},e.prototype.waitForIceGatheringComplete=function(e,t){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=0),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((function(e,i){n.iceGatheringCompleteResolve=e,n.iceGatheringCompleteReject=i,t>0&&(n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),n.iceGatheringCompleteTimeoutId=setTimeout((function(){n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),n.iceGatheringComplete()}),t))})),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())},e.prototype.initPeerConnectionEventHandlers=function(){var e=this;if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");var t=this._peerConnection;t.onconnectionstatechange=function(n){var i,r=t.connectionState;e.logger.debug("SessionDescriptionHandler.onconnectionstatechange ".concat(r)),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.onconnectionstatechange)&&e._peerConnectionDelegate.onconnectionstatechange(n)},t.ondatachannel=function(t){var n;e.logger.debug("SessionDescriptionHandler.ondatachannel"),e._dataChannel=t.channel,e.onDataChannel&&e.onDataChannel(e._dataChannel),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ondatachannel)&&e._peerConnectionDelegate.ondatachannel(t)},t.onicecandidate=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidate)&&e._peerConnectionDelegate.onicecandidate(t)},t.onicecandidateerror=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidateerror)&&e._peerConnectionDelegate.onicecandidateerror(t)},t.oniceconnectionstatechange=function(n){var i,r=t.iceConnectionState;e.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange ".concat(r)),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.oniceconnectionstatechange)&&e._peerConnectionDelegate.oniceconnectionstatechange(n)},t.onicegatheringstatechange=function(n){var i,r=t.iceGatheringState;e.logger.debug("SessionDescriptionHandler.onicegatheringstatechange ".concat(r)),"complete"===r&&e.iceGatheringComplete(),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.onicegatheringstatechange)&&e._peerConnectionDelegate.onicegatheringstatechange(n)},t.onnegotiationneeded=function(t){var n;e.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onnegotiationneeded)&&e._peerConnectionDelegate.onnegotiationneeded(t)},t.onsignalingstatechange=function(n){var i,r=t.signalingState;e.logger.debug("SessionDescriptionHandler.onsignalingstatechange ".concat(r)),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.onsignalingstatechange)&&e._peerConnectionDelegate.onsignalingstatechange(n)},t.onstatsended=function(t){var n;e.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onstatsended)&&e._peerConnectionDelegate.onstatsended(t)},t.ontrack=function(t){var n,i=t.track.kind,r=t.track.enabled?"enabled":"disabled";e.logger.debug("SessionDescriptionHandler.ontrack ".concat(i," ").concat(r)),e.setRemoteTrack(t.track),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ontrack)&&e._peerConnectionDelegate.ontrack(t)}},e}();function kn(e){return function(t,n){void 0===e&&(e=function(e){return 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)});var i={iceGatheringTimeout:void 0!==(null==n?void 0:n.iceGatheringTimeout)?null==n?void 0:n.iceGatheringTimeout:5e3,peerConnectionConfiguration:s(s({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}),null==n?void 0:n.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new Rn(r,e,i)}}var Cn=function(){function e(t,n){if(this._state=Sn.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new an,this.logger=t,n){var i=n,r=null==i?void 0:i.wsServers,o=null==i?void 0:i.maxReconnectionAttempts;if(void 0!==r){var a='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(a)}if(void 0!==o){a='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(a)}r&&!n.server&&("string"==typeof r&&(n.server=r),r instanceof Array&&(n.server=r[0]))}this.configuration=s(s({},e.defaultOptions),n);var c=this.configuration.server,u=He.parse(c,"absoluteURI");if(-1===u)throw this.logger.error('Invalid WebSocket Server URL "'.concat(c,'"')),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(u.scheme))throw this.logger.error('Invalid scheme in WebSocket Server URL "'.concat(c,'"')),new Error("Invalid scheme in WebSocket Server URL");this._protocol=u.scheme.toUpperCase()}return e.prototype.dispose=function(){return this.disconnect()},Object.defineProperty(e.prototype,"protocol",{get:function(){return this._protocol},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"server",{get:function(){return this.configuration.server},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ws",{get:function(){return this._ws},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this._connect()},e.prototype.disconnect=function(){return this._disconnect()},e.prototype.isConnected=function(){return this.state===Sn.Connected},e.prototype.send=function(e){return this._send(e)},e.prototype._connect=function(){var e,t=this;switch(this.logger.log("Connecting ".concat(this.server)),this.state){case Sn.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case Sn.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case Sn.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Sn.Connecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;case Sn.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Sn.Connecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}try{(e=new WebSocket(this.server,"sip")).binaryType="arraybuffer",e.addEventListener("close",(function(n){return t.onWebSocketClose(n,e)})),e.addEventListener("error",(function(n){return t.onWebSocketError(n,e)})),e.addEventListener("open",(function(n){return t.onWebSocketOpen(n,e)})),e.addEventListener("message",(function(n){return t.onWebSocketMessage(n,e)})),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise((function(n,i){t.connectResolve=n,t.connectReject=i,t.transitionState(Sn.Disconnected,e)}))}return this.connectPromise=new Promise((function(n,i){t.connectResolve=n,t.connectReject=i,t.connectTimeout=setTimeout((function(){t.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s."),e.close(1e3)}),1e3*t.configuration.connectionTimeout)})),this.connectPromise},e.prototype._disconnect=function(){var e=this;switch(this.logger.log("Disconnecting ".concat(this.server)),this.state){case Sn.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Sn.Disconnecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;case Sn.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Sn.Disconnecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;case Sn.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case Sn.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.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.");var t=this._ws;return this.disconnectPromise=new Promise((function(n,i){e.disconnectResolve=n,e.disconnectReject=i;try{t.close(1e3)}catch(t){throw e.logger.error("WebSocket close failed."),e.logger.error(t),t}})),this.disconnectPromise},e.prototype._send=function(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==Sn.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()},e.prototype.onWebSocketClose=function(e,t){if(t===this._ws){var n="WebSocket closed ".concat(this.server," (code: ").concat(e.code,")"),i=this.disconnectPromise?void 0:new Error(n);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(n),this._ws=void 0,this.transitionState(Sn.Disconnected,i)}},e.prototype.onWebSocketError=function(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")},e.prototype.onWebSocketMessage=function(e,t){if(t===this._ws){var n,i=e.data;if(/^(\r\n)+$/.test(i))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(i){if("string"!=typeof i){try{n=(new TextDecoder).decode(new Uint8Array(i))}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"+n+"\n")}else n=i,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===Sn.Connected){if(this.onMessage)try{this.onMessage(n)}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...")}},e.prototype.onWebSocketOpen=function(e,t){t===this._ws&&this._state===Sn.Connecting&&(this.logger.log("WebSocket opened ".concat(this.server)),this.transitionState(Sn.Connected))},e.prototype.transitionLoopDetectedError=function(e){var t="A state transition loop has been detected.";return t+=" An attempt to transition from ".concat(this._state," to ").concat(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 rn("Loop detected.")},e.prototype.transitionState=function(e,t){var n=this,i=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case Sn.Connecting:e!==Sn.Connected&&e!==Sn.Disconnecting&&e!==Sn.Disconnected&&i();break;case Sn.Connected:e!==Sn.Disconnecting&&e!==Sn.Disconnected&&i();break;case Sn.Disconnecting:e!==Sn.Connecting&&e!==Sn.Disconnected&&i();break;case Sn.Disconnected:e!==Sn.Connecting&&i();break;default:throw new Error("Unknown state.")}var r=this._state;this._state=e;var s=this.connectResolve,o=this.connectReject;r===Sn.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);var a=this.disconnectResolve,c=this.disconnectReject;if(r===Sn.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 ".concat(r," to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===Sn.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===Sn.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===Sn.Connecting){if(!s)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===Sn.Connected?s():o(t||new Error("Connect aborted."))}if(r===Sn.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!c)throw new Error("Disconnect reject undefined.");e===Sn.Disconnected?a():c(t||new Error("Disconnect aborted."))}this.transitioningState=!1},e.prototype.clearKeepAliveTimeout=function(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0},e.prototype.sendKeepAlive=function(){var e=this;return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout((function(){e.clearKeepAliveTimeout()}),1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))},e.prototype.startSendingKeepAlives=function(){var e,t,n=this;this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval((function(){n.sendKeepAlive(),n.startSendingKeepAlives()}),(e=this.configuration.keepAliveInterval,t=.8*e,1e3*(Math.random()*(e-t)+t))))},e.prototype.stopSendingKeepAlives=function(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0},e.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0},e}(),An=function(){function e(t){void 0===t&&(t={});var n=this;if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=En.Stopped,this.unloadListener=function(){n.stop()},this._stateEventEmitter=new an,this.delegate=t.delegate,this.options=s(s(s(s(s({},e.defaultOptions()),{sipjsId:Me(5)}),{uri:new De("sip","anonymous."+Me(6),"anonymous.invalid")}),{viaHost:Me(12)+".invalid"}),e.stripUndefinedProperties(t)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){var i=Math.floor(254*Math.random()+1);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Lt,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=Nt.error;break;case"warn":this.loggerFactory.level=Nt.warn;break;case"log":this.loggerFactory.level=Nt.log;break;case"debug":this.loggerFactory.level=Nt.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach((function(e){var t=n.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":n.logger.log("· "+e+": "+t);break;case"authorizationPassword":n.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":n.logger.log("· "+e+": "+t.name);break;default:n.logger.log("· "+e+": "+JSON.stringify(t))}}))),this.options.transportOptions){var r=this.options.transportOptions,o=r.maxReconnectionAttempts,a=r.reconnectionTimeout;if(void 0!==o){var c='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(c)}if(void 0!==a){c='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(c)}void 0===t.reconnectionDelay&&void 0!==a&&(this.options.reconnectionDelay=a),void 0===t.reconnectionAttempts&&void 0!==o&&(this.options.reconnectionAttempts=o)}if(void 0!==t.reconnectionDelay){c='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(c)}if(void 0!==t.reconnectionAttempts){c='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(c)}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()}return e.makeURI=function(e){return He.URIParse(e)},e.defaultOptions=function(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:function(){},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:kn(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:hn.Unsupported,sipExtensionReplaces:hn.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Cn,transportOptions:{},uri:new De("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.20.0",viaHost:""}},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce((function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t}),{})},Object.defineProperty(e.prototype,"configuration",{get:function(){return this.options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contact",{get:function(){return this._contact},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this._userAgentCore},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){return this.loggerFactory.getLogger(e,t)},e.prototype.getLoggerFactory=function(){return this.loggerFactory},e.prototype.isConnected=function(){return this.transport.isConnected()},e.prototype.reconnect=function(){var e=this;return this.state===En.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then((function(){return e.transport.connect()}))},e.prototype.start=function(){if(this.state===En.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting ".concat(this.configuration.uri)),this.transitionState(En.Started),this.options.autoStop){var 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()},e.prototype.stop=function(){return o(this,void 0,void 0,(function(){var e,t,n,i,r,o,c,u,l,d,h,p,g,f,m,v,y,b,w,T,S,E,I,R,k,C,A,P=this;return a(this,(function(_){switch(_.label){case 0:if(this.state===En.Stopped)return this.logger.warn("User agent already stopped"),[2,Promise.resolve()];for(h in this.logger.log("Stopping ".concat(this.configuration.uri)),this.transitionState(En.Stopped),this.options.autoStop&&(e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime),"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)),t=s({},this._publishers),n=s({},this._registerers),i=s({},this._sessions),r=s({},this._subscriptions),o=this.transport,c=this.userAgentCore,this.logger.log("Dispose of registerers"),u=function(e){return a(this,(function(t){switch(t.label){case 0:return n[e]?[4,n[e].dispose().catch((function(t){throw P.logger.error(t.message),delete P._registerers[e],t}))]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))},d=[],l=n)d.push(h);p=0,_.label=1;case 1:return p<d.length?(h=d[p])in l?[5,u(h)]:[3,3]:[3,4];case 2:_.sent(),_.label=3;case 3:return p++,[3,1];case 4:for(v in this.logger.log("Dispose of sessions"),g=function(e){return a(this,(function(t){switch(t.label){case 0:return i[e]?[4,i[e].dispose().catch((function(t){throw P.logger.error(t.message),delete P._sessions[e],t}))]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))},m=[],f=i)m.push(v);y=0,_.label=5;case 5:return y<m.length?(v=m[y])in f?[5,g(v)]:[3,7]:[3,8];case 6:_.sent(),_.label=7;case 7:return y++,[3,5];case 8:for(S in this.logger.log("Dispose of subscriptions"),b=function(e){return a(this,(function(t){switch(t.label){case 0:return r[e]?[4,r[e].dispose().catch((function(t){throw P.logger.error(t.message),delete P._subscriptions[e],t}))]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))},T=[],w=r)T.push(S);E=0,_.label=9;case 9:return E<T.length?(S=T[E])in w?[5,b(S)]:[3,11]:[3,12];case 10:_.sent(),_.label=11;case 11:return E++,[3,9];case 12:for(C in this.logger.log("Dispose of publishers"),I=function(e){return a(this,(function(n){switch(n.label){case 0:return t[e]?[4,t[e].dispose().catch((function(t){throw P.logger.error(t.message),delete P._publishers[e],t}))]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}}))},k=[],R=t)k.push(C);A=0,_.label=13;case 13:return A<k.length?(C=k[A])in R?[5,I(C)]:[3,15]:[3,16];case 14:_.sent(),_.label=15;case 15:return A++,[3,13];case 16:return this.logger.log("Dispose of transport"),[4,o.dispose().catch((function(e){throw P.logger.error(e.message),e}))];case 17:return _.sent(),this.logger.log("Dispose of core"),c.dispose(),[2]}}))}))},e.prototype._makeInviter=function(e,t){return new yn(this,e,t)},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;e>n?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - trying")),setTimeout((function(){t.reconnect().then((function(){t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - succeeded"))})).catch((function(i){t.logger.error(i.message),t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - failed")),t.attemptReconnection(++e)}))}),1===e?0:1e3*i))},e.prototype.initContact=function(){var e=this,t=""!==this.options.contactName?this.options.contactName:Me(8),n=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new De("sip",t,this.options.viaHost,void 0,n),toString:function(t){void 0===t&&(t={});var i=t.anonymous||!1,r=t.outbound||!1,s="<";return s+=i?e.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport=".concat(n.transport?n.transport:"ws"):e.contact.pubGruu||e.contact.uri,r&&(s+=";ob"),s+=">"}}},e.prototype.initCore=function(){var e=this,t=[];t.push("outbound"),this.options.sipExtension100rel===hn.Supported&&t.push("100rel"),this.options.sipExtensionReplaces===hn.Supported&&t.push("replaces"),this.options.sipExtensionExtraSupported&&t.push.apply(t,this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(t=t.filter((function(e){return mn[e]})));var n=(t=Array.from(new Set(t))).slice();(this.contact.pubGruu||this.contact.tempGruu)&&n.push("gruu");var i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:t,supportedOptionTagsResponse:n,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:function(){var t=e.options.authorizationUsername?e.options.authorizationUsername:e.options.uri.user,n=e.options.authorizationPassword?e.options.authorizationPassword:void 0,i=e.options.authorizationHa1?e.options.authorizationHa1:void 0;return new et(e.getLoggerFactory(),i,t,n)},transportAccessor:function(){return e.transport}};return new Qt(i,{onInvite:function(t){var n,i=new vn(e,t);if(t.delegate={onCancel:function(e){i._onCancel(e)},onTransportError:function(t){e.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},t.trying(),e.options.sipExtensionReplaces!==hn.Unsupported){var r=t.message.parseHeader("replaces");if(r){var s=r.call_id;if("string"!=typeof s)throw new Error("Type of call id is not string");var o=r.replaces_to_tag;if("string"!=typeof o)throw new Error("Type of to tag is not string");var a=r.replaces_from_tag;if("string"!=typeof a)throw new Error("type of from tag is not string");var c=s+o+a,u=e.userAgentCore.dialogs.get(c);if(!u)return void i.reject({statusCode:481});if(!u.early&&!0===r.early_only)return void i.reject({statusCode:486});var l=e._sessions[s+a]||e._sessions[s+o]||void 0;if(!l)throw new Error("Session does not exist.");i._replacee=l}}if(null===(n=e.delegate)||void 0===n?void 0:n.onInvite)return i.autoSendAnInitialProvisionalResponse?void i.progress().then((function(){var t;if(void 0===(null===(t=e.delegate)||void 0===t?void 0:t.onInvite))throw new Error("onInvite undefined.");e.delegate.onInvite(i)})):void e.delegate.onInvite(i);i.reject({statusCode:486})},onMessage:function(t){if(e.delegate&&e.delegate.onMessage){var n=new un(t);e.delegate.onMessage(n)}else t.accept()},onNotify:function(t){if(e.delegate&&e.delegate.onNotify){var n=new ln(t);e.delegate.onNotify(n)}else e.options.allowLegacyNotifications?t.accept():t.reject({statusCode:481})},onRefer:function(t){e.logger.warn("Received an out of dialog REFER request"),e.delegate&&e.delegate.onReferRequest?e.delegate.onReferRequest(t):t.reject({statusCode:405})},onRegister:function(t){e.logger.warn("Received an out of dialog REGISTER request"),e.delegate&&e.delegate.onRegisterRequest?e.delegate.onRegisterRequest(t):t.reject({statusCode:405})},onSubscribe:function(t){e.logger.warn("Received an out of dialog SUBSCRIBE request"),e.delegate&&e.delegate.onSubscribeRequest?e.delegate.onSubscribeRequest(t):t.reject({statusCode:405})}})},e.prototype.initTransportCallbacks=function(){var e=this;this.transport.onConnect=function(){return e.onTransportConnect()},this.transport.onDisconnect=function(t){return e.onTransportDisconnect(t)},this.transport.onMessage=function(t){return e.onTransportMessage(t)}},e.prototype.onTransportConnect=function(){this.state!==En.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()},e.prototype.onTransportDisconnect=function(e){this.state!==En.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())},e.prototype.onTransportMessage=function(e){var t=this,n=Xe.parseMessage(e,this.getLogger("sip.Parser"));if(n)if(this.state===En.Stopped&&n instanceof Ve)this.logger.warn("Received ".concat(n.method," request while stopped. Dropping."));else{var i=function(){for(var e=0,i=["from","to","call_id","cseq","via"];e<i.length;e++){var r=i[e];if(!n.hasHeader(r))return t.logger.warn("Missing mandatory header field : ".concat(r,".")),!1}return!0};if(n instanceof Ve){if(!i())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!n.toTag&&n.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(n,{statusCode:482});var r=Le(n.body);if((s=n.getHeader("content-length"))&&r<Number(s))return void this.userAgentCore.replyStateless(n,{statusCode:400})}if(n instanceof Ge){if(!i())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(n.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(n.via.host!==this.options.viaHost||void 0!==n.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var s;r=Le(n.body);if((s=n.getHeader("content-length"))&&r<Number(s))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(n instanceof Ve)this.userAgentCore.receiveIncomingRequestFromTransport(n);else{if(!(n instanceof Ge))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(n)}}else this.logger.warn("Failed to parse incoming message. Dropping.")},e.prototype.transitionState=function(e,t){var n=this,i=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};switch(this._state){case En.Started:e!==En.Stopped&&i();break;case En.Stopped:e!==En.Started&&i();break;default:throw new Error("Unknown state.")}this.logger.log("Transitioned from ".concat(this._state," to ").concat(e)),this._state=e,this._stateEventEmitter.emit(this._state)},e}();!function(){function e(e,t){void 0===t&&(t={});var n=this;this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.muted=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=s({},t);var i=s({},t.userAgentOptions);if(i.transportConstructor||(i.transportConstructor=Cn),i.transportOptions||(i.transportOptions={server:e}),!i.uri&&t.aor){var r=An.makeURI(t.aor);if(!r)throw new Error("Failed to create valid URI from ".concat(t.aor));i.uri=r}this.userAgent=new An(i),this.userAgent.delegate={onConnect:function(){n.logger.log("[".concat(n.id,"] Connected")),n.delegate&&n.delegate.onServerConnect&&n.delegate.onServerConnect(),n.registerer&&n.registerRequested&&(n.logger.log("[".concat(n.id,"] Registering...")),n.registerer.register().catch((function(e){n.logger.error("[".concat(n.id,"] Error occurred registering after connection with server was obtained.")),n.logger.error(e.toString())})))},onDisconnect:function(e){n.logger.log("[".concat(n.id,"] Disconnected")),n.delegate&&n.delegate.onServerDisconnect&&n.delegate.onServerDisconnect(e),n.session&&(n.logger.log("[".concat(n.id,"] Hanging up...")),n.hangup().catch((function(e){n.logger.error("[".concat(n.id,"] Error occurred hanging up call after connection with server was lost.")),n.logger.error(e.toString())}))),n.registerer&&(n.logger.log("[".concat(n.id,"] Unregistering...")),n.registerer.unregister().catch((function(e){n.logger.error("[".concat(n.id,"] Error occurred unregistering after connection with server was lost.")),n.logger.error(e.toString())}))),e&&n.attemptReconnection()},onInvite:function(e){if(n.logger.log("[".concat(n.id,"] Received INVITE")),n.session)return n.logger.warn("[".concat(n.id,"] Session already in progress, rejecting INVITE...")),void e.reject().then((function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))})).catch((function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())}));var t={sessionDescriptionHandlerOptions:{constraints:n.constraints}};n.initSession(e,t),n.delegate&&n.delegate.onCallReceived?n.delegate.onCallReceived():(n.logger.warn("[".concat(n.id,"] No handler available, rejecting INVITE...")),e.reject().then((function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))})).catch((function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())})))},onMessage:function(e){e.accept().then((function(){n.delegate&&n.delegate.onMessageReceived&&n.delegate.onMessageReceived(e.request.body)}))}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",(function(){n.logger.log("[".concat(n.id,"] Online")),n.attemptReconnection()}))}Object.defineProperty(e.prototype,"id",{get:function(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof Rn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof Rn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localAudioTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find((function(e){return"audio"===e.kind}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localVideoTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find((function(e){return"video"===e.kind}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteAudioTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find((function(e){return"audio"===e.kind}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteVideoTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find((function(e){return"video"===e.kind}))},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this.logger.log("[".concat(this.id,"] Connecting UserAgent...")),this.connectRequested=!0,this.userAgent.state!==En.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.disconnect=function(){return this.logger.log("[".concat(this.id,"] Disconnecting UserAgent...")),this.connectRequested=!1,this.userAgent.stop()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e.prototype.register=function(e,t){var n=this;return this.logger.log("[".concat(this.id,"] Registering UserAgent...")),this.registerRequested=!0,this.registerer||(this.registerer=new Tn(this.userAgent,e),this.registerer.stateChange.addListener((function(e){switch(e){case fn.Initial:break;case fn.Registered:n.delegate&&n.delegate.onRegistered&&n.delegate.onRegistered();break;case fn.Unregistered:n.delegate&&n.delegate.onUnregistered&&n.delegate.onUnregistered();break;case fn.Terminated:n.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}}))),this.registerer.register(t).then((function(){}))},e.prototype.unregister=function(e){return this.logger.log("[".concat(this.id,"] Unregistering UserAgent...")),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then((function(){})):Promise.resolve()},e.prototype.call=function(e,t,n){if(this.logger.log("[".concat(this.id,"] Beginning Session...")),this.session)return Promise.reject(new Error("Session already exists."));var i=An.makeURI(e);if(!i)return Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);var r=new yn(this.userAgent,i,t);return this.sendInvite(r,t,n).then((function(){}))},e.prototype.hangup=function(){return this.logger.log("[".concat(this.id,"] Hangup...")),this.terminate()},e.prototype.answer=function(e){return this.logger.log("[".concat(this.id,"] Accepting Invitation...")),this.session?this.session instanceof vn?(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."))},e.prototype.decline=function(){return this.logger.log("[".concat(this.id,"] rejecting Invitation...")),this.session?this.session instanceof vn?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))},e.prototype.hold=function(){return this.logger.log("[".concat(this.id,"] holding session...")),this.setHold(!0)},e.prototype.unhold=function(){return this.logger.log("[".concat(this.id,"] unholding session...")),this.setHold(!1)},e.prototype.isHeld=function(){return this.held},e.prototype.mute=function(){this.logger.log("[".concat(this.id,"] disabling media tracks...")),this.setMute(!0)},e.prototype.unmute=function(){this.logger.log("[".concat(this.id,"] enabling media tracks...")),this.setMute(!1)},e.prototype.isMuted=function(){return this.muted},e.prototype.sendDTMF=function(e){if(this.logger.log("[".concat(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("[".concat(this.id,"] Sending DTMF tone: ").concat(e));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then((function(){}))},e.prototype.message=function(e,t){this.logger.log("[".concat(this.id,"] sending message..."));var n=An.makeURI(e);return n?new bn(this.userAgent,n,t).message():Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')))},Object.defineProperty(e.prototype,"constraints",{get:function(){var e,t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=s({},this.options.media.constraints)),t},enumerable:!1,configurable:!0}),e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts||3,i=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log("[".concat(this.id,"] Reconnection attempt already in progress")),e>n?this.logger.log("[".concat(this.id,"] Reconnection maximum attempts reached")):(1===e?this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying")):this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying in ").concat(i," seconds")),this.attemptingReconnection=!0,setTimeout((function(){if(!t.connectRequested)return t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - aborted")),void(t.attemptingReconnection=!1);t.userAgent.reconnect().then((function(){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - succeeded")),t.attemptingReconnection=!1})).catch((function(i){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - failed")),t.logger.error(i.message),t.attemptingReconnection=!1,t.attemptReconnection(++e)}))}),1===e?0:1e3*i))):this.logger.log("[".concat(this.id,"] Reconnection not currently desired"))},e.prototype.cleanupMedia=function(){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())))},e.prototype.enableReceiverTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof Rn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getReceivers().forEach((function(t){t.track&&(t.track.enabled=e)}))},e.prototype.enableSenderTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof Rn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getSenders().forEach((function(t){t.track&&(t.track.enabled=e)}))},e.prototype.initSession=function(e,t){var n=this;this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener((function(t){if(n.session===e)switch(n.logger.log("[".concat(n.id,"] session state changed to ").concat(t)),t){case Wt.Initial:case Wt.Establishing:break;case Wt.Established:n.setupLocalMedia(),n.setupRemoteMedia(),n.delegate&&n.delegate.onCallAnswered&&n.delegate.onCallAnswered();break;case Wt.Terminating:case Wt.Terminated:n.session=void 0,n.cleanupMedia(),n.delegate&&n.delegate.onCallHangup&&n.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}})),this.session.delegate={onInfo:function(e){var t;if(void 0!==(null===(t=n.delegate)||void 0===t?void 0:t.onCallDTMFReceived)){var i=e.request.getHeader("content-type");if(i&&/^application\/dtmf-relay/i.exec(i)){var r=e.request.body.split("\r\n",2);if(2===r.length){var s,o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(o.test(r[0])&&(s=r[0].replace(o,"$2")),s){var a,c=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;c.test(r[1])&&(a=parseInt(r[1].replace(c,"$2"),10)),a?e.accept().then((function(){if(n.delegate&&n.delegate.onCallDTMFReceived){if(!s||!a)throw new Error("Tone or duration undefined.");n.delegate.onCallDTMFReceived(s,a)}})).catch((function(e){n.logger.error(e.message)})):e.reject()}else e.reject()}else e.reject()}else e.reject()}else e.reject()},onRefer:function(e){e.accept().then((function(){return n.sendInvite(e.makeInviter(t),t)})).catch((function(e){n.logger.error(e.message)}))}}},e.prototype.sendInvite=function(e,t,n){var i=this;return this.initSession(e,t),e.invite(n).then((function(){i.logger.log("[".concat(i.id,"] sent INVITE"))}))},e.prototype.setHold=function(e){var t=this;if(!this.session)return Promise.reject(new Error("Session does not exist."));var n=this.session;if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof Rn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var i={requestDelegate:{onAccept:function(){t.held=e,t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)},onReject:function(){t.logger.warn("[".concat(t.id,"] re-invite request was rejected")),t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)}}},r=n.sessionDescriptionHandlerOptionsReInvite;return r.hold=e,n.sessionDescriptionHandlerOptionsReInvite=r,this.session.invite(i).then((function(){t.enableReceiverTracks(!e),t.enableSenderTracks(!e&&!t.muted)})).catch((function(e){throw e instanceof en&&t.logger.error("[".concat(t.id,"] A hold request is already in progress.")),e}))},e.prototype.setMute=function(e){this.session?this.session.state===Wt.Established?(this.muted=e,this.enableSenderTracks(!this.held&&!this.muted)):this.logger.warn("[".concat(this.id,"] An established session is required to enable/disable media tracks")):this.logger.warn("[".concat(this.id,"] A session is required to enabled/disable media tracks"))},e.prototype.setupLocalMedia=function(){var e,t,n=this;if(!this.session)throw new Error("Session does not exist.");var i=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(i){var r=this.localMediaStream;if(!r)throw new Error("Local media stream undefiend.");i.srcObject=r,i.volume=0,i.play().catch((function(e){n.logger.error("[".concat(n.id,"] Failed to play local media")),n.logger.error(e.message)}))}},e.prototype.setupRemoteMedia=function(){var e,t,n,i,r=this;if(!this.session)throw new Error("Session does not exist.");var s=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(i=null===(n=this.options.media)||void 0===n?void 0:n.remote)||void 0===i?void 0:i.audio);if(s){var o=this.remoteMediaStream;if(!o)throw new Error("Remote media stream undefiend.");s.autoplay=!0,s.srcObject=o,s.play().catch((function(e){r.logger.error("[".concat(r.id,"] Failed to play remote media")),r.logger.error(e.message)})),o.onaddtrack=function(){r.logger.log("[".concat(r.id,"] Remote media onaddtrack")),s.load(),s.play().catch((function(e){r.logger.error("[".concat(r.id,"] Failed to play remote media")),r.logger.error(e.message)}))}}},e.prototype.terminate=function(){var e=this;if(this.logger.log("[".concat(this.id,"] Terminating...")),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case Wt.Initial:if(this.session instanceof yn)return this.session.cancel().then((function(){e.logger.log("[".concat(e.id,"] Inviter never sent INVITE (canceled)"))}));if(this.session instanceof vn)return this.session.reject().then((function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))}));throw new Error("Unknown session type.");case Wt.Establishing:if(this.session instanceof yn)return this.session.cancel().then((function(){e.logger.log("[".concat(e.id,"] Inviter canceled (sent CANCEL)"))}));if(this.session instanceof vn)return this.session.reject().then((function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))}));throw new Error("Unknown session type.");case Wt.Established:return this.session.bye().then((function(){e.logger.log("[".concat(e.id,"] Session ended (sent BYE)"))}));case Wt.Terminating:case Wt.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log("[".concat(this.id,"] Terminating in state ").concat(this.session.state,", no action taken")),Promise.resolve()}}();var Pn=function(e){var t=document.getElementById(e);if(t instanceof HTMLAudioElement)return t;var n=new Audio;return n.controls=!0,n.autoplay=!0,n.id="ueRemoteAudio",n.style.display="none",document.body.appendChild(n),document.getElementById(e)}("ueRemoteAudio"),_n=function(){function e(e){var t=this;this.registerRequested=!1,this.attemptingReconnection=!1,this.connectRequested=!1,this.requestDelegate={onAccept:function(e){},onProgress:function(e){},onRedirect:function(e){},onReject:function(e){return o(t,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return[4,this.disconnect()];case 1:return e.sent(),[4,this.connect()];case 2:return e.sent(),this.register(),[2]}}))}))},onTrying:function(e){}},this.accept=function(){return o(t,void 0,void 0,(function(){var e;return a(this,(function(t){return e={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},[2,this.Ginvitation.accept(e)]}))}))},this.ueUnregisterWebrtc=function(){return o(t,void 0,void 0,(function(){return a(this,(function(e){return this.registerer?[2,this.registerer.unregister({all:!0}).then((function(e){})).catch((function(e){}))]:[2,!1]}))}))};var n=An.makeURI("sip:"+e.sip+"@"+e.server);if(!n)throw new Error("Failed to create URI");var i={onConnect:function(e){return o(t,void 0,void 0,(function(){return a(this,(function(e){return this.registerer&&this.registerRequested&&this.registerer.register().catch((function(e){})),[2]}))}))},onDisconnect:function(e){t.registerer&&t.registerer.unregister().catch((function(e){})),e&&t.attemptReconnection()},onInvite:function(e){t.Ginvitation=e;var n=e;n.delegate={onRefer:function(e){}},n.stateChange.addListener((function(e){switch(e){case Wt.Initial:case Wt.Establishing:break;case Wt.Established:var t=n.sessionDescriptionHandler;if(!(t&&t instanceof Rn))throw new Error("Invalid session description handler.");Pn&&(i=t.remoteMediaStream,(r=Pn).autoplay=!0,r.srcObject=i,r.play().catch((function(e){})),i.onaddtrack=function(){r.load(),r.play().catch((function(e){}))},i.onremovetrack=function(){r.load(),r.play().catch((function(e){}))});break;case Wt.Terminating:case Wt.Terminated:break;default:throw new Error("Unknown session state.")}var i,r}));var i={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},r=t.Ginvitation.incomingInviteRequest.message.headers["X-Calltype"][0].raw;"callout"!==r&&"callTask"!==r||e.accept(i).then((function(){})).catch((function(e){}))}},r={logBuiltinEnabled:!1,delegate:i,displayName:"WEBRTC",uri:n,transportOptions:{server:"wss://"+e.server},authorizationUsername:e.sip,authorizationHa1:e.secret,reconnectionDelay:0};this.userAgent=new An(r),window.addEventListener("online",(function(){return o(t,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return window.sessionStorage.getItem("kickoff")?[2]:[4,this.attemptReconnection()];case 1:return e.sent(),this.register(),[2]}}))}))}))}return e.prototype.register=function(){var e=this;return this.registerRequested=!0,this.registerer||(this.registerer=new Tn(this.userAgent,{expires:10}),this.registerer.stateChange.addListener((function(t){switch(t){case fn.Initial:case fn.Registered:case fn.Unregistered:break;case fn.Terminated:e.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}}))),this.registerer.register({requestDelegate:this.requestDelegate}).then((function(){}))},e.prototype.unregister=function(e){return this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then((function(){})):Promise.resolve()},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);this.connectRequested&&(e>1||(this.attemptingReconnection=!0,setTimeout((function(){t.connectRequested?t.userAgent.reconnect().then((function(){t.attemptingReconnection=!1})).catch((function(n){t.attemptingReconnection=!1,t.attemptReconnection(++e)})):t.attemptingReconnection=!1}),0)))},e.prototype.sendDTMF=function(e){if(!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.Ginvitation)return Promise.reject(new Error("Session does not exist."));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.Ginvitation.info({requestOptions:t}).then((function(){}))},e.prototype.disconnect=function(){return this.connectRequested=!1,this.userAgent.stop()},e.prototype.connect=function(){return this.connectRequested=!0,this.userAgent.state!==En.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e}(),Dn={requestState:!1,delay:0},qn=function(){function i(e){void 0===e&&(e={});var t=this;this.getWebrtcInfo=function(e,t,n){r.request(e+"/call/api/sip/webrtc/config/query",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(e){e.success&&e.data?(r.agentextras=e.data,"WEBRTC"===n&&r.initWebrtcEvent(e.data)):t.error(s({},e))},error:function(e){t.error({error:e})}})},this.initAttachEvent=function(e,n,i,s){r.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach((function(e){"KF"===e.id&&(o=e.url)}));var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:n,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:1,pushHangupStatistics:r.initOptions.pushHangupStatistics||!1,pushCallinRingStatistics:r.initOptions.pushCallinRingStatistics||!1},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};t.attachEventCallbacks?(t.attachEventCallbacks.serve=o,t.attachEventCallbacks.SocketOptions=a,r.createEventHandle(t.attachEventCallbacks)):r.createEventHandle({serve:o,SocketOptions:a})}},error:function(e){i.error({error:e})}})},this.attachNetworkCallbacks={message:r.noop,error:r.noop,success:r.noop},this.initnNetworkMonitoring=function(e,n){var i="";e.forEach((function(e){"MONITOR"===e.id&&(i="https://"+e.url)})),t.attachNetworkCallbacks.success(),t.attachNetworkCallbacks.message({delay:100}),setInterval((function(){var e=(new Date).getTime();Dn.requestState=!0,r.request(i+"/ready",{method:"GET",success:function(n){if(n.success){var i=(new Date).getTime();Dn.delay=(i-e)/2,t.attachNetworkCallbacks.message({delay:Dn.delay})}else t.attachNetworkCallbacks.error(),Dn.delay=500,Dn.requestState=!1},error:function(e){t.attachNetworkCallbacks.error(),Dn.delay=500,Dn.requestState=!1}})}),1e4)},this.listenCallNetork=function(e){e&&(t.attachNetworkCallbacks.message=e.message&&"function"==typeof e.message?e.message:r.noop,t.attachNetworkCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.attachNetworkCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop)},this.volumeCallbacks={message:r.noop,error:r.noop,success:r.noop},this.stopVolumeCallbacks={error:r.noop,success:r.noop},this.audioContext=null,this.analyser=null,this.dataArray=null,this.stream=null,this.volumeIntervalId=null,this.getMicrophoneVolume=function(){if(!t.analyser||!t.dataArray)return 0;t.analyser.getByteFrequencyData(t.dataArray);for(var e=0,n=0;n<t.dataArray.length;n++)e+=t.dataArray[n];return e/t.dataArray.length},this.initAudioDetection=function(){return o(t,void 0,void 0,(function(){var e,t,n;return a(this,(function(i){switch(i.label){case 0:if(this.audioContext)return[2];i.label=1;case 1:return i.trys.push([1,3,,4]),e=this,[4,navigator.mediaDevices.getUserMedia({audio:!0})];case 2:return e.stream=i.sent(),this.audioContext=new AudioContext,t=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),t.connect(this.analyser),[3,4];case 3:return n=i.sent(),this.volumeCallbacks.error(n),[3,4];case 4:return[2]}}))}))},this.startVolumeDetection=function(e,n){return o(t,void 0,void 0,(function(){var t,n=this;return a(this,(function(i){switch(i.label){case 0:return"WEBRTC"!==e.loginType?(this.volumeCallbacks.error("只有webrtc支持音量检测"),[2]):(this.clearVolumeDetection(),[4,this.initAudioDetection()]);case 1:return i.sent(),this.volumeCallbacks.success({code:"200",msg:"音频检测已初始化"}),e.interval||(e.interval=500),e.interval<100&&(e.interval=100),e.interval>5e3&&(e.interval=5e3),t=this.getMicrophoneVolume(),this.volumeCallbacks.message({volume:Math.round(t/255*100)}),this.volumeIntervalId=setInterval((function(){var e=n.getMicrophoneVolume();n.volumeCallbacks.message({volume:Math.round(e/255*100)})}),e.interval),[2]}}))}))},this.clearVolumeDetection=function(){t.volumeIntervalId&&(clearInterval(t.volumeIntervalId),t.volumeIntervalId=null),t.stream&&(t.stream.getTracks().forEach((function(e){return e.stop()})),t.stream=null),t.audioContext&&(t.audioContext.close(),t.audioContext=null),t.analyser=null,t.dataArray=null},this.stopVolumeDetection=function(){try{t.clearVolumeDetection(),t.stopVolumeCallbacks.success({code:"200",msg:"音频检测关闭成功"})}catch(e){t.stopVolumeCallbacks.error(e)}},this.listenCallVolume=function(e){e&&(t.volumeCallbacks.message=e.message&&"function"==typeof e.message?e.message:r.noop,t.volumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.volumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop),r.initOptions.volume||(r.initOptions.volume={open:!0,interval:500}),t.startVolumeDetection(s(s({},r.initOptions.volume),{loginType:r.initOptions.loginType}),"")},this.stopListenVolume=function(e){e&&(t.stopVolumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.stopVolumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop),t.stopVolumeDetection()},this.turnOffRingCallbacks={error:r.noop,success:r.noop},this.muteRing=function(e){e&&(t.turnOffRingCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.turnOffRingCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop);try{r.isCanRing=!1,Hn.ringAudioPause(),t.turnOffRingCallbacks.success({code:"200",msg:"关闭铃声成功"})}catch(e){t.turnOffRingCallbacks.error(e)}},this.sdkMonitorMsg=function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.error=e&&"function"==typeof e.error?e.error:r.noop,null!==e.type&&void 0!==e.type&&""!==e.type)if(null!==e.requestMsg&&void 0!==e.requestMsg&&""!==e.requestMsg&&"{}"!==JSON.stringify(e.requestMsg))if(r.initOptions.monitor)try{r.changeMonitorEventHandle(t.allMonitorEventCallbacks,e),e.success({code:"200",msg:"成功"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter requestMsg is required!"});else e.error({success:!1,message:"Parameter type is required!"})},this.closeSdkMonitor=function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.error=e&&"function"==typeof e.error?e.error:r.noop,null!==e.type&&void 0!==e.type&&""!==e.type&&0!==e.type.length)if(r.initOptions.monitor)try{e.type.forEach((function(e){switch(e){case"summary":clearInterval(r.summaryUeTimer);break;case"agent":clearInterval(r.agentUeTimer);break;case"queue":clearInterval(r.queueUeTimer)}})),e.success({code:"200",msg:"success"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter type is required!"})},this.initAgentQueue=function(e,n,i,s){(t.attachMonitorEventCallbacks||t.attachNlsTranslationEventCallbacks||t.allMonitorEventCallbacks)&&r.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach((function(e){"MONITOR"===e.id&&(o=e.url)}));var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:n,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:3},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};t.attachMonitorEventCallbacks&&r.UserConfig.isOpenCallQueue&&(t.attachMonitorEventCallbacks.serve=o,t.attachMonitorEventCallbacks.SocketOptions=a,r.createQueueMonitorEventHandle(t.attachMonitorEventCallbacks)),t.attachNlsTranslationEventCallbacks&&r.UserConfig.openNlsTranslation&&(t.attachNlsTranslationEventCallbacks.serve=o,t.attachNlsTranslationEventCallbacks.SocketOptions=a,r.createopenNlsTransEventHandle(t.attachNlsTranslationEventCallbacks)),t.allMonitorEventCallbacks&&r.UserConfig.monitor&&(t.allMonitorEventCallbacks.serve=o,t.allMonitorEventCallbacks.SocketOptions=a,r.createopenAllMonitorEventHandle(t.allMonitorEventCallbacks))}},error:function(e){r.log("失败"),i.error({error:e})}})},this.initQueue=function(e){r.request(e+"/call/monitor/agent/queue/query",{verb:"POST",body:{accountId:r.agentInfo.accountId,agentId:r.agentInfo._id},success:function(e){e&&e.data?t.attachMonitorEventCallbacks.message(e):t.attachMonitorEventCallbacks.error(e)},error:function(e){t.attachMonitorEventCallbacks.error(e)}})},this.listenCallQueueEvent=function(e){t.attachMonitorEventCallbacks=e},this.listenTranslationEvent=function(e){t.attachNlsTranslationEventCallbacks=e},this.listenMonitor=function(e){t.allMonitorEventCallbacks=e},this.openMediaAudio=function(e,n){var i,r=navigator,s=r.mediaDevices,c=r.getUserMedia,u=r.webkitGetUserMedia,l=r.mozGetUserMedia,d=r.msGetUserMedia,h=null===(i=s&&s.getUserMedia||c||u||l||d)||void 0===i?void 0:i.bind(navigator);return s&&s.getUserMedia?s.getUserMedia({audio:!0}).then((function(e){return o(t,void 0,void 0,(function(){return a(this,(function(t){return p(e),[2,!0]}))}))})).catch((function(t){var i=t.message.includes("Permission denied")||"NotAllowedError"===t.name;return n?(i?alert(Ae.forbiddenAudioMsg):e&&alert(e),i?Ae:Ce):i?Ae:Ce})):new Promise((function(t,i){h?h({audio:!0},(function(e){p(e),t(!0)}),(function(t){n&&e&&alert(e),i(Ce)})):i(Ce)}));function p(e){e&&"function"==typeof e.getTracks&&e.getTracks().forEach((function(e){e.stop()}))}},this.listenCallEvent=function(e){t.attachEventCallbacks=e,e&&null!=r.Socketinstance&&r.createEventHandle(t.attachEventCallbacks)},this.switchOutDevices=function(e){return o(t,void 0,void 0,(function(){var t,n,i,s;return a(this,(function(o){switch(o.label){case 0:if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,!e.deviceId||"string"!=typeof e.deviceId)return e.fail({success:!1,message:"Passing in an illegal deviceId!"}),[2];t=document.getElementById("ueRemoteAudio"),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,navigator.mediaDevices.enumerateDevices()];case 2:return n=o.sent(),i=n.filter((function(e){return"audiooutput"===e.kind})),i.some((function(t){return t.deviceId===e.deviceId}))?[4,t.setSinkId(e.deviceId)]:(e.fail({success:!1,message:"The deviceId is not in the output device list!"}),[2]);case 3:return o.sent(),[3,5];case 4:return s=o.sent(),e.fail(s),[3,5];case 5:return e.success({code:"200",msg:"切换音频输出设备成功"}),[2]}}))}))},this._callApi=function(){var e,n,i=t;return{callout:function(t){return o(this,void 0,void 0,(function(){var o,c,u,l,d,h;return a(this,(function(a){switch(a.label){case 0:if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null===r.loginToken||void 0===r.loginToken)return t.fail({success:!1,message:"initialization not complete!"}),[2];if("KICK_OFF"===r.loginToken)return t.fail({success:!1,message:"您的座席账号正在别处登录,当前页面电话条已退出。"}),[2];if(null===r.agentInfo||void 0===r.agentInfo)return t.fail({success:!1,message:"initialization not complete!"}),[2];if(null===t.customerNumber||void 0===t.customerNumber)return t.fail({success:!1,message:"Parameter customerNumber is required!"}),[2];if(o=r.initOptions.server||r.callApiUrl,c={customerNumber:t.customerNumber,agentNumber:r.agentInfo.agentNumber,accountId:r.agentInfo.accountId,agentId:r.agentInfo._id,loginType:t.loginType||r.agentInfo.loginType||r.initOptions.loginType},t.agentTimeout&&(c.agentTimeout=t.agentTimeout),t.customerTimeout&&(c.customerTimeout=t.customerTimeout),t.agentDisNumber&&(c.agentDisNumber=t.agentDisNumber),t.customerDisNumber&&(c.customerDisNumber=t.customerDisNumber),t.extras&&(c.extras=t.extras),t.numberGroupId&&(c.numberGroupId=t.numberGroupId),t.numberGroupName&&(c.numberGroupName=t.numberGroupName),u=r.initOptions,l=!0,"WEBRTC"!==u.loginType)return[3,4];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,i.openMediaAudio("请打开麦克风权限!",l)];case 2:return d=a.sent()||{},r.log(d),!0!==d?(t.fail({success:!1,message:"无麦克风权限!"}),[2]):[3,4];case 3:return h=a.sent(),r.log(h),t.fail({success:!1,message:"无麦克风权限!"}),[2];case 4:return r.request(o+"/call/api/call/call/out",{verb:"POST",body:c,loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success(s(s({success:!0,message:"callout success"},d),e.data)):t.fail(s({success:!1,message:e.message,code:e.code},d))}}),[2]}}))}))},hangup:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/hangup",{verb:"POST",body:{},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?(t.success({success:!0,message:"hangup success",data:e}),Hn.InvalidateHangup()):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},holdOrUnHold:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type){var i=r.initOptions.server||r.callApiUrl,s={type:t.type};r.request(i+"/call/api/call/hold",{verb:"POST",body:s,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"holdOrUnHold success"}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},muteOrUnMute:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type){var i=r.initOptions.server||r.callApiUrl,s="1"===t.type?"in":"all",o={type:t.type,direction:s};r.request(i+"/call/api/call/mute",{verb:"POST",body:o,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"muteOrUnMute success"}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},transfer:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type)if(null!==t.number&&void 0!==t.number){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/transfer",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"transfer success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter number is required!"});else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},consult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.mode&&void 0!==t.mode)if(null!==t.number&&void 0!==t.number){t.agentNumber=r.agentInfo.agentNumber;var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"consult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter number is required!"});else t.fail({success:!1,message:"Parameter mode is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},cancelconsult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/cancel",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"cancelconsult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},endConsult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/stop",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"endConsult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},callbackConsult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/resume",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"resumeConsult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},consultTransfer:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/transfer",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"consultTransfer success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},threeWayCall:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/threeway",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"threeWayCall success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},evaluate:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/evaluate",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"evaluate success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},meeting:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.number&&void 0!==t.number){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/meeting",{verb:"POST",body:{meetingType:"phone",number:t.number},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"meeting success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter number is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},listen:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/listen",{verb:"POST",body:{agentNumber:t.agentNumber,listenAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"listen success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},loot:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/lootCall",{verb:"POST",body:{agentNumber:t.agentNumber,lootAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"loot success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},forcedHangup:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/hangupChannel",{verb:"POST",body:{agentNumber:t.agentNumber,hangupAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"forcedHangup success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},breakIn:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/breakIn",{verb:"POST",body:{agentNumber:t.agentNumber,breakInAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"breakIn success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},whisper:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/whisper",{verb:"POST",body:{agentNumber:t.agentNumber,whisperAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"whisper success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})}}},this._agentApi=function(){var e=t;return{switchLoginType:function(t){return o(this,void 0,void 0,(function(){var n,i,c,u,l=this;return a(this,(function(d){return n=null,t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null===t.loginType||void 0===t.loginType?(t.fail({success:!1,message:"Parameter loginType is required!"}),[2]):null===r.agentInfo||void 0===r.agentInfo?(t.fail({success:!1,message:"initialization not complete!"}),[2]):(null!==t.loginNumber&&void 0!==t.loginNumber&&(n=t.loginNumber),"PSTN"!==t.loginType||(n=n||r.agentInfo.mobile)?("SIP"===t.loginType&&(n=n||r.agentInfo.sipNumber),"WEBRTC"===t.loginType&&(n=r.agentInfo.webrtcSipNumber),i=r.initOptions.server||r.callApiUrl,c={loginType:t.loginType,loginNumber:n},r.request(i+"/call/api/agent/v1/login-type/change",{verb:"POST",body:c,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(n){return o(l,void 0,void 0,(function(){return a(this,(function(o){switch(o.label){case 0:return n.success?(t.success(s({success:!0,message:"updateLoginType success"},u)),r.agentInfo.loginType=t.loginType,r.initOptions.loginType=t.loginType,"WEBRTC"!==t.loginType?[3,1]:(e._webPhoneApi().connect(),[3,4])):[3,5];case 1:return"PSTN"!==t.loginType?[3,3]:[4,r.request(i+"/platform/action/updateCallConfig",{verb:"POST",body:{agentCallConfig:{},mobile:t.loginNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId})];case 2:return o.sent(),e._webPhoneApi().disconnect(),[3,4];case 3:e._webPhoneApi().disconnect(),o.label=4;case 4:return[3,6];case 5:t.fail(s({success:!1,message:n.message,code:n.code},u)),o.label=6;case 6:return[2]}}))}))}}),[2]):(alert("请给座席绑定手机号,或者传入号码参数!"),t.fail({success:!1,message:"Please bind your mobile number"}),[2]))}))}))},findPhoneBarList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl;r.request(t+"/call/api/phone/bar/all",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(t){if(t.success){var n=[];t.data.forEach((function(e){var t={name:e.name,number:e.number};n.push(t)})),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},switchPhoneBar:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==e.stateNumber&&void 0!==e.stateNumber)if(null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl,n={stateNumber:e.stateNumber,accountId:r.agentInfo.accountId,agentNumber:r.agentInfo.agentNumber};r.request(t+"/call/api/agent/status/switch",{verb:"POST",body:n,loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(t){t.success?e.success({success:!0}):e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"});else e.fail({success:!1,message:"Parameter stateNumber is required!"})},logout:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){null!==e.toAnswerOffline&&void 0!==e.toAnswerOffline||(e.toAnswerOffline="0");var t=r.initOptions.server||r.callApiUrl,n={toAnswerOffline:e.toAnswerOffline};r.request(t+"/call/api/sdk/agent/logout",{verb:"POST",body:n,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(t){t.success?e&&(r.Socketinstance&&(r.Socketinstance.disconnect(),r.Socketinstance=null),r.MonitorSocketinstance&&(r.MonitorSocketinstance.disconnect(),r.MonitorSocketinstance=null),"WEBRTC"===r.UserConfig.loginType&&r.webPhone&&(window.sessionStorage.setItem("kickoff","true"),r.webPhone.disconnect(),r.webPhone=null),e.success({success:!0})):e&&e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},findIdleAgentsForQueue:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl;r.request(t+"/call/api/queue/acountFreeAgent/find",{verb:"POST",body:{},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(t){t.success?e&&e.success({success:!0,dataList:t.data||[]}):e&&e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},getAvailableSipNumberList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl;r.request(t+"/call/api/sip/avaliable/query",{verb:"POST",body:{},loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(t){if(t.success&&t.data){var n=[];t.data.forEach((function(e){var t={number:e.id,numberName:e.number};n.push(t)})),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})}}},this._webPhoneApi=function(){return{accept:function(){r.webPhone.accept()},connect:function(){r.webPhone&&this.isConnected()||r.initWebrtcEvent(r.agentextras)},disconnect:function(){r.webPhone&&this.isConnected()&&r.webPhone.disconnect()},isConnected:function(){return r.webPhone.isConnected()},sendDTMF:function(e){r.webPhone.sendDTMF(e)}}},e.error="function"==typeof e.error?e.error:r.noop,e.success="function"==typeof e.success?e.success:r.noop,null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.accountId&&void 0!==e.accountId&&""!==e.accountId?null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.agentNumber&&void 0!==e.agentNumber&&""!==e.accountId?null!==e.password&&void 0!==e.password?(null!==e.loginType&&void 0!==e.loginType||(e.loginType="PSTN"),null!==e.pushHangupStatistics&&void 0!==e.pushHangupStatistics||(e.pushHangupStatistics=!1),null!==e.pushCallinRingStatistics&&void 0!==e.pushCallinRingStatistics||(e.pushCallinRingStatistics=!1),this.init(e)):e.error({message:"Invalid password"}):e.error({message:"Invalid agentNumber or Invalid accountName"}):e.error({message:"Invalid accountId or Invalid accountName"})}var r;return i.noop=function(){},i.prototype.init=function(e){if(void 0===e&&(e={}),r.trace=r.noop,r.debug=r.noop,r.log=r.noop,r.warn=r.noop,r.error=r.noop,!0===e.debug||"all"===e.debug)r.trace=console.trace.bind(console),r.debug=console.debug.bind(console),r.log=console.log.bind(console),r.warn=console.warn.bind(console),r.error=console.error.bind(console);else if(Array.isArray(e.debug))for(var t in e.debug){var n=e.debug[t];switch(n){case"trace":r.trace=console.trace.bind(console);break;case"debug":r.debug=console.debug.bind(console);break;case"log":r.log=console.log.bind(console);break;case"warn":r.warn=console.warn.bind(console);break;case"error":r.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+n+"' (supported: 'trace', 'debug', 'log', warn', 'error')")}}r.log("Initializing library");var i=r.useDefaultDependencies({WebSocket:On});r.newWebSocket=i.newWebSocket,r.request=i.request,this.getDomain(e)},i.prototype.getDomain=function(e){return o(this,void 0,void 0,(function(){var t,n,i,s=this;return a(this,(function(o){return t=(null===(i=e.accountName)||void 0===i?void 0:i.split("@")[1])||e.accountId,n=e.server||r.callApiUrl,r.request(n+"/platform/public/cloudConfig?accountName="+t,{verb:"GET",success:function(t){t.success?(e.server="https://"+t.data.baseURL+"/api",r.callApiUrl="https://"+t.data.baseURL+"/api",s.login(e)):e.error({res:t})},error:function(t){e.error({error:t})}}),[2]}))}))},i.prototype.login=function(i){return o(this,void 0,void 0,(function(){var o,c,u,l,d,h,p,g,f,m=this;return a(this,(function(a){return r.log(i),r.UserConfig=i,o=i.server||r.callApiUrl,c=i.accountName?i.accountName:i.agentNumber+"@"+i.accountId,u=i.loginType,l=i.isOpenNetwork||!1,d=i.isOpenCallQueue||!1,h=i.openNlsTranslation||!1,p=i.monitor||!1,g={loginName:c,loginType:u,loginChannel:"SDK",password:"",clientType:1},i.password&&(g.password=i.password),r.request(o+"/platform/public/loginPre",{verb:"GET",success:function(a){if(a&&a.success&&a.data){var c=decodeURIComponent(e.Base64.decode(a.data.pk)),v=new n.JSEncrypt;v.setPublicKey(c);var y=t(g.password),b=v.encrypt(y);g.password=b,r.request(o+"/platform/public/login",{verb:"POST",body:g,success:function(e){e.success?r.request(o+"/platform/action/loginInfo",{verb:"GET",loginToken:e.data.loginToken,sessionId:e.data.sessionId,success:function(e){e.success?(i.success(s(s({},e),{msg:"登录成功"})),e.data.agent&&(r.agentInfo=e.data.agent,i.success({ueFlag:"success",msg:"agentInfo获取成功"}),r.loginToken=e.data.loginToken,r.initOptions=s(s({},i),{audioInfo:f})),m.initAttachEvent(o,u,e.data.pushServer,e.data.agent),l&&m.initnNetworkMonitoring(e.data.pushServer,""),(d||h||p)&&m.initAgentQueue(o,u,e.data.pushServer,e.data.agent),d&&m.initQueue(o),m.getWebrtcInfo(o,i,u),window.sessionStorage.removeItem("kickoff")):i.error(s(s({},e),f))},error:function(e){i.error(s({error:e},f))}}):i.error(s(s({},e),f))},error:function(e){i.error(s({error:e},f))}})}else i.error(s(s({},a),f))},error:function(e){i.error(s({error:e},f))}}),[2]}))}))},i.createEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.event="function"==typeof e.event?e.event:r.noop,e.server=null===e.serve||void 0===e.serve?"ws://152.136.72.209:3201/phoneBarGateway":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),this.Socketinstance||(this.Socketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.Socketinstance.on("connect",(function(){e.success("connect event serve success!")})),this.Socketinstance.on("error",(function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")})),this.Socketinstance.on("message",(function(t,n){e.message({subtype:t.subType,data:t.data}),"WEBRTC"===r.initOptions.loginType&&$n("WEBRTC",t.data),n&&"function"==typeof n&&n("success")})),this.Socketinstance.on("event",(function(t){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.event({message:"坐席账户在其他地方登录",data:t})}}))},i.createQueueMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",(function(){e.success("connect event serve success!"),r.log("监控connect========")})),this.MonitorSocketinstance.on("error",(function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")})),this.MonitorSocketinstance.on("event",(function(t,n){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:t})}e.message(t)})),this.MonitorSocketinstance.on("call",(function(t,n){"queue"==t.subType&&r.UserConfig.isOpenCallQueue&&e.message({subtype:t.subType,data:t.data})}))},i.createopenNlsTransEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",(function(){e.success("转译connect event serve success!"),r.log("转译监控connect========")})),this.MonitorSocketinstance.on("error",(function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")})),this.MonitorSocketinstance.on("event",(function(t,n){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:t})}e.message(t)})),this.MonitorSocketinstance.on("call",(function(t,n){"translation"==t.subType&&r.UserConfig.openNlsTranslation&&e.message({subtype:t.subType,data:t.data})}))},i.createopenAllMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",(function(){e.success("转译connect event serve success!"),r.log("转译监控connect========")})),this.MonitorSocketinstance.on("error",(function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")})),this.MonitorSocketinstance.on("event",(function(t,n){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:t})}e.message(t)})),r.UserConfig.monitor&&this.MonitorSocketinstance.on("monitor",(function(t){r.UserConfig.monitor&&e.message({type:"agent",data:t})}))},i.changeMonitorEventHandle=function(e,t){var n=this;void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),r.UserConfig.monitor&&t&&(r.agentUeTimer&&clearInterval(r.agentUeTimer),r.queueUeTimer&&clearInterval(r.queueUeTimer),r.summaryUeTimer&&clearInterval(r.summaryUeTimer),t.type.forEach((function(i){var o;switch(i){case"agent":null!==n.MonitorSocketinstance&&(null===(o=n.MonitorSocketinstance)||void 0===o||o.emit("monitor","agent",JSON.stringify(s(s({},t.requestMsg),{monitorQueryAgent:r.agentInfo._id,accountId:r.agentInfo.accountId})))),r.agentUeTimer=window.setInterval((function(){var e;null===(e=n.MonitorSocketinstance)||void 0===e||e.emit("monitor","agent",JSON.stringify(s(s({},t.requestMsg),{monitorQueryAgent:r.agentInfo._id,accountId:r.agentInfo.accountId})))}),3e3);break;case"queue":null!==n.MonitorSocketinstance&&n.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:r.agentInfo.accountId,date:new Date}},e),r.queueUeTimer=window.setInterval((function(){n.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:r.agentInfo.accountId,date:new Date}},e)}),3e3);break;case"summary":null!==n.MonitorSocketinstance&&n.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:r.agentInfo.accountId,date:new Date}},e),r.summaryUeTimer=window.setInterval((function(){n.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:r.agentInfo.accountId,date:new Date}},e)}),3e3)}})))},i.handleHttpMonitor=function(e,t){r.request(r.callApiUrl+e.url,{verb:"POST",body:e.data,success:function(n){n.success&&r.UserConfig.monitor?t.message({type:e.type,data:n.data}):t.error({type:e.type,data:n})}})},i.useDefaultDependencies=function(e){var t=e&&e.fetch||fetch,n=e&&e.Promise||Promise,i=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new i(e,t)},request:function(e,i){var s={method:i.verb,cache:"no-cache",headers:{"Content-Type":"application/json",loginToken:i.loginToken||"",sessionId:i.sessionId||"",clienttype:0}};i.encryptionFields&&(s.headers["ue-encryption-algorithm"]=i.encryptionAlgorithm||"aes",s.headers["ue-encryption-fields"]=i.encryptionFields),void 0!==i.withCredentials&&(s.credentials=!0===i.withCredentials?"include":i.withCredentials?i.withCredentials:"omit"),void 0!==i.body&&(s.body=JSON.stringify(i.body));var o=t(e,s).catch((function(e){return n.reject({message:"Probably a network error, is the gateway down?",error:e})}));if(void 0!==i.timeout){var a=new n((function(e,t){var n=window.setTimeout((function(){return clearTimeout(n),i.error({message:"Request timed out",timeout:i.timeout}),t({message:"Request timed out",timeout:i.timeout})}),i.timeout)}));o=n.race([o,a])}return o.then((function(e){return e.ok?typeof i.success==typeof r.noop?e.json().then((function(e){i.success(e)})).catch((function(t){return i.error({message:"Failed to parse response body",error:t,response:e}),n.reject({message:"Failed to parse response body",error:t,response:e})})):void 0:(i.error({message:"API call failed",response:e}),n.reject({message:"API call failed",response:e}))})).catch((function(e){typeof i.error==typeof r.noop&&i.error(e.message||"<< internal error >>",e)})),o}}},Object.defineProperty(i.prototype,"agent",{get:function(){return this._agentApi()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"webrtc",{get:function(){return this._webPhoneApi()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"call",{get:function(){return this._callApi()},enumerable:!1,configurable:!0}),r=i,i.callApiUrl="https://app.useasy.cn/api",i.Socketinstance=null,i.AudioTask=null,i.MonitorSocketinstance=null,i.UserConfig=null,i.isCanRing=!0,i.kickOffEvent=function(){r.Socketinstance&&(r.Socketinstance.disconnect(),r.Socketinstance=null),r.MonitorSocketinstance&&(r.MonitorSocketinstance.disconnect(),r.MonitorSocketinstance=null),"WEBRTC"===r.UserConfig.loginType&&r.webPhone&&(window.sessionStorage.setItem("kickoff","true"),r.webPhone.disconnect(),r.webPhone=null)},i.initWebrtcEvent=function(e){return o(void 0,void 0,void 0,(function(){return a(r,(function(t){switch(t.label){case 0:return r.webPhone=new _n({server:e.wssUrl,sip:e.sip,secret:e.password}),[4,this.webPhone.connect()];case 1:return t.sent(),this.webPhone.register(),[2]}}))}))},i}(),On=function(){function e(e,t){delete t.path,delete t.hostname,delete t.port,this.ws=ke.connect("wss://".concat(e),t)}return e.prototype.on=function(e,t){"connect"===e&&this.ws.on(e,t),"error"===e&&(this.ws.on("connect_error",t),this.ws.on("error",t),this.ws.on("disconnect",t),this.ws.on("reconnect_failed",t)),"message"===e&&this.ws.on("call",t),"event"===e&&this.ws.on("event",t),"call"===e&&this.ws.on("call",t),"monitor"===e&&this.ws.on("monitor",t)},e.prototype.emit=function(e,t,n){this.ws.emit(e,t,n)},e.prototype.disconnect=function(){this.ws.disconnect()},e}(),Hn=new(function(){function e(){var e=this;fetch("https://softphone.useasy.cn/ring.wav").then((function(e){return e.blob()})).then((function(t){var n=URL.createObjectURL(t);e.ringAudio=new Audio(n),e.ringAudio.loop=!0,e.ringAudioRunning=!1})),fetch("https://softphone.useasy.cn/hangup.wav").then((function(e){return e.blob()})).then((function(t){var n=URL.createObjectURL(t);e.handupAudio=new Audio(n),e.hangupAllow=!0}))}return e.prototype.ringAudioPlay=function(){return o(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return[4,this.ringAudio.play()];case 1:return e.sent(),this.ringAudioRunning=!0,[2]}}))}))},e.prototype.ringAudioPause=function(){return o(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return this.ringAudio.paused?[3,2]:[4,this.ringAudio.pause()];case 1:e.sent(),this.ringAudioRunning=!1,e.label=2;case 2:return[2]}}))}))},e.prototype.activeHangup=function(){this.hangupAllow=!0},e.prototype.InvalidateHangup=function(){this.hangupAllow=!1},e.prototype.triggerTask=function(){return o(this,void 0,void 0,(function(){return a(this,(function(e){return this.hangupAllow?this.handupAudio.play():this.activeHangup(),[2]}))}))},e}()),$n=function(e,t){"WEBRTC"===e&&("ring"!==t.eventType||"callin"!==t.callType&&"inner"!==t.callType&&"transfer"!==t.callType&&"autoCallout"!==t.callType||!qn.isCanRing?Hn.ringAudioRunning&&Hn.ringAudioPause():Hn.ringAudioPlay(),"hangup"===t.eventType&&(Hn.triggerTask(),qn.isCanRing=!0))};return qn}));
1
+ import{Base64 as e}from"js-base64";import t from"js-md5";import{JSEncrypt as n}from"jsencrypt";var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)};function r(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var s=function(){return s=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},s.apply(this,arguments)};function o(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})}function a(e,t){var n,i,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(r=2&a[0]?i.return:a[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,a[1])).done)return r;switch(i=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(r=s.trys,(r=r.length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;const c=Object.create(null);c.open="0",c.close="1",c.ping="2",c.pong="3",c.message="4",c.upgrade="5",c.noop="6";const u=Object.create(null);Object.keys(c).forEach(e=>{u[c[e]]=e});const l={type:"error",data:"parser error"},d="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),h="function"==typeof ArrayBuffer,p=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,g=({type:e,data:t},n,i)=>d&&t instanceof Blob?n?i(t):f(t,i):h&&(t instanceof ArrayBuffer||p(t))?n?i(t):f(new Blob([t]),i):i(c[e]+(t||"")),f=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function m(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let v;const y="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)y["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;const b="function"==typeof ArrayBuffer,w=(e,t)=>{if("string"!=typeof e)return{type:"message",data:S(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:T(e.substring(1),t)}:u[n]?e.length>1?{type:u[n],data:e.substring(1)}:{type:u[n]}:l},T=(e,t)=>{if(b){const n=(e=>{let t,n,i,r,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const u=new ArrayBuffer(o),l=new Uint8Array(u);for(t=0;t<a;t+=4)n=y[e.charCodeAt(t)],i=y[e.charCodeAt(t+1)],r=y[e.charCodeAt(t+2)],s=y[e.charCodeAt(t+3)],l[c++]=n<<2|i>>4,l[c++]=(15&i)<<4|r>>2,l[c++]=(3&r)<<6|63&s;return u})(e);return S(n,t)}return{base64:!0,data:e}},S=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,I=String.fromCharCode(30);function E(){return new TransformStream({transform(e,t){!function(e,t){d&&e.data instanceof Blob?e.data.arrayBuffer().then(m).then(t):h&&(e.data instanceof ArrayBuffer||p(e.data))?t(m(e.data)):g(e,!1,e=>{v||(v=new TextEncoder),t(v.encode(e))})}(e,n=>{const i=n.length;let r;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);const e=new DataView(r.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{r=new Uint8Array(9);const e=new DataView(r.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(n)})}})}let R;function k(e){return e.reduce((e,t)=>e+t.length,0)}function C(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let i=0;for(let r=0;r<t;r++)n[r]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),n}function A(e){if(e)return function(e){for(var t in A.prototype)e[t]=A.prototype[t];return e}(e)}A.prototype.on=A.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},A.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},A.prototype.off=A.prototype.removeListener=A.prototype.removeAllListeners=A.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<i.length;r++)if((n=i[r])===t||n.fn===t){i.splice(r,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},A.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(n){i=0;for(var r=(n=n.slice(0)).length;i<r;++i)n[i].apply(this,t)}return this},A.prototype.emitReserved=A.prototype.emit,A.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},A.prototype.hasListeners=function(e){return!!this.listeners(e).length};const P="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function _(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const D=P.setTimeout,q=P.clearTimeout;function O(e,t){t.useNativeTimers?(e.setTimeoutFn=D.bind(P),e.clearTimeoutFn=q.bind(P)):(e.setTimeoutFn=P.setTimeout.bind(P),e.clearTimeoutFn=P.clearTimeout.bind(P))}class H extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}let $=class extends A{constructor(e){super(),this.writable=!1,O(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new H(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=w(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}};const x="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),N={};let M,j=0,U=0;function F(e){let t="";do{t=x[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function L(){const e=F(+new Date);return e!==M?(j=0,M=e):e+"."+F(j++)}for(;U<64;U++)N[x[U]]=U;let B=!1;try{B="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(c){}const V=B;function G(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||V))return new XMLHttpRequest}catch(e){}if(!t)try{return new(P[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function W(){}const K=null!=new G({xdomain:!1}).responseType;class z extends A{constructor(e,t){super(),O(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=_(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const n=this.xhr=new G(t);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof n.status?n.status:0)},0))},n.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=z.requestsCount++,z.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=W,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete z.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function Y(){for(let e in z.requests)z.requests.hasOwnProperty(e)&&z.requests[e].abort()}z.requestsCount=0,z.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Y):"function"==typeof addEventListener&&addEventListener("onpagehide"in P?"pagehide":"unload",Y,!1));const J="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Z=P.WebSocket||P.MozWebSocket,Q="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),X={websocket:class extends ${constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=Q?{}:_(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=Q?new Z(e,t,n):t?new Z(e,t):new Z(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;g(n,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}i&&J(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=L()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Z}},webtransport:class extends ${get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){R||(R=new TextDecoder);const n=[];let i=0,r=-1,s=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(0===i){if(k(n)<1)break;const e=C(n,1);s=!(128&~e[0]),r=127&e[0],i=r<126?3:126===r?1:2}else if(1===i){if(k(n)<2)break;const e=C(n,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(k(n)<8)break;const e=C(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(l);break}r=s*Math.pow(2,32)+t.getUint32(4),i=3}else{if(k(n)<r)break;const e=C(n,r);a.enqueue(w(s?e:R.decode(e),t)),i=0}if(0===r||r>e){a.enqueue(l);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=E();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const r=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),r())}).catch(e=>{})};r();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this.writer.write(n).then(()=>{i&&J(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends ${constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=K&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(I),i=[];for(let e=0;e<n.length;e++){const r=w(n[e],t);if(i.push(r),"error"===r.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,i=new Array(n);let r=0;e.forEach((e,s)=>{g(e,!1,e=>{i[s]=e,++r===n&&t(i.join(I))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=L()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new z(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},ee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,te=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ne(e){const t=e,n=e.indexOf("["),i=e.indexOf("]");-1!=n&&-1!=i&&(e=e.substring(0,n)+e.substring(n,i).replace(/:/g,";")+e.substring(i,e.length));let r=ee.exec(e||""),s={},o=14;for(;o--;)s[te[o]]=r[o]||"";return-1!=n&&-1!=i&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,s.path),s.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(n[t]=i)}),n}(0,s.query),s}class ie extends A{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=ne(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=ne(t.host).host),O(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,i=n.length;e<i;e++){let i=n[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new X[e](n)}open(){let e;if(this.opts.rememberUpgrade&&ie.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(e){let t=this.createTransport(e),n=!1;ie.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ie.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function r(){n||(n=!0,u(),t.close(),t=null)}const s=e=>{const n=new Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&r()}const u=()=>{t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onOpen(){if(this.readyState="open",ie.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(e+="string"==typeof(t=i)?function(e){let t=0,n=0;for(let i=0,r=e.length;i<r;i++)t=e.charCodeAt(i),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}var t;return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}onError(e){ie.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const i=e.length;for(;n<i;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}ie.protocol=4;const re="function"==typeof ArrayBuffer,se=Object.prototype.toString,oe="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===se.call(Blob),ae="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===se.call(File);function ce(e){return re&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||oe&&e instanceof Blob||ae&&e instanceof File}function ue(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ue(e[t]))return!0;return!1}if(ce(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ue(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ue(e[t]))return!0;return!1}function le(e){const t=[],n=e.data,i=e;return i.data=de(n,t),i.attachments=t.length,{packet:i,buffers:t}}function de(e,t){if(!e)return e;if(ce(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let i=0;i<e.length;i++)n[i]=de(e[i],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=de(e[i],t));return n}return e}function he(e,t){return e.data=pe(e.data,t),delete e.attachments,e}function pe(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=pe(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=pe(e[n],t));return e}const ge=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var fe;function me(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(fe||(fe={}));class ve extends A{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===fe.BINARY_EVENT;n||t.type===fe.BINARY_ACK?(t.type=n?fe.EVENT:fe.ACK,this.reconstructor=new ye(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!ce(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===fe[n.type])throw new Error("unknown packet type "+n.type);if(n.type===fe.BINARY_EVENT||n.type===fe.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const r=e.substring(i,t);if(r!=Number(r)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(r)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(i,t)}else n.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!ve.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case fe.CONNECT:return me(t);case fe.DISCONNECT:return void 0===t;case fe.CONNECT_ERROR:return"string"==typeof t||me(t);case fe.EVENT:case fe.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ge.indexOf(t[0]));case fe.ACK:case fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ye{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=he(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var be=Object.freeze({__proto__:null,protocol:5,get PacketType(){return fe},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==fe.EVENT&&e.type!==fe.ACK||!ue(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===fe.EVENT?fe.BINARY_EVENT:fe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==fe.BINARY_EVENT&&e.type!==fe.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=le(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}},Decoder:ve});function we(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Te=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Se extends A{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[we(e,"open",this.onopen.bind(this)),we(e,"packet",this.onpacket.bind(this)),we(e,"error",this.onerror.bind(this)),we(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Te.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:fe.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),n.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,[null,...e])}}emitWithAck(e,...t){const n=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((i,r)=>{t.push((e,t)=>n?e?r(e):i(t):i(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:fe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case fe.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case fe.EVENT:case fe.BINARY_EVENT:this.onevent(e);break;case fe.ACK:case fe.BINARY_ACK:this.onack(e);break;case fe.DISCONNECT:this.ondisconnect();break;case fe.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:fe.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:fe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function Ie(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ie.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},Ie.prototype.reset=function(){this.attempts=0},Ie.prototype.setMin=function(e){this.ms=e},Ie.prototype.setMax=function(e){this.max=e},Ie.prototype.setJitter=function(e){this.jitter=e};class Ee extends A{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,O(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Ie({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||be;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ie(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=we(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=we(t,"error",r);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(i),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(we(e,"ping",this.onping.bind(this)),we(e,"data",this.ondata.bind(this)),we(e,"error",this.onerror.bind(this)),we(e,"close",this.onclose.bind(this)),we(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){J(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Se(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Re={};function ke(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let i=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),i=ne(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const r=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+t,i.href=i.protocol+"://"+r+(n&&n.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=n.source,r=n.id,s=n.path,o=Re[r]&&s in Re[r].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Ee(i,t):(Re[r]||(Re[r]=new Ee(i,t)),a=Re[r]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(ke,{Manager:Ee,Socket:Se,io:ke,connect:ke});var Ce={notOpenAudioMsg:"麦克风没有开启",notOpenAudioCode:403,notOpenAudioMsgEn:"Permission dismissed"},Ae={forbiddenAudioMsg:"请先检查您的麦克风是否开启",forbiddenAudioCode:0,forbiddenAudioMsgEn:"Permission denied"},Pe=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!(!e||void 0===this.parameters[e.toLowerCase()])},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.hasParam(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}(),_e=function(e){function t(t,n,i){var r=e.call(this,i)||this;return r.uri=t,r._displayName=n,r}return r(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!1,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(Pe),De=function(e){function t(t,n,i,r,s,o){void 0===t&&(t="sip");var a=e.call(this,s||{})||this;if(a.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(var c in o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:n,host:i,port:r},a.normal={scheme:t.toLowerCase(),user:n,host:i.toLowerCase(),port:r},a}return r(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!1,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!1,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var n in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(n)&&(t+=";"+n,null!==this.parameters[n]&&(t+="="+this.parameters[n]));var i=[];for(var r in this.headers)if(this.headers.hasOwnProperty(r))for(var s in this.headers[r])this.headers[r].hasOwnProperty(s)&&i.push(r+"="+this.headers[r][s]);return i.length>0&&(t+="?"+i.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),i=n.length,r="",s=0;s<i;s++)0!==s&&(r+="-"),r+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[r]&&(r=t[r]),r},t}(Pe);function qe(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){var n=Object.keys(e.parameters),i=Object.keys(t.parameters),r=n.filter(function(e){return i.includes(e)});return!!r.every(function(n){return e.parameters[n]===t.parameters[n]})&&(!!["user","ttl","method","transport"].every(function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)})&&!!["maddr"].every(function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)}))}(e,t))return!1;var n=Object.keys(e.headers),i=Object.keys(t.headers);if(0!==n.length||0!==i.length){if(n.length!==i.length)return!1;var r=n.filter(function(e){return i.includes(e)});if(r.length!==i.length)return!1;if(!r.every(function(n){return e.headers[n].length&&t.headers[n].length&&e.headers[n][0]===t.headers[n][0]}))return!1}return!0}var Oe=function(e){function t(n,i,r,s){var o=e.call(this)||this;return o.message=n,o.expected=i,o.found=r,o.location=s,o.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(o,t),o}return r(t,e),t.buildMessage=function(e,t){function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function i(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,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function r(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,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function s(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":var t=e.parts.map(function(e){return Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(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){var t,n,i=e.map(s);if(i.sort(),i.length>0){for(t=1,n=1;t<i.length;t++)i[t-1]!==i[t]&&(i[n]=i[t],n++);i.length=n}switch(i.length){case 1:return i[0];case 2:return i[0]+" or "+i[1];default:return i.slice(0,-1).join(", ")+", or "+i[i.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o},t}(Error);var He,$e,xe=function(e,t){t=void 0!==t?t:{};var n,i,r,s,o={},a={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},c=119,u=["\r\n",b("\r\n",!1),/^[0-9]/,w([["0","9"]],!1,!1),/^[a-zA-Z]/,w([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,w([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,w([["\0","ÿ"]],!1,!1),/^["]/,w(['"'],!1,!1)," ",b(" ",!1),"\t",b("\t",!1),/^[a-zA-Z0-9]/,w([["a","z"],["A","Z"],["0","9"]],!1,!1),";",b(";",!1),"/",b("/",!1),"?",b("?",!1),":",b(":",!1),"@",b("@",!1),"&",b("&",!1),"=",b("=",!1),"+",b("+",!1),"$",b("$",!1),",",b(",",!1),"-",b("-",!1),"_",b("_",!1),".",b(".",!1),"!",b("!",!1),"~",b("~",!1),"*",b("*",!1),"'",b("'",!1),"(",b("(",!1),")",b(")",!1),"%",b("%",!1),function(){return" "},function(){return":"},/^[!-~]/,w([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,w([["€","￿"]],!1,!1),/^[\x80-\xBF]/,w([["€","¿"]],!1,!1),/^[a-f]/,w([["a","f"]],!1,!1),"`",b("`",!1),"<",b("<",!1),">",b(">",!1),"\\",b("\\",!1),"[",b("[",!1),"]",b("]",!1),"{",b("{",!1),"}",b("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,w([["!","'"]],!1,!1),/^[*-[]/,w([["*","["]],!1,!1),/^[\]-~]/,w([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,w([["#","["]],!1,!1),/^[\0-\t]/,w([["\0","\t"]],!1,!1),/^[\x0B-\f]/,w([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,w([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new De(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 De(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",b("sips",!0),"sip",b("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_\-]/,w([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,w([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",b("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",b("25",!1),/^[0-5]/,w([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,w([["0","4"]],!1,!1),"1",b("1",!1),/^[1-9]/,w([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",b("transport=",!0),"udp",b("udp",!0),"tcp",b("tcp",!0),"sctp",b("sctp",!0),"tls",b("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",b("user=",!0),"phone",b("phone",!0),"ip",b("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",b("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",b("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",b("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",b("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,n){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),n=null===n?void 0:n[1],t.data.uri_params[e.toLowerCase()]=n},function(e,n){e=e.join("").toLowerCase(),n=n.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(n):t.data.uri_headers[e]=[n]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new De(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)},"//",b("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},b("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",b("INVITE",!1),"ACK",b("ACK",!1),"VXACH",b("VXACH",!1),"OPTIONS",b("OPTIONS",!1),"BYE",b("BYE",!1),"CANCEL",b("CANCEL",!1),"REGISTER",b("REGISTER",!1),"SUBSCRIBE",b("SUBSCRIBE",!1),"NOTIFY",b("NOTIFY",!1),"REFER",b("REFER",!1),"PUBLISH",b("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,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new _e(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:d,offset:y().start.offset,parsed:e})},function(e){'"'===(e=v().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",b("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",b("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",b("0",!1),function(){return parseFloat(v())},function(e,n){(t=t||{data:{}}).data.params||(t.data.params={}),n=null===n?void 0:n[1],t.data.params[e.toLowerCase()]=n},"render",b("render",!0),"session",b("session",!0),"icon",b("icon",!0),"alert",b("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=v().toLowerCase())},"handling",b("handling",!0),"optional",b("optional",!0),"required",b("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=v()},"text",b("text",!0),"image",b("image",!0),"audio",b("audio",!0),"video",b("video",!0),"application",b("application",!0),"message",b("message",!0),"multipart",b("multipart",!0),"x-",b("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new _e(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",b("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new _e(t.data.uri,t.data.displayName,t.data.params)},"digest",b("Digest",!0),"realm",b("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",b("domain",!0),"nonce",b("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",b("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",b("stale",!0),"true",b("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",b("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",b("algorithm",!0),"md5",b("MD5",!0),"md5-sess",b("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",b("qop",!0),"auth-int",b("auth-int",!0),"auth",b("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new _e(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:d,offset:y().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new _e(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",b("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",b("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",b("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",b("active",!0),"pending",b("pending",!0),"terminated",b("terminated",!0),function(){(t=t||{data:{}}).data.state=v()},"reason",b("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",b("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",b("deactivated",!0),"probation",b("probation",!0),"rejected",b("rejected",!0),"timeout",b("timeout",!0),"giveup",b("giveup",!0),"noresource",b("noresource",!0),"invariant",b("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new _e(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",b("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",b("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",b("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",b("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",b("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},b("UDP",!0),b("TCP",!0),b("TLS",!0),b("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=v()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",b("refresher",!1),"uas",b("uas",!1),"uac",b("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",b("stuns",!0),"stun",b("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",b("?transport=",!1),"turns",b("turns",!0),"turn",b("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=v()},"Referred-By",b("Referred-By",!1),"b",b("b",!1),"cid",b("cid",!1)],l=[E('2 ""6 7!'),E('4"""5!7#'),E('4$""5!7%'),E('4&""5!7\''),E(";'.# &;("),E('4(""5!7)'),E('4*""5!7+'),E('2,""6,7-'),E('2.""6.7/'),E('40""5!71'),E('22""6273.‰ &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'),E(";).# &;,"),E('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),E('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),E('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),E(';.." &"'),E("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),E('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E('4\\""5!7].# &;3'),E('4^""5!7_'),E('4`""5!7a'),E(';!.) &4b""5!7c'),E('%$;).• &2F""6F7G.‰ &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/ž#0›*;).• &2F""6F7G.‰ &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&&&#/"!&,)'),E('%$;).‰ &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/’#0*;).‰ &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&&&#/"!&,)'),E('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273.› &28""6879. &2j""6j7k.ƒ &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),E('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),E("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),E("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),E("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),E("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),E("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),E('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),E('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),E("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),E("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),E("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),E("%;//0#;&/'$8\":~\" )(\"'#&'#"),E("%;&/0#;//'$8\":~\" )(\"'#&'#"),E("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),E('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),E("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),E("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),E(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),E('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),E("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),E("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),E('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),E('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),E("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),E('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'),E('%$;+._ &;-.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!:–! )'),E('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:—! )"),E('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),E('$4™""5!7š/,#0)*4™""5!7š&&&#'),E('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),E('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),E('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),E('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),E("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),E('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),E('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),E(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),E('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),E('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),E('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),E('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),E('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),E('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),E('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),E('%$;j/&#0#*;j&&&#/"!&,)'),E('%$;j/&#0#*;j&&&#/"!&,)'),E(";k.) &;+.# &;-"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),E('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),E('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),E("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),E("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),E(";‘.# &;r"),E("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),E(";M.# &;t"),E("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),E('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),E('%24""6475/,#;{/#$+")("\'#&\'#'),E("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),E(";*.) &;+.# &;-"),E(';+. &;-.‰ &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'),E('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E("$;~0#*;~&"),E(';+.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'),E('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),E(";.# &;‚"),E('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),E('$;+.ƒ &;-.} &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/Œ#0‰*;+.ƒ &;-.} &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&&&#'),E("$;y0#*;y&"),E('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),E('2Õ""6Õ7Ö'),E('2×""6×7Ø'),E('2Ù""6Ù7Ú'),E('2Û""6Û7Ü'),E('2Ý""6Ý7Þ'),E('2ß""6ß7à'),E('2á""6á7â'),E('2ã""6ã7ä'),E('2å""6å7æ'),E('2ç""6ç7è'),E('2é""6é7ê'),E("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),E("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%;“/' 8!:ì!! )"),E("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),E("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),E("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),E("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),E("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),E("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),E("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),E(";œ.) &;.# &; "),E("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),E("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),E('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),E('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),E(";6.) &;T.# &;H"),E("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),E(";¥.# &; "),E('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),E("%;©/& 8!:č! )"),E("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";«.# &;¬"),E('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),E('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),E(";6.# &;®"),E('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),E(";­.# &;6"),E("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),E(";6.# &;H"),E("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),E("%;ž/' 8!:ğ!! )"),E('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),E('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),E(";¹.# &; "),E("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),E("%;ž/' 8!:Ħ!! )"),E("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),E(";¾"),E("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),E("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),E(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),E("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:Ĭ!! )"),E("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),E(";t.# &;w"),E("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:ı!! )"),E("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),E('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),E('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),E('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),E('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),E("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),E("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),E('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),E("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),E("%;–/& 8!:Ő! )"),E('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),E("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),E("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),E("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),E('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),E(';1." &"'),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),E("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),E(";¹.# &; "),E("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),E("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),E("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),E("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),E("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),E("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),E("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),E('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),E('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),E('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),E('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),E(";¾"),E('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),E(";ô.# &; "),E('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),E('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),E("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),E("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),E("$;%0#*;%&"),E("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),E('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),E('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),E(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),E('2L""6L7M.• &2B""6B7C.‰ &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),E('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),E('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),E("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),E("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),E("%;ă/,#;ă/#$+\")(\"'#&'#"),E("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),E("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),E('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),E(";™.# &;L"),E("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),E("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")],d=0,h=0,p=[{line:1,column:1}],g=0,f=[],m=0;if(void 0!==t.startRule){if(!(t.startRule in a))throw new Error("Can't start parsing from rule \""+t.startRule+'".');c=a[t.startRule]}function v(){return e.substring(h,d)}function y(){return S(h,d)}function b(e,t){return{type:"literal",text:e,ignoreCase:t}}function w(e,t,n){return{type:"class",parts:e,inverted:t,ignoreCase:n}}function T(t){var n,i=p[t];if(i)return i;for(n=t-1;!p[n];)n--;for(i={line:(i=p[n]).line,column:i.column};n<t;)10===e.charCodeAt(n)?(i.line++,i.column=1):i.column++,n++;return p[t]=i,i}function S(e,t){var n=T(e),i=T(t);return{start:{offset:e,line:n.line,column:n.column},end:{offset:t,line:i.line,column:i.column}}}function I(e){d<g||(d>g&&(g=d,f=[]),f.push(e))}function E(e){return e.split("").map(function(e){return e.charCodeAt(0)-32})}if(t.data={},n=function t(n){for(var i,r=l[n],s=0,a=[],c=r.length,p=[],g=[];;){for(;s<c;)switch(r[s]){case 0:g.push(u[r[s+1]]),s+=2;break;case 1:g.push(void 0),s++;break;case 2:g.push(null),s++;break;case 3:g.push(o),s++;break;case 4:g.push([]),s++;break;case 5:g.push(d),s++;break;case 6:g.pop(),s++;break;case 7:d=g.pop(),s++;break;case 8:g.length-=r[s+1],s+=2;break;case 9:g.splice(-2,1),s++;break;case 10:g[g.length-2].push(g.pop()),s++;break;case 11:g.push(g.splice(g.length-r[s+1],r[s+1])),s+=2;break;case 12:g.push(e.substring(g.pop(),d)),s++;break;case 13:p.push(c),a.push(s+3+r[s+1]+r[s+2]),g[g.length-1]?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 14:p.push(c),a.push(s+3+r[s+1]+r[s+2]),g[g.length-1]===o?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 15:p.push(c),a.push(s+3+r[s+1]+r[s+2]),g[g.length-1]!==o?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 16:g[g.length-1]!==o?(p.push(c),a.push(s),c=s+2+r[s+1],s+=2):s+=2+r[s+1];break;case 17:p.push(c),a.push(s+3+r[s+1]+r[s+2]),e.length>d?(c=s+3+r[s+1],s+=3):(c=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 18:p.push(c),a.push(s+4+r[s+2]+r[s+3]),e.substr(d,u[r[s+1]].length)===u[r[s+1]]?(c=s+4+r[s+2],s+=4):(c=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 19:p.push(c),a.push(s+4+r[s+2]+r[s+3]),e.substr(d,u[r[s+1]].length).toLowerCase()===u[r[s+1]]?(c=s+4+r[s+2],s+=4):(c=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 20:p.push(c),a.push(s+4+r[s+2]+r[s+3]),u[r[s+1]].test(e.charAt(d))?(c=s+4+r[s+2],s+=4):(c=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 21:g.push(e.substr(d,r[s+1])),d+=r[s+1],s+=2;break;case 22:g.push(u[r[s+1]]),d+=u[r[s+1]].length,s+=2;break;case 23:g.push(o),0===m&&I(u[r[s+1]]),s+=2;break;case 24:h=g[g.length-1-r[s+1]],s+=2;break;case 25:h=d,s++;break;case 26:i=r.slice(s+4,s+4+r[s+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-r[s+2],r[s+2],u[r[s+1]].apply(null,i)),s+=4+r[s+3];break;case 27:g.push(t(r[s+1])),s+=2;break;case 28:m++,s++;break;case 29:m--,s++;break;default:throw new Error("Invalid opcode: "+r[s]+".")}if(!(p.length>0))break;c=p.pop(),s=a.pop()}return g[0]}(c),n!==o&&d===e.length)return n;throw n!==o&&d<e.length&&I({type:"end"}),i=f,r=g<e.length?e.charAt(g):null,s=g<e.length?S(g,g+1):S(g,g),new Oe(Oe.buildMessage(i,r),i,r,s)};!function(e){e.parse=function(e,t){var n={startRule:t};try{xe(e,n)}catch(e){n.data=-1}return n.data},e.nameAddrHeaderParse=function(t){var n=e.parse(t,"Name_Addr_Header");return-1!==n?n:void 0},e.URIParse=function(t){var n=e.parse(t,"SIP_URI");return-1!==n?n:void 0}}(He||(He={})),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"}($e||($e={}));var Ne={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 Me(e,t){void 0===t&&(t=32);for(var n="",i=0;i<e;i++){n+=Math.floor(Math.random()*t).toString(t)}return n}function je(e){return Ne[e]||""}function Ue(){return Me(10)}function Fe(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),i=n.length,r="",s=0;s<i;s++)0!==s&&(r+="-"),r+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[r]&&(r=t[r]),r}function Le(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}var Be=function(){function e(){this.headers={}}return e.prototype.addHeader=function(e,t){var n={raw:t};e=Fe(e),this.headers[e]?this.headers[e].push(n):this.headers[e]=[n]},e.prototype.getHeader=function(e){var t=this.headers[Fe(e)];if(t)return t[0]?t[0].raw:void 0},e.prototype.getHeaders=function(e){var t=this.headers[Fe(e)],n=[];if(!t)return[];for(var i=0,r=t;i<r.length;i++){var s=r[i];n.push(s.raw)}return n},e.prototype.hasHeader=function(e){return!!this.headers[Fe(e)]},e.prototype.parseHeader=function(e,t){if(void 0===t&&(t=0),e=Fe(e),this.headers[e]&&!(t>=this.headers[e].length)){var n=this.headers[e][t],i=n.raw;if(n.parsed)return n.parsed;var r=He.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(n.parsed=r,r)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[Fe(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}(),Ve=function(e){function t(){return e.call(this)||this}return r(t,e),t}(Be),Ge=function(e){function t(){return e.call(this)||this}return r(t,e),t}(Be),We=function(){function e(t,n,i,r,o,a,c){this.headers={},this.extraHeaders=[],this.options=e.getDefaultOptions(),o&&(this.options=s(s({},this.options),o),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),a&&a.length&&(this.extraHeaders=a.slice()),c&&(this.body={body:c.content,contentType:c.contentType}),this.method=t,this.ruri=n.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Ue(),this.from=e.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=r.clone(),this.toTag=this.options.toTag,this.to=e.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+Me(15),this.cseq=this.options.cseq,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")}return e.getDefaultOptions=function(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}},e.makeNameAddrHeader=function(e,t,n){var i={};return n&&(i.tag=n),new _e(e,t,i)},e.prototype.getHeader=function(e){var t=this.headers[Fe(e)];if(t){if(t[0])return t[0]}else for(var n=new RegExp("^\\s*"+e+"\\s*:","i"),i=0,r=this.extraHeaders;i<r.length;i++){var s=r[i];if(n.test(s))return s.substring(s.indexOf(":")+1).trim()}},e.prototype.getHeaders=function(e){var t=[],n=this.headers[Fe(e)];if(n)for(var i=0,r=n;i<r.length;i++){var s=r[i];t.push(s)}else for(var o=new RegExp("^\\s*"+e+"\\s*:","i"),a=0,c=this.extraHeaders;a<c.length;a++){var u=c[a];o.test(u)&&t.push(u.substring(u.indexOf(":")+1).trim())}return t},e.prototype.hasHeader=function(e){if(this.headers[Fe(e)])return!0;for(var t=new RegExp("^\\s*"+e+"\\s*:","i"),n=0,i=this.extraHeaders;n<i.length;n++){var r=i[n];if(t.test(r))return!0}return!1},e.prototype.setHeader=function(e,t){this.headers[Fe(e)]=t instanceof Array?t:[t]},e.prototype.setViaHeader=function(e,t){this.options.hackViaTcp&&(t="TCP");var n="SIP/2.0/"+t;n+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(n+=";rport"),this.setHeader("via",n),this.branch=e},e.prototype.toString=function(){var e="";for(var t in e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n",this.headers)if(this.headers[t])for(var n=0,i=this.headers[t];n<i.length;n++){e+=t+": "+i[n]+"\r\n"}for(var r=0,s=this.extraHeaders;r<s.length;r++){e+=(t=s[r]).trim()+"\r\n"}return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+Le(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+Le(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e},e}();function Ke(e){return"application/sdp"===e?"session":"render"}function ze(e){var t="string"==typeof e?e:e.body,n="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ke(n),contentType:n,content:t}}function Ye(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Je(e){var t,n,i,r;e instanceof Ve&&(e.body&&(t=(r=e.parseHeader("Content-Disposition"))?r.type:void 0,n=e.parseHeader("Content-Type"),i=e.body));e instanceof Ge&&(e.body&&(t=(r=e.parseHeader("Content-Disposition"))?r.type:void 0,n=e.parseHeader("Content-Type"),i=e.body));if(e instanceof We&&e.body)if(t=e.getHeader("Content-Disposition"),n=e.getHeader("Content-Type"),"string"==typeof e.body){if(!n)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(n&&n!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");n=e.body.contentType,i=e.body.body}if(Ye(e)&&(t=e.contentDisposition,n=e.contentType,i=e.content),i){if(n&&!t&&(t=Ke(n)),!t)throw new Error("Content disposition undefined.");if(!n)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:n,content:i}}}var Ze=function(){function e(){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()}return e.hashStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendStr(e).end(t)},e.hashAsciiStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendAsciiStr(e).end(t)},e._hex=function(t){var n,i,r,s,o=e.hexChars,a=e.hexOut;for(s=0;s<4;s+=1)for(i=8*s,n=t[s],r=0;r<8;r+=2)a[i+1+r]=o.charAt(15&n),n>>>=4,a[i+0+r]=o.charAt(15&n),n>>>=4;return a.join("")},e._md5cycle=function(e,t){var n=e[0],i=e[1],r=e[2],s=e[3];i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[0]-680876936|0)<<7|n>>>25)+i|0)&i|~n&r)+t[1]-389564586|0)<<12|s>>>20)+n|0)&n|~s&i)+t[2]+606105819|0)<<17|r>>>15)+s|0)&s|~r&n)+t[3]-1044525330|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[4]-176418897|0)<<7|n>>>25)+i|0)&i|~n&r)+t[5]+1200080426|0)<<12|s>>>20)+n|0)&n|~s&i)+t[6]-1473231341|0)<<17|r>>>15)+s|0)&s|~r&n)+t[7]-45705983|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[8]+1770035416|0)<<7|n>>>25)+i|0)&i|~n&r)+t[9]-1958414417|0)<<12|s>>>20)+n|0)&n|~s&i)+t[10]-42063|0)<<17|r>>>15)+s|0)&s|~r&n)+t[11]-1990404162|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&r|~i&s)+t[12]+1804603682|0)<<7|n>>>25)+i|0)&i|~n&r)+t[13]-40341101|0)<<12|s>>>20)+n|0)&n|~s&i)+t[14]-1502002290|0)<<17|r>>>15)+s|0)&s|~r&n)+t[15]+1236535329|0)<<22|i>>>10)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[1]-165796510|0)<<5|n>>>27)+i|0)&r|i&~r)+t[6]-1069501632|0)<<9|s>>>23)+n|0)&i|n&~i)+t[11]+643717713|0)<<14|r>>>18)+s|0)&n|s&~n)+t[0]-373897302|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[5]-701558691|0)<<5|n>>>27)+i|0)&r|i&~r)+t[10]+38016083|0)<<9|s>>>23)+n|0)&i|n&~i)+t[15]-660478335|0)<<14|r>>>18)+s|0)&n|s&~n)+t[4]-405537848|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[9]+568446438|0)<<5|n>>>27)+i|0)&r|i&~r)+t[14]-1019803690|0)<<9|s>>>23)+n|0)&i|n&~i)+t[3]-187363961|0)<<14|r>>>18)+s|0)&n|s&~n)+t[8]+1163531501|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i&s|r&~s)+t[13]-1444681467|0)<<5|n>>>27)+i|0)&r|i&~r)+t[2]-51403784|0)<<9|s>>>23)+n|0)&i|n&~i)+t[7]+1735328473|0)<<14|r>>>18)+s|0)&n|s&~n)+t[12]-1926607734|0)<<20|i>>>12)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[5]-378558|0)<<4|n>>>28)+i|0)^i^r)+t[8]-2022574463|0)<<11|s>>>21)+n|0)^n^i)+t[11]+1839030562|0)<<16|r>>>16)+s|0)^s^n)+t[14]-35309556|0)<<23|i>>>9)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[1]-1530992060|0)<<4|n>>>28)+i|0)^i^r)+t[4]+1272893353|0)<<11|s>>>21)+n|0)^n^i)+t[7]-155497632|0)<<16|r>>>16)+s|0)^s^n)+t[10]-1094730640|0)<<23|i>>>9)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[13]+681279174|0)<<4|n>>>28)+i|0)^i^r)+t[0]-358537222|0)<<11|s>>>21)+n|0)^n^i)+t[3]-722521979|0)<<16|r>>>16)+s|0)^s^n)+t[6]+76029189|0)<<23|i>>>9)+r|0,i=((i+=((r=((r+=((s=((s+=((n=((n+=(i^r^s)+t[9]-640364487|0)<<4|n>>>28)+i|0)^i^r)+t[12]-421815835|0)<<11|s>>>21)+n|0)^n^i)+t[15]+530742520|0)<<16|r>>>16)+s|0)^s^n)+t[2]-995338651|0)<<23|i>>>9)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[0]-198630844|0)<<6|n>>>26)+i|0)|~r))+t[7]+1126891415|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[14]-1416354905|0)<<15|r>>>17)+s|0)|~n))+t[5]-57434055|0)<<21|i>>>11)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[12]+1700485571|0)<<6|n>>>26)+i|0)|~r))+t[3]-1894986606|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[10]-1051523|0)<<15|r>>>17)+s|0)|~n))+t[1]-2054922799|0)<<21|i>>>11)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[8]+1873313359|0)<<6|n>>>26)+i|0)|~r))+t[15]-30611744|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[6]-1560198380|0)<<15|r>>>17)+s|0)|~n))+t[13]+1309151649|0)<<21|i>>>11)+r|0,i=((i+=((s=((s+=(i^((n=((n+=(r^(i|~s))+t[4]-145523070|0)<<6|n>>>26)+i|0)|~r))+t[11]-1120210379|0)<<10|s>>>22)+n|0)^((r=((r+=(n^(s|~i))+t[2]+718787259|0)<<15|r>>>17)+s|0)|~n))+t[9]-343485551|0)<<21|i>>>11)+r|0,e[0]=n+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=s+e[3]|0},e.prototype.start=function(){return this._dataLength=0,this._bufferLength=0,this._state.set(e.stateIdentity),this},e.prototype.appendStr=function(t){var n,i,r=this._buffer8,s=this._buffer32,o=this._bufferLength;for(i=0;i<t.length;i+=1){if((n=t.charCodeAt(i))<128)r[o++]=n;else if(n<2048)r[o++]=(n>>>6)+192,r[o++]=63&n|128;else if(n<55296||n>56319)r[o++]=(n>>>12)+224,r[o++]=n>>>6&63|128,r[o++]=63&n|128;else{if((n=1024*(n-55296)+(t.charCodeAt(++i)-56320)+65536)>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");r[o++]=(n>>>18)+240,r[o++]=n>>>12&63|128,r[o++]=n>>>6&63|128,r[o++]=63&n|128}o>=64&&(this._dataLength+=64,e._md5cycle(this._state,s),o-=64,s[0]=s[16])}return this._bufferLength=o,this},e.prototype.appendAsciiStr=function(t){for(var n,i=this._buffer8,r=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)i[s++]=t.charCodeAt(o++);if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,r),s=0}return this._bufferLength=s,this},e.prototype.appendByteArray=function(t){for(var n,i=this._buffer8,r=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)i[s++]=t[o++];if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,r),s=0}return this._bufferLength=s,this},e.prototype.getState=function(){var e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}},e.prototype.setState=function(e){var t,n=e.buffer,i=e.state,r=this._state;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],t=0;t<n.length;t+=1)this._buffer8[t]=n.charCodeAt(t)},e.prototype.end=function(t){void 0===t&&(t=!1);var n,i=this._bufferLength,r=this._buffer8,s=this._buffer32,o=1+(i>>2);if(this._dataLength+=i,r[i]=128,r[i+1]=r[i+2]=r[i+3]=0,s.set(e.buffer32Identity.subarray(o),o),i>55&&(e._md5cycle(this._state,s),s.set(e.buffer32Identity)),(n=8*this._dataLength)<=4294967295)s[14]=n;else{var a=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===a)return;var c=parseInt(a[2],16),u=parseInt(a[1],16)||0;s[14]=c,s[15]=u}return e._md5cycle(this._state,s),t?this._state:e._hex(this._state)},e.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),e.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),e.hexChars="0123456789abcdef",e.hexOut=[],e.onePassHasher=new e,e}();function Qe(e){return Ze.hashStr(e)}"5d41402abc4b2a76b9719d911017c592"!==Ze.hashStr("hello")&&console.error("Md5 self test failed.");var Xe,et=function(){function e(e,t,n,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=n,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}return e.prototype.authenticate=function(e,t,n){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=Me(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(n),!0},e.prototype.toString=function(){var 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(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,n;""!==(t=this.ha1)&&void 0!==t||(t=Qe(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(n=Qe(this.method+":"+this.uri),this.response=Qe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=Qe(this.method+":"+this.uri+":"+Qe(e||"")),this.response=Qe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):void 0===this.qop&&(n=Qe(this.method+":"+this.uri),this.response=Qe(t+":"+this.nonce+":"+n))},e}();function tt(e,t){var n="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);var i=t.reasonPhrase?t.reasonPhrase:je(t.statusCode),r="SIP/2.0 "+t.statusCode+" "+i+n;t.statusCode>=100&&t.statusCode,t.statusCode;var s="From: "+e.getHeader("From")+n,o="Call-ID: "+e.callId+n,a="CSeq: "+e.cseq+" "+e.method+n,c=e.getHeaders("via").reduce(function(e,t){return e+"Via: "+t+n},""),u="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var l=t.toTag;l||(l=Ue()),u+=";tag="+l}u+=n;var d="";t.supported&&(d="Supported: "+t.supported.join(", ")+n);var h="";t.userAgent&&(h="User-Agent: "+t.userAgent+n);var p="";return t.extraHeaders&&(p=t.extraHeaders.reduce(function(e,t){return e+t.trim()+n},"")),r+=c,r+=s,r+=u,r+=a,r+=o,r+=d,r+=h,r+=p,t.body?(r+="Content-Type: "+t.body.contentType+n,r+="Content-Length: "+Le(t.body.content)+n+n,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){var n=t,i=0,r=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===i;){if(-1===(r=e.indexOf("\r\n",n)))return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?n=r+2:i=r}return i}function n(e,t,n,i){var r,s=t.indexOf(":",n),o=t.substring(n,s).trim(),a=t.substring(s+1,i).trim();switch(o.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(r=e.parseHeader("Via"))&&(e.via=r,e.viaBranch=r.branch):r=0;break;case"from":case"f":e.setHeader("from",a),(r=e.parseHeader("from"))&&(e.from=r,e.fromTag=r.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),(r=e.parseHeader("to"))&&(e.to=r,e.toTag=r.getParam("tag"));break;case"record-route":if(-1===(r=He.parse(a,"Record_Route"))){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach(function(t){e.addHeader("record-route",a.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",a),(r=e.parseHeader("call-id"))&&(e.callId=a);break;case"contact":case"m":if(-1===(r=He.parse(a,"Contact"))){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach(function(t){e.addHeader("contact",a.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",a),r=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),r=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),(r=e.parseHeader("cseq"))&&(e.cseq=r.value),e instanceof Ge&&(e.method=r.method);break;case"max-forwards":e.setHeader("max-forwards",a),r=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),r=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),r=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),(r=e.parseHeader("refer-to"))&&(e.referTo=r);break;default:e.addHeader(o.toLowerCase(),a),r=0}return void 0!==r||{error:"error parsing header '"+o+"'"}}e.getHeader=t,e.parseHeader=n,e.parseMessage=function(e,i){var r=0,s=e.indexOf("\r\n");if(-1!==s){var o,a=e.substring(0,s),c=He.parse(a,"Request_Response");if(-1!==c){var u;for(c.status_code?((o=new Ge).statusCode=c.status_code,o.reasonPhrase=c.reason_phrase):((o=new Ve).method=c.method,o.ruri=c.uri),o.data=e,r=s+2;;){if(-2===(s=t(e,r))){u=r+2;break}if(-1===s)return void i.error("malformed message");var l=n(o,e,r,s);if(l&&!0!==l)return void i.error(l.error);r=s+2}return o.hasHeader("content-length")?o.body=e.substr(u,Number(o.getHeader("content-length"))):o.body=e.substring(u),o}i.warn('error parsing first line of SIP message: "'+a+'"')}else i.warn("no CRLF found, not a SIP message, discarded")}}(Xe||(Xe={}));var nt,it,rt=function(){function e(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}return e.initialDialogStateForUserAgentClient=function(e,t){var n=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");var r=i.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");var u=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:u,remoteURI:l,remoteTarget:r,routeSet:n,secure:!1}},e.initialDialogStateForUserAgentServer=function(e,t,n){void 0===n&&(n=!1);var i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");var s=r.uri,o=e.cseq,a=e.callId,c=t,u=e.fromTag,l=e.from.uri;return{id:a+c+u,early:n,callId:a,localTag:c,remoteTag:u,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:l,remoteTarget:s,routeSet:i,secure:!1}},e.prototype.dispose=function(){this.core.dialogs.delete(this.id)},Object.defineProperty(e.prototype,"id",{get:function(){return this.dialogState.id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"early",{get:function(){return this.dialogState.early},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"callId",{get:function(){return this.dialogState.callId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localTag",{get:function(){return this.dialogState.localTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTag",{get:function(){return this.dialogState.remoteTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localSequenceNumber",{get:function(){return this.dialogState.localSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteSequenceNumber",{get:function(){return this.dialogState.remoteSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localURI",{get:function(){return this.dialogState.localURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteURI",{get:function(){return this.dialogState.remoteURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTarget",{get:function(){return this.dialogState.remoteTarget},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"routeSet",{get:function(){return this.dialogState.routeSet},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"secure",{get:function(){return this.dialogState.secure},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this.core},enumerable:!1,configurable:!0}),e.prototype.confirm=function(){this.dialogState.early=!1},e.prototype.receiveRequest=function(e){if(e.method!==$e.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)}},e.prototype.recomputeRouteSet=function(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()},e.prototype.createOutgoingRequestMessage=function(e,t){var n,i=this.remoteURI,r=this.remoteTag,s=this.localURI,o=this.localTag,a=this.callId;n=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;var c=this.remoteTarget,u=this.routeSet,l=t&&t.extraHeaders,d=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,s,i,{callId:a,cseq:n,fromTag:o,toTag:r,routeSet:u},l,d)},e.prototype.incrementLocalSequenceNumber=function(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1},e.prototype.sequenceGuard=function(e){return e.method===$e.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))},e}();!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(nt||(nt={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(it||(it={}));var st,ot=500,at=5e3,ct={T1:ot,T2:4e3,T4:at,TIMER_B:32e3,TIMER_D:0,TIMER_F:3e3,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},ut=function(e){function t(t){var n=this.constructor,i=e.call(this,t)||this;return Object.setPrototypeOf(i,n.prototype),i}return r(t,e),t}(Error),lt=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return r(t,e),t}(ut),dt=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return r(t,e),t}(ut),ht=function(){function e(e,t,n,i,r){this._transport=e,this._user=t,this._id=n,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,n),this.logger.debug("Constructing ".concat(this.typeToString()," with id ").concat(this.id,"."))}return e.prototype.dispose=function(){this.logger.debug("Destroyed ".concat(this.typeToString()," with id ").concat(this.id,"."))},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),e.prototype.addStateChangeListener=function(e,t){var n=this,i=function(){n.removeStateChangeListener(i),e()};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)},e.prototype.notifyStateChangeListeners=function(){this.listeners.slice().forEach(function(e){return e()})},e.prototype.removeStateChangeListener=function(e){this.listeners=this.listeners.filter(function(t){return t!==e})},e.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in ".concat(this.typeToString()," with id ").concat(this.id,".")),this.logger.error(t)},e.prototype.send=function(e){var t=this;return this.transport.send(e).catch(function(e){if(e instanceof dt)throw t.onTransportError(e),e;var n;throw n=e&&"string"==typeof e.message?new dt(e.message):new dt,t.onTransportError(n),n})},e.prototype.setState=function(e){this.logger.debug('State change to "'.concat(e,'" on ').concat(this.typeToString()," with id ").concat(this.id,".")),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()},e.prototype.typeToString=function(){return"UnknownType"},e}(),pt=function(e){function t(n,i,r,s,o){var a=e.call(this,i,r,t.makeId(n),s,o)||this;return a._request=n,a.user=r,n.setViaHeader(a.id,i.protocol),a}return r(t,e),t.makeId=function(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())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(ht);!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(st||(st={}));var gt=function(e){function t(t,n,i){var r=e.call(this,t,n,i,st.Calling,"sip.transaction.ict")||this;return r.ackRetransmissionCache=new Map,r.B=setTimeout(function(){return r.timerB()},ct.TIMER_B),r.send(t.toString()).catch(function(e){r.logTransportError(e,"Failed to send initial outgoing request.")}),r}return r(t,e),t.prototype.dispose=function(){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),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ict"},enumerable:!1,configurable:!0}),t.prototype.ackResponse=function(e){var t=this,n=e.toTag;if(!n)throw new Error("To tag undefined.");var i="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(i,this.transport.protocol),this.ackRetransmissionCache.set(n,e),this.send(e.toString()).catch(function(e){t.logTransportError(e,"Failed to send ACK to 2xx response.")})},t.prototype.receiveResponse=function(e){var t=this,n=e.statusCode;if(!n||n<100||n>699)throw new Error("Invalid status code ".concat(n));switch(this.state){case st.Calling:if(n>=100&&n<=199)return this.stateTransition(st.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(st.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(st.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Proceeding:if(n>=100&&n<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(st.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(st.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Accepted:if(n>=200&&n<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var i=this.ackRetransmissionCache.get(e.toTag);return i?void this.send(i.toString()).catch(function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case st.Completed:if(n>=300&&n<=699)return void this.ack(e);break;case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var r="Received unexpected ".concat(n," response while in state ").concat(this.state,".");this.logger.warn(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(st.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,n=this.request.ruri,i=this.request.callId,r=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK ".concat(n," SIP/2.0\r\n");c&&(u+="Route: ".concat(c,"\r\n")),u+="Via: ".concat(a,"\r\n"),u+="To: ".concat(o,"\r\n"),u+="From: ".concat(s,"\r\n"),u+="Call-ID: ".concat(i,"\r\n"),u+="CSeq: ".concat(r," ACK\r\n"),u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch(function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")})},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case st.Calling:i();break;case st.Proceeding:this.state!==st.Calling&&i();break;case st.Accepted:case st.Completed:this.state!==st.Calling&&this.state!==st.Proceeding&&i();break;case st.Terminated:this.state!==st.Calling&&this.state!==st.Accepted&&this.state!==st.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),st.Proceeding,e===st.Completed&&(this.D=setTimeout(function(){return n.timerD()},ct.TIMER_D)),e===st.Accepted&&(this.M=setTimeout(function(){return n.timerM()},ct.TIMER_M)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerA=function(){},t.prototype.timerB=function(){this.logger.debug("Timer B expired for INVITE client transaction ".concat(this.id,".")),this.state===st.Calling&&(this.onRequestTimeout(),this.stateTransition(st.Terminated))},t.prototype.timerD=function(){this.logger.debug("Timer D expired for INVITE client transaction ".concat(this.id,".")),this.state===st.Completed&&this.stateTransition(st.Terminated)},t.prototype.timerM=function(){this.logger.debug("Timer M expired for INVITE client transaction ".concat(this.id,".")),this.state===st.Accepted&&this.stateTransition(st.Terminated)},t}(pt),ft=function(e){function t(t,n,i,r,s){var o=e.call(this,n,i,t.viaBranch,r,s)||this;return o._request=t,o.user=i,o}return r(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t}(ht),mt=function(e){function t(t,n,i){return e.call(this,t,n,i,st.Proceeding,"sip.transaction.ist")||this}return r(t,e),t.prototype.dispose=function(){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),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case st.Proceeding:if(e.method===$e.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case st.Accepted:if(e.method===$e.INVITE)return;break;case st.Completed:if(e.method===$e.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===$e.ACK)return void this.stateTransition(st.Confirmed);break;case st.Confirmed:case st.Terminated:if(e.method===$e.INVITE||e.method===$e.ACK)return;break;default:throw new Error("Invalid state ".concat(this.state))}var n="INVITE server transaction received unexpected ".concat(e.method," request while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));switch(this.state){case st.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(st.Accepted),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(st.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send non-2xx final response.")});break;case st.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 2xx response.")});break;case st.Completed:case st.Confirmed:case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var i="INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(i),new Error(i)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===st.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(function(t){e.logTransportError(t,"Failed to send 2xx response.")})},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t.state," to ").concat(e))};switch(e){case st.Proceeding:n();break;case st.Accepted:case st.Completed:this.state!==st.Proceeding&&n();break;case st.Confirmed:this.state!==st.Completed&&n();break;case st.Terminated:this.state!==st.Accepted&&this.state!==st.Completed&&this.state!==st.Confirmed&&n();break;default:n()}this.stopProgressExtensionTimer(),e===st.Accepted&&(this.L=setTimeout(function(){return t.timerL()},ct.TIMER_L)),e===st.Completed&&(this.H=setTimeout(function(){return t.timerH()},ct.TIMER_H)),e===st.Confirmed&&(this.I=setTimeout(function(){return t.timerI()},ct.TIMER_I)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction ".concat(e.id,".")),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch(function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")})},ct.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timerG=function(){},t.prototype.timerH=function(){this.logger.debug("Timer H expired for INVITE server transaction ".concat(this.id,".")),this.state===st.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(st.Terminated))},t.prototype.timerI=function(){this.logger.debug("Timer I expired for INVITE server transaction ".concat(this.id,".")),this.stateTransition(st.Terminated)},t.prototype.timerL=function(){this.logger.debug("Timer L expired for INVITE server transaction ".concat(this.id,".")),this.state===st.Accepted&&this.stateTransition(st.Terminated)},t}(ft),vt=function(e){function t(t,n,i){var r=e.call(this,t,n,i,st.Trying,"sip.transaction.nict")||this;return r.F=setTimeout(function(){return r.timerF()},ct.TIMER_F),r.send(t.toString()).catch(function(e){r.logTransportError(e,"Failed to send initial outgoing request.")}),r}return r(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!1,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code ".concat(t));switch(this.state){case st.Trying:if(t>=100&&t<=199)return this.stateTransition(st.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(st.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(st.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case st.Completed:case st.Terminated:return;default:throw new Error("Invalid state ".concat(this.state))}var n="Non-INVITE client transaction received unexpected ".concat(t," response while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(st.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case st.Trying:i();break;case st.Proceeding:this.state!==st.Trying&&i();break;case st.Completed:this.state!==st.Trying&&this.state!==st.Proceeding&&i();break;case st.Terminated:this.state!==st.Trying&&this.state!==st.Proceeding&&this.state!==st.Completed&&(t||i());break;default:i()}e===st.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(function(){return n.timerK()},ct.TIMER_K)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerF=function(){this.logger.debug("Timer F expired for non-INVITE client transaction ".concat(this.id,".")),this.state!==st.Trying&&this.state!==st.Proceeding||(this.onRequestTimeout(),this.stateTransition(st.Terminated))},t.prototype.timerK=function(){this.state===st.Completed&&this.stateTransition(st.Terminated)},t}(pt),yt=function(e){function t(t,n,i){return e.call(this,t,n,i,st.Trying,"sip.transaction.nist")||this}return r(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case st.Trying:break;case st.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case st.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")});break;case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case st.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(st.Proceeding),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(st.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send final response.")});break;case st.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(st.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send final response.")});break;case st.Completed:return;case st.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var i="Non-INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(i),new Error(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(st.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var i=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case st.Trying:i();break;case st.Proceeding:this.state!==st.Trying&&i();break;case st.Completed:this.state!==st.Trying&&this.state!==st.Proceeding&&i();break;case st.Terminated:this.state!==st.Proceeding&&this.state!==st.Completed&&(t||i());break;default:i()}e===st.Completed&&(this.J=setTimeout(function(){return n.timerJ()},ct.TIMER_J)),e===st.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerJ=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction ".concat(this.id,".")),this.state===st.Completed&&this.stateTransition(st.Terminated)},t}(ft),bt=function(){function e(e,t,n,i){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.cancel=function(t,n){var i=this;if(void 0===n&&(n={}),!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.");var r=this.core.makeOutgoingRequestMessage($e.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},n.extraHeaders);return r.branch=this.message.branch,this.message.headers.Route&&(r.headers.Route=this.message.headers.Route),t&&r.setHeader("Reason",t),this.transaction.state===st.Proceeding?new e(vt,this.core,r):this.transaction.addStateChangeListener(function(){i.transaction&&i.transaction.state===st.Proceeding&&new e(vt,i.core,r)},{once:!0}),r},e.prototype.authenticationGuard=function(e,t){var n,i,r=e.statusCode;if(!r)throw new Error("Response status code undefined.");if(401!==r&&407!==r)return!0;if(401===r?(n=e.parseHeader("www-authenticate"),i="authorization"):(n=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!n)return this.logger.warn(r+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(r+" 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,n))return!0;this.challenged=!0,n.stale&&(this.stale=!0);var s=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),s=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",s+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new Ge;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new Ge;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var 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 ".concat(t))}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===st.Terminated&&(e.core.userAgentClients.delete(i),n===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var i=n.id+n.request.method;this.core.userAgentClients.set(i,this)},e}(),wt=function(e){function t(t,n,i){var r,s=t.createOutgoingRequestMessage($e.BYE,i);return r=e.call(this,vt,t.userAgentCore,s,n)||this,t.dispose(),r}return r(t,e),t}(bt),Tt=function(){function e(e,t,n,i){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=n.toTag?n.toTag:Ue(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new lt("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new lt("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new lt("".concat(this.message.method," not redirectable in state ").concat(this.transaction.state,"."));var n=t.statusCode;if(n<300||n>399)throw new TypeError("Invalid statusCode: ".concat(n));var i=new Array;return e.forEach(function(e){return i.push("Contact: ".concat(e.toString()))}),t.extraHeaders=(t.extraHeaders||[]).concat(i),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new lt("".concat(this.message.method," not rejectable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new lt("".concat(this.message.method," not tryingable in state ").concat(this.transaction.state,"."));return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding||this.transaction.state===st.Accepted;if(this.transaction instanceof yt)return this.transaction.state===st.Trying||this.transaction.state===st.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return!1;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return this.transaction.state===st.Trying||this.transaction.state===st.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return this.transaction.state===st.Trying||this.transaction.state===st.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof mt)return this.transaction.state===st.Proceeding;if(this.transaction instanceof yt)return this.transaction.state===st.Trying;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),e.prototype.reply=function(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;var t=tt(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===st.Terminated&&(e.core.userAgentServers.delete(i),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var i=n.id;this.core.userAgentServers.set(n.id,this)},e}(),St=function(e){function t(t,n,i){return e.call(this,yt,t.userAgentCore,n,i)||this}return r(t,e),t}(Tt),It=function(e){function t(t,n,i){var r=t.createOutgoingRequestMessage($e.INFO,i);return e.call(this,vt,t.userAgentCore,r,n)||this}return r(t,e),t}(bt),Et=function(e){function t(t,n,i){return e.call(this,yt,t.userAgentCore,n,i)||this}return r(t,e),t}(Tt),Rt=function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}return r(t,e),t}(bt),kt=function(e){function t(t,n,i){return e.call(this,yt,t,n,i)||this}return r(t,e),t}(Tt),Ct=function(e){function t(t,n,i){var r=t.createOutgoingRequestMessage($e.NOTIFY,i);return e.call(this,vt,t.userAgentCore,r,n)||this}return r(t,e),t}(bt);var At=function(e){function t(t,n,i){var r=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,yt,r,n,i)||this}return r(t,e),t}(Tt),Pt=function(e){function t(t,n,i){var r,s=t.createOutgoingRequestMessage($e.PRACK,i);return r=e.call(this,vt,t.userAgentCore,s,n)||this,t.signalingStateTransition(s),r}return r(t,e),t}(bt),_t=function(e){function t(t,n,i){var r=e.call(this,yt,t.userAgentCore,n,i)||this;return t.signalingStateTransition(n),r.dialog=t,r}return r(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(Tt),Dt=function(e){function t(t,n,i){var r=this,s=t.createOutgoingRequestMessage($e.INVITE,i);return(r=e.call(this,gt,t.userAgentCore,s,n)||this).delegate=n,t.signalingStateTransition(s),t.reinviteUserAgentClient=r,r.dialog=t,r}return r(t,e),t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e,this.dialog)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(n):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(n):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(n):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(n):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 ".concat(n))}}},t}(bt),qt=function(e){function t(t,n,i){var r=e.call(this,mt,t.userAgentCore,n,i)||this;return t.reinviteUserAgentServer=r,r.dialog=t,r}return r(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map(function(e){return"Record-Route: ".concat(e)}));var n=e.prototype.accept.call(this,t),i=this.dialog,r=s(s({},n),{session:i});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),r},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var n=e.prototype.progress.call(this,t),i=this.dialog,r=s(s({},n),{session:i});return t.body&&this.dialog.signalingStateTransition(t.body),r},t.prototype.redirect=function(e,t){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(Tt),Ot=function(e){function t(t,n,i){var r=t.createOutgoingRequestMessage($e.REFER,i);return e.call(this,vt,t.userAgentCore,r,n)||this}return r(t,e),t}(bt);var Ht,$t=function(e){function t(t,n,i){var r=void 0!==t.userAgentCore?t.userAgentCore:t;return e.call(this,yt,r,n,i)||this}return r(t,e),t}(Tt),xt=function(e){function t(t,n,i,r){var s=e.call(this,n,i)||this;return s.initialTransaction=t,s._signalingState=it.Initial,s.ackWait=!1,s.ackProcessing=!1,s.delegate=r,t instanceof mt&&(s.ackWait=!0),s.early||s.start2xxRetransmissionTimer(),s.signalingStateTransition(t.request),s.logger=n.loggerFactory.getLogger("sip.invite-dialog"),s.logger.log("INVITE dialog ".concat(s.id," constructed")),s}return r(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=it.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?nt.Early:this.ackWait?nt.AckWait:this._signalingState===it.Closed?nt.Terminated:nt.Confirmed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!1,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog ".concat(this.id," sending ACK request")),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof gt))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof gt))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}var n=this.createOutgoingRequestMessage($e.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(n),this.signalingStateTransition(n),{message:n}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending BYE request")),this.initialTransaction instanceof mt){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==st.Terminated)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.")}return new wt(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INFO request")),this.early)throw new Error("Dialog not confirmed.");return new It(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INVITE request")),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new Dt(this,e,t)},t.prototype.message=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending MESSAGE request")),this.early)throw new Error("Dialog not confirmed.");var n=this.createOutgoingRequestMessage($e.MESSAGE,t);return new Rt(this.core,n,e)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending NOTIFY request")),this.early)throw new Error("Dialog not confirmed.");return new Ct(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog ".concat(this.id," sending PRACK request")),new Pt(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending REFER request")),this.early)throw new Error("Dialog not confirmed.");return new Ot(this,e,t)},t.prototype.receiveRequest=function(t){var n=this;if(this.logger.log("INVITE dialog ".concat(this.id," received ").concat(t.method," request")),t.method!==$e.ACK)if(this.sequenceGuard(t)){if(e.prototype.receiveRequest.call(this,t),t.method===$e.INVITE){var i=function(){var e=n.ackWait?"waiting for initial ACK":"processing initial ACK";n.logger.warn("INVITE dialog ".concat(n.id," received re-INVITE while ").concat(e));n.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.")},r=Math.floor(10*Math.random())+1,s=["Retry-After: ".concat(r)];if(this.ackProcessing)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void i();if(this.ackWait&&this.signalingState!==it.Stable)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void i();if(this.reinviteUserAgentServer)return void this.core.replyStateless(t,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(t.method===$e.INVITE){var o=t.parseHeader("contact");if(!o)throw new Error("Contact undefined.");if(!(o instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=o.uri}switch(t.method){case $e.BYE:var a=new St(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(a):a.accept(),this.dispose();break;case $e.INFO:a=new Et(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(a):a.reject({statusCode:469,extraHeaders:["Recv-Info:"]});break;case $e.INVITE:a=new qt(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(a):a.reject({statusCode:488});break;case $e.MESSAGE:a=new kt(this.core,t);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(a):a.accept();break;case $e.NOTIFY:a=new At(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(a):a.accept();break;case $e.PRACK:a=new _t(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(a):a.accept();break;case $e.REFER:a=new $t(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(a):a.reject();break;default:this.logger.log("INVITE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."));else{if(this.ackWait){if(this.initialTransaction instanceof gt)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(t),this.delegate&&this.delegate.onAck){var c=this.delegate.onAck({message:t});c instanceof Promise&&(this.ackProcessing=!0,c.then(function(){return n.ackProcessing=!1}).catch(function(){return n.ackProcessing=!1}))}}},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var n=e.getHeader("require"),i=e.getHeader("rseq"),r=n&&n.includes("100rel")&&i?Number(i):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==it.HaveLocalOffer&&this.signalingState!==it.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=it.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=Je(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===it.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Ve)switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:this._signalingState=it.Stable,this._answer=t;break;case it.HaveRemoteOffer:case it.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Ge)switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:this._signalingState=it.Stable,this._answer=t;break;case it.HaveRemoteOffer:case it.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof We)switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:break;case it.HaveRemoteOffer:this._signalingState=it.Stable,this._answer=t;break;case it.Closed:break;default:throw new Error("Unexpected signaling state.")}if(Ye(e))switch(this._signalingState){case it.Initial:case it.Stable:this._signalingState=it.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case it.HaveLocalOffer:break;case it.HaveRemoteOffer:this._signalingState=it.Stable,this._answer=t;break;case it.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof mt){var t=this.initialTransaction,n=ct.T1,i=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,ct.T2),e.invite2xxTimer=setTimeout(i,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,n);var r=function(){t.state===st.Terminated&&(t.removeStateChangeListener(r),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addStateChangeListener(r)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof mt){var t=this.reinviteUserAgentServer.transaction,n=ct.T1,i=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,ct.T2),e.invite2xxTimer=setTimeout(i,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,n);var r=function(){t.state===st.Terminated&&(t.removeStateChangeListener(r),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addStateChangeListener(r)}},t}(rt);!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(Ht||(Ht={}));var Nt,Mt=[$e.ACK,$e.BYE,$e.CANCEL,$e.INFO,$e.INVITE,$e.MESSAGE,$e.NOTIFY,$e.OPTIONS,$e.PRACK,$e.REFER,$e.REGISTER,$e.SUBSCRIBE],jt=function(e){function t(t,n,i){var r=this,s=t.createOutgoingRequestMessage($e.SUBSCRIBE,i);return(r=e.call(this,vt,t.userAgentCore,s,n)||this).dialog=t,r}return r(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var i=Number(n);this.dialog.subscriptionExpires>i&&(this.dialog.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(bt),Ut=function(e){function t(t,n,i,r,s,o){var a=e.call(this,r,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=n,a._subscriptionExpiresInitial=n,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=i,a.logger=r.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog ".concat(a.id," constructed")),a}return r(t,e),t.initialDialogStateForSubscription=function(e,t){var n=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof _e))throw new Error("Contact not instance of NameAddrHeader.");var r=i.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:n,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog ".concat(this.id," received ").concat(t.method," request")),this.sequenceGuard(t))if(e.prototype.receiveRequest.call(this,t),t.method===$e.NOTIFY)this.onNotify(t);else this.logger.log("SUBSCRIBE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501});else this.logger.log("SUBSCRIBE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."))},t.prototype.refresh=function(){var e="Allow: "+Mt.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)},t.prototype.subscribe=function(e,t){var n=this;if(void 0===t&&(t={}),this.subscriptionState!==Ht.Pending&&this.subscriptionState!==Ht.Active)throw new Error("Invalid state ".concat(this.subscriptionState,'. May only re-subscribe while in state "pending" or "active".'));this.logger.log("SUBSCRIBE dialog ".concat(this.id," sending SUBSCRIBE request"));var i=new jt(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(function(){return n.timerN()},ct.TIMER_N),i},t.prototype.terminate=function(){this.stateTransition(Ht.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+Mt.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)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var n=e.parseHeader("Subscription-State");if(n&&n.state){var i=n.state,r=n.expires?Math.max(n.expires,0):void 0;switch(i){case"pending":this.stateTransition(Ht.Pending,r);break;case"active":this.stateTransition(Ht.Active,r);break;case"terminated":this.stateTransition(Ht.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}var s=new At(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())},t)}},t.prototype.stateTransition=function(e,t){var n=this,i=function(){n.logger.warn("Invalid subscription state transition from ".concat(n.subscriptionState," to ").concat(e))};switch(e){case Ht.Initial:case Ht.NotifyWait:return void i();case Ht.Pending:if(this.subscriptionState!==Ht.NotifyWait&&this.subscriptionState!==Ht.Pending)return void i();break;case Ht.Active:case Ht.Terminated:if(this.subscriptionState!==Ht.NotifyWait&&this.subscriptionState!==Ht.Pending&&this.subscriptionState!==Ht.Active)return void i();break;default:return void i()}e===Ht.Pending&&t&&(this.subscriptionExpires=t),e===Ht.Active&&t&&(this.subscriptionExpires=t),e===Ht.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timerN=function(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==Ht.Terminated&&(this.stateTransition(Ht.Terminated),this.onTerminated())},t}(rt);!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(Nt||(Nt={}));var Ft=function(){function e(e,t,n){this.logger=e,this.category=t,this.label=n}return e.prototype.error=function(e){this.genericLog(Nt.error,e)},e.prototype.warn=function(e){this.genericLog(Nt.warn,e)},e.prototype.log=function(e){this.genericLog(Nt.log,e)},e.prototype.debug=function(e){this.genericLog(Nt.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},Object.defineProperty(e.prototype,"level",{get:function(){return this.logger.level},set:function(e){this.logger.level=e},enumerable:!1,configurable:!0}),e}(),Lt=function(){function e(){this.builtinEnabled=!0,this._level=Nt.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:Nt.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new Ft(this,e,t);if(this.loggers[e])return this.loggers[e];var n=new Ft(this,e);return this.loggers[e]=n,n},e.prototype.genericLog=function(e,t,n,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,n,i),this.connector&&this.connector(Nt[e],t,n,i)},e.prototype.print=function(e,t,n,i){if("string"==typeof i){var r=[new Date,t];n&&r.push(n),i=r.concat(i).join(" | ")}switch(e){case Nt.error:console.error(i);break;case Nt.warn:console.warn(i);break;case Nt.log:console.log(i);break;case Nt.debug:console.debug(i)}},e}();!function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}r(t,e)}(bt);var Bt=function(e){function t(t,n,i){var r=e.call(this,gt,t,n,i)||this;return r.confirmedDialogAcks=new Map,r.confirmedDialogs=new Map,r.earlyDialogs=new Map,r.delegate=i,r}return r(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.onTransportError=function(t){if(this.transaction.state===st.Calling)return e.prototype.onTransportError.call(this,t);this.logger.error(t.message),this.logger.error("User agent client request transport error while sending ACK.")},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(n):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.");var i=rt.initialDialogStateForUserAgentClient(this.message,e),r=this.earlyDialogs.get(i.id);if(!r){if(!((a=this.transaction)instanceof gt))throw new Error("Transaction not instance of InviteClientTransaction.");r=new xt(a,this.core,i),this.earlyDialogs.set(r.id,r)}if(!r.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");r.signalingState!==it.Initial&&r.signalingState!==it.HaveLocalOffer||r.signalingStateTransition(e);var s=r;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:s,prack:function(e){return s.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(n):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.");i=rt.initialDialogStateForUserAgentClient(this.message,e);var o=this.confirmedDialogs.get(i.id);if(o){if(u=this.confirmedDialogAcks.get(i.id)){if(!((a=this.transaction)instanceof gt))throw new Error("Client transaction not instance of InviteClientTransaction.");a.ackResponse(u.message)}return}if(o=this.earlyDialogs.get(i.id))o.confirm(),o.recomputeRouteSet(e),this.earlyDialogs.delete(o.id),this.confirmedDialogs.set(o.id,o);else{var a;if(!((a=this.transaction)instanceof gt))throw new Error("Transaction not instance of InviteClientTransaction.");o=new xt(a,this.core,i),this.confirmedDialogs.set(o.id,o)}o.signalingState!==it.Initial&&o.signalingState!==it.HaveLocalOffer||o.signalingStateTransition(e);var c=o;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:c,ack:function(e){var n=c.ack(e);return t.confirmedDialogAcks.set(c.id,n),n}});else{var u=c.ack();this.confirmedDialogAcks.set(c.id,u)}return;case/^3[0-9]{2}$/.test(n):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(n):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code ".concat(n))}}},t}(bt),Vt=function(e){function t(t,n,i){var r=e.call(this,mt,t,n,i)||this;return r.core=t,r}return r(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new lt("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var n=this.transaction;if(!(n instanceof mt))throw new Error("Transaction not instance of InviteClientTransaction.");var i=rt.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new xt(n,this.core,i)}var r=this.message.getHeaders("record-route").map(function(e){return"Record-Route: ".concat(e)}),o="Contact: ".concat(this.core.configuration.contact.toString()),a="Allow: "+Mt.toString();if(!t.body)if(this.confirmedDialog.signalingState===it.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===it.Initial||this.confirmedDialog.signalingState===it.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(r),t.extraHeaders.push(a),t.extraHeaders.push(o);var c=e.prototype.accept.call(this,t),u=this.confirmedDialog,l=s(s({},c),{session:u});return t.body&&this.confirmedDialog.signalingState!==it.Stable&&this.confirmedDialog.signalingStateTransition(t.body),l},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new lt("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));if(!this.earlyDialog){var n=this.transaction;if(!(n instanceof mt))throw new Error("Transaction not instance of InviteClientTransaction.");var i=rt.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new xt(n,this.core,i)}var r=this.message.getHeaders("record-route").map(function(e){return"Record-Route: ".concat(e)}),o="Contact: ".concat(this.core.configuration.contact);t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(r),t.extraHeaders.push(o);var a=e.prototype.progress.call(this,t),c=this.earlyDialog,u=s(s({},a),{session:c});return t.body&&this.earlyDialog.signalingState!==it.Stable&&this.earlyDialog.signalingStateTransition(t.body),u},t.prototype.redirect=function(t,n){return void 0===n&&(n={statusCode:302}),e.prototype.redirect.call(this,t,n)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(Tt),Gt=function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}return r(t,e),t}(bt);!function(e){function t(t,n,i){return e.call(this,yt,t.userAgentCore,n,i)||this}r(t,e)}(Tt);var Wt,Kt=function(e){function t(t,n,i){return e.call(this,vt,t,n,i)||this}return r(t,e),t}(bt),zt=function(e){function t(t,n,i){var r=e.call(this,yt,t,n,i)||this;return r.core=t,r}return r(t,e),t}(Tt),Yt=function(e){function t(t,n,i){var r=this,s=n.getHeader("Event");if(!s)throw new Error("Event undefined");var o=n.getHeader("Expires");if(!o)throw new Error("Expires undefined");return(r=e.call(this,vt,t,n,i)||this).delegate=i,r.subscriberId=n.callId+n.fromTag+s,r.subscriptionExpiresRequested=r.subscriptionExpires=Number(o),r.subscriptionEvent=s,r.subscriptionState=Ht.NotifyWait,r.waitNotifyStart(),r}return r(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var n=e.message.parseHeader("Subscription-State");if(!n||!n.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var i=n.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state ".concat(i)),void e.reject({statusCode:489})}if("terminated"!==i&&!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=n.expires?Math.min(this.subscriptionExpires,Math.max(n.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=Ht.Pending;break;case"active":this.subscriptionState=Ht.Active;break;case"terminated":this.subscriptionState=Ht.Terminated;break;default:throw new Error("Unrecognized state ".concat(i,"."))}if(this.subscriptionState!==Ht.Terminated){var r=Ut.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Ut(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,r)}if(this.delegate&&this.delegate.onNotify){var s=e,o=this.dialog;this.delegate.onNotify({request:s,subscription:o})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(function(){return e.timerN()},ct.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var i=Number(n);i>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),i<this.subscriptionExpires&&(this.subscriptionExpires=i)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timerN=function(){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()},t}(bt),Jt=function(e){function t(t,n,i){var r=e.call(this,yt,t,n,i)||this;return r.core=t,r}return r(t,e),t}(Tt),Zt=["application/sdp","application/dtmf-relay"],Qt=function(){function e(e,t){void 0===t&&(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")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach(function(e){return e.dispose()}),this.dialogs.clear(),this.subscribers.forEach(function(e){return e.dispose()}),this.subscribers.clear(),this.userAgentClients.forEach(function(e){return e.dispose()}),this.userAgentClients.clear(),this.userAgentServers.forEach(function(e){return e.dispose()}),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!1,configurable:!0}),e.prototype.invite=function(e,t){return new Bt(this,e,t)},e.prototype.message=function(e,t){return new Rt(this,e,t)},e.prototype.publish=function(e,t){return new Gt(this,e,t)},e.prototype.register=function(e,t){return new Kt(this,e,t)},e.prototype.subscribe=function(e,t){return new Yt(this,e,t)},e.prototype.request=function(e,t){return new bt(vt,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,n,i,r,o,a){var c=this.configuration.sipjsId,u=this.configuration.displayName,l=this.configuration.viaForceRport,d=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===$e.REGISTER&&h.push("path","gruu"),e===$e.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");var p=this.configuration.routeSet,g=this.configuration.userAgentHeaderFieldValue,f=this.configuration.viaHost,m=s(s({},{callIdPrefix:c,forceRport:l,fromDisplayName:u,hackViaTcp:d,optionTags:h,routeSet:p,userAgentString:g,viaHost:f}),r);return new We(e,t,n,i,m,o,a)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var n=this,i=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=s(s({},t),{userAgent:i,supported:r});var o=tt(e,t);return this.transport.send(o.message).catch(function(t){t instanceof Error&&n.logger.error(t.message),n.logger.error("Transport error occurred sending stateless reply to ".concat(e.method," request."))}),o},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,n=this.userAgentServers.get(t);e.method===$e.ACK&&n&&n.transaction.state===st.Accepted&&n instanceof Vt?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction ".concat(t,".")):e.method!==$e.CANCEL?n?n.transaction.receiveRequest(e):this.receiveRequest(e):n?(this.replyStateless(e,{statusCode:200}),n.transaction instanceof mt&&n.transaction.state===st.Proceeding&&n instanceof Vt&&n.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(Mt.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,n=function(e){return!!e&&e.user===t.user};if(!n(this.configuration.aor)&&!(n(this.configuration.contact.uri)||n(this.configuration.contact.pubGruu)||n(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==$e.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==$e.INVITE||e.hasHeader("Contact")){if(!e.toTag){var i=e.viaBranch;if(!this.userAgentServers.has(i))if(Array.from(this.userAgentServers.values()).some(function(t){return 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"})}else this.replyStateless(e,{statusCode:416})}else{var r="Allow: "+Mt.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[r]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===$e.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var n=e.callId+e.toTag+t.event,i=this.subscribers.get(n);if(i){var r=new At(this,e);return void i.onNotify(r)}}var s=e.callId+e.toTag+e.fromTag,o=this.dialogs.get(s);if(o){if(e.method===$e.OPTIONS){var a="Allow: "+Mt.toString(),c="Accept: "+Zt.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[a,c]})}o.receiveRequest(e)}else e.method!==$e.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case $e.ACK:break;case $e.BYE:this.replyStateless(e,{statusCode:481});break;case $e.CANCEL:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."));case $e.INFO:this.replyStateless(e,{statusCode:405});break;case $e.INVITE:var t=new Vt(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case $e.MESSAGE:t=new kt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case $e.NOTIFY:t=new At(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case $e.OPTIONS:var n="Allow: "+Mt.toString(),i="Accept: "+Zt.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[n,i]});break;case $e.REFER:t=new $t(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case $e.REGISTER:t=new zt(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case $e.SUBSCRIBE:t=new Jt(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."))}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,n=this.userAgentClients.get(t);n?n.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched ".concat(e.statusCode," response to ").concat(e.method," ").concat(t,"."))}},e}(),Xt=function(e){function t(t){return e.call(this,t||"Unsupported content type.")||this}return r(t,e),t}(ut),en=function(e){function t(t){return e.call(this,t||"Request pending.")||this}return r(t,e),t}(ut),tn=function(e){function t(t){return e.call(this,t||"Unspecified session description handler error.")||this}return r(t,e),t}(ut),nn=function(e){function t(){return e.call(this,"The session has terminated.")||this}return r(t,e),t}(ut),rn=function(e){function t(t){return e.call(this,t||"An error occurred during state transition.")||this}return r(t,e),t}(ut),sn=function(){function e(e){this.incomingAckRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingAckRequest.message},enumerable:!1,configurable:!0}),e}(),on=function(){function e(e){this.incomingByeRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingByeRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingByeRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingByeRequest.reject(e),Promise.resolve()},e}(),an=function(){function e(){this.listeners=new Array}return e.prototype.addListener=function(e,t){var n=this,i=function(t){n.removeListener(i),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)},e.prototype.emit=function(e){this.listeners.slice().forEach(function(t){return t(e)})},e.prototype.removeAllListeners=function(){this.listeners=[]},e.prototype.removeListener=function(e){this.listeners=this.listeners.filter(function(t){return t!==e})},e.prototype.on=function(e){return this.addListener(e)},e.prototype.off=function(e){return this.removeListener(e)},e.prototype.once=function(e){return this.addListener(e,{once:!0})},e}(),cn=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}(),un=function(){function e(e){this.incomingMessageRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingMessageRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingMessageRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingMessageRequest.reject(e),Promise.resolve()},e}(),ln=function(){function e(e){this.incomingNotifyRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingNotifyRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()},e}(),dn=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof _e))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){var e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var n=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&n.push("Replaces: "+decodeURIComponent(i));var r=this.referredBy;return r&&n.push("Referred-By: "+r),e.extraHeaders=n,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter},e}();!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(Wt||(Wt={}));var hn,pn=function(){function e(e,t){void 0===t&&(t={}),this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=Wt.Initial,this.delegate=t.delegate,this._stateEventEmitter=new an,this._userAgent=e}return e.prototype.dispose=function(){var e=this;switch(this.logger.log("Session ".concat(this.id," in state ").concat(this._state," is being disposed")),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case Wt.Initial:case Wt.Establishing:break;case Wt.Established:return new Promise(function(t){e._bye({onAccept:function(){return t()},onRedirect:function(){return t()},onReject:function(){return t()}})});case Wt.Terminating:case Wt.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()},Object.defineProperty(e.prototype,"assertedIdentity",{get:function(){return this._assertedIdentity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replacee",{get:function(){return this._replacee},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandler",{get:function(){return this._sessionDescriptionHandler},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerFactory",{get:function(){return this.userAgent.configuration.sessionDescriptionHandlerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiers",{get:function(){return this._sessionDescriptionHandlerModifiers||[]},set:function(e){this._sessionDescriptionHandlerModifiers=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptions",{get:function(){return this._sessionDescriptionHandlerOptions||{}},set:function(e){this._sessionDescriptionHandlerOptions=s({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiersReInvite",{get:function(){return this._sessionDescriptionHandlerModifiersReInvite||[]},set:function(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptionsReInvite",{get:function(){return this._sessionDescriptionHandlerOptionsReInvite||{}},set:function(e){this._sessionDescriptionHandlerOptionsReInvite=s({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgent",{get:function(){return this._userAgent},enumerable:!1,configurable:!0}),e.prototype.bye=function(e){void 0===e&&(e={});var t="Session.bye() may only be called if established session.";switch(this.state){case Wt.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 Wt.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 Wt.Established:var n=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._bye(n,i);case Wt.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 Wt.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 ".concat(this.state)))},e.prototype.info=function(e){if(void 0===e&&(e={}),this.state!==Wt.Established){return this.logger.error("Session.info() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._info(t,n)},e.prototype.invite=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Session.invite"),this.state!==Wt.Established)return Promise.reject(new Error("Invalid session state ".concat(this.state)));if(this.pendingReinvite)return Promise.reject(new en("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);var n={onAccept:function(n){var i=Je(n.message);if(!i)return t.logger.error("Received 2xx response to re-INVITE without a session description"),t.ackAndBye(n,400,"Missing session description"),t.stateTransition(Wt.Terminated),void(t.pendingReinvite=!1);if(e.withoutSdp){var r={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setOfferAndGetAnswer(i,r).then(function(e){n.ack({body:e})}).catch(function(e){t.logger.error("Failed to handle offer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state===Wt.Terminated?n.ack():(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(Wt.Terminated))}).then(function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})}else{r={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setAnswer(i,r).then(function(){n.ack()}).catch(function(e){t.logger.error("Failed to handle answer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state!==Wt.Terminated?(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(Wt.Terminated)):n.ack()}).then(function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})}},onProgress:function(e){},onRedirect:function(e){},onReject:function(n){t.logger.warn("Received a non-2xx response to re-INVITE"),t.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n):t.rollbackOffer().catch(function(e){if(t.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),t.logger.error(e.message),t.state!==Wt.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");var n=[];n.push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(Wt.Terminated)}}).then(function(){e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)})},onTrying:function(e){}},i=e.requestOptions||{};if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.extraHeaders.push("Allow: "+Mt.toString()),i.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(n,i))}var r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(r).then(function(e){if(!t.dialog)throw t.pendingReinvite=!1,new Error("Dialog undefined.");return i.body=e,t.dialog.invite(n,i)}).catch(function(e){throw t.logger.error(e.message),t.logger.error("Failed to send re-INVITE"),t.pendingReinvite=!1,e})},e.prototype.message=function(e){if(void 0===e&&(e={}),this.state!==Wt.Established){return this.logger.error("Session.message() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._message(t,n)},e.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.state!==Wt.Established){return this.logger.error("Session.refer() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var n=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return i.extraHeaders=i.extraHeaders?i.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,n,i)},e.prototype._bye=function(e,t){var n=this;if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));var i=this.dialog;switch(i.sessionState){case nt.Initial:case nt.Early:throw new Error("Invalid dialog state ".concat(i.sessionState));case nt.AckWait:return this.stateTransition(Wt.Terminating),new Promise(function(r){i.delegate={onAck:function(){var s=i.bye(e,t);return n.stateTransition(Wt.Terminated),r(s),Promise.resolve()},onAckTimeout:function(){var s=i.bye(e,t);n.stateTransition(Wt.Terminated),r(s)}}});case nt.Confirmed:var r=i.bye(e,t);return this.stateTransition(Wt.Terminated),Promise.resolve(r);case nt.Terminated:throw new Error("Invalid dialog state ".concat(i.sessionState));default:throw new Error("Unrecognized state.")}},e.prototype._info=function(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._message=function(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._refer=function(e,t,n){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,n))):Promise.reject(new Error("Session dialog undefined."))},e.prototype.ackAndBye=function(e,t,n){e.ack();var i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,n)),e.session.bye(void 0,{extraHeaders:i})},e.prototype.onAckRequest=function(e){var t=this;if(this.logger.log("Session.onAckRequest"),this.state!==Wt.Established&&this.state!==Wt.Terminating)return this.logger.error("ACK received while in state ".concat(this.state,", dropping request")),Promise.resolve();var n=this.dialog;if(!n)throw new Error("Dialog undefined.");var i={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){var r=new sn(e);this.delegate.onAck(r)}switch(this.pendingReinviteAck=!1,n.signalingState){case it.Initial:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));var s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(Wt.Terminated),Promise.resolve();case it.Stable:var o=Je(e.message);return o?"render"===o.contentDisposition?(this._renderbody=o.content,this._rendertype=o.contentType,Promise.resolve()):"session"!==o.contentDisposition?Promise.resolve():this.setAnswer(o,i).catch(function(e){t.logger.error(e.message);var i=["Reason: "+t.getReasonHeaderValue(488,"Bad Media Description")];n.bye(void 0,{extraHeaders:i}),t.stateTransition(Wt.Terminated)}):Promise.resolve();case it.HaveLocalOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(Wt.Terminated),Promise.resolve();case it.HaveRemoteOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(Wt.Terminated),Promise.resolve();case it.Closed:default:throw new Error("Invalid signaling state ".concat(n.signalingState,"."))}},e.prototype.onByeRequest=function(e){if(this.logger.log("Session.onByeRequest"),this.state===Wt.Established){if(this.delegate&&this.delegate.onBye){var t=new on(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(Wt.Terminated)}else this.logger.error("BYE received while in state ".concat(this.state,", dropping request"))},e.prototype.onInfoRequest=function(e){if(this.logger.log("Session.onInfoRequest"),this.state===Wt.Established)if(this.delegate&&this.delegate.onInfo){var t=new cn(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error("INFO received while in state ".concat(this.state,", dropping request"))},e.prototype.onInviteRequest=function(e){var t=this;if(this.logger.log("Session.onInviteRequest"),this.state===Wt.Established){this.pendingReinviteAck=!0;var n=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){var i=e.message.getHeader("P-Asserted-Identity");if(!i)throw new Error("Header undefined.");this._assertedIdentity=He.nameAddrHeaderParse(i)}var r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(r).then(function(i){var r=e.accept({statusCode:200,extraHeaders:n,body:i});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,r.message,200)}).catch(function(i){if(t.logger.error(i.message),t.logger.error("Failed to handle to re-INVITE request"),!t.dialog)throw new Error("Dialog undefined.");if(t.logger.error(t.dialog.signalingState),t.dialog.signalingState!==it.Stable)t.rollbackOffer().then(function(){var n=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,n.message,488)}).catch(function(i){t.logger.error(i.message),t.logger.error("Failed to rollback offer on re-INVITE request");var r=e.reject({statusCode:488});if(t.state!==Wt.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(Wt.Terminated)}t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,r.message,488)});else{var r=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,r.message,488)}})}else this.logger.error("INVITE received while in state ".concat(this.state,", dropping request"))},e.prototype.onMessageRequest=function(e){if(this.logger.log("Session.onMessageRequest"),this.state===Wt.Established)if(this.delegate&&this.delegate.onMessage){var t=new un(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error("MESSAGE received while in state ".concat(this.state,", dropping request"))},e.prototype.onNotifyRequest=function(e){if(this.logger.log("Session.onNotifyRequest"),this.state===Wt.Established)if(this.onNotify){var t=new ln(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){t=new ln(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error("NOTIFY received while in state ".concat(this.state,", dropping request"))},e.prototype.onPrackRequest=function(e){if(this.logger.log("Session.onPrackRequest"),this.state===Wt.Established)throw new Error("Unimplemented.");this.logger.error("PRACK received while in state ".concat(this.state,", dropping request"))},e.prototype.onReferRequest=function(e){var t=this;if(this.logger.log("Session.onReferRequest"),this.state===Wt.Established){if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();var n=new dn(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(n):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),n.accept().then(function(){return n.makeInviter(t._referralInviterOptions).invite()}).catch(function(e){t.logger.error(e.message)}))}else this.logger.error("REFER received while in state ".concat(this.state,", dropping request"))},e.prototype.generateResponseOfferAnswer=function(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);var n=Je(e.message);return n&&"session"===n.contentDisposition?this.setOfferAndGetAnswer(n,t):this.getOffer(t)},e.prototype.generateResponseOfferAnswerInDialog=function(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case it.Initial:return this.getOffer(e);case it.HaveLocalOffer:return Promise.resolve(void 0);case it.HaveRemoteOffer:if(!this.dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this.dialog.signalingState,"."));return this.setOfferAndGetAnswer(this.dialog.offer,e);case it.Stable:return this.state!==Wt.Established?Promise.resolve(void 0):this.getOffer(e);case it.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},e.prototype.getOffer=function(e){var t=this,n=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,r=e.sessionDescriptionHandlerModifiers;try{return n.getDescription(i,r).then(function(e){return ze(e)}).catch(function(e){t.logger.error("Session.getOffer: SDH getDescription rejected...");var n=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw t.logger.error(n.message),n})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");var s=e instanceof Error?e:new Error(e);return this.logger.error(s.message),Promise.reject(s)}},e.prototype.rollbackOffer=function(){var e=this,t=this.setupSessionDescriptionHandler();if(void 0===t.rollbackDescription)return Promise.resolve();try{return t.rollbackDescription().catch(function(t){e.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");var n=t instanceof Error?t:new Error("Session.rollbackOffer unknown error.");throw e.logger.error(n.message),n})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");var n=e instanceof Error?e:new Error(e);return this.logger.error(n.message),Promise.reject(n)}},e.prototype.setAnswer=function(e,t){var n=this,i=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Xt)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,r,s).catch(function(e){n.logger.error("Session.setAnswer: SDH setDescription rejected...");var t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw n.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setOfferAndGetAnswer=function(e,t){var n=this,i=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Xt)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,r,s).then(function(){return i.getDescription(r,s)}).then(function(e){return ze(e)}).catch(function(e){n.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");var t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw n.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setSessionDescriptionHandler=function(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e},e.prototype.setupSessionDescriptionHandler=function(){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},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case Wt.Initial:e!==Wt.Establishing&&e!==Wt.Established&&e!==Wt.Terminating&&e!==Wt.Terminated&&n();break;case Wt.Establishing:e!==Wt.Established&&e!==Wt.Terminating&&e!==Wt.Terminated&&n();break;case Wt.Established:e!==Wt.Terminating&&e!==Wt.Terminated&&n();break;case Wt.Terminating:e!==Wt.Terminated&&n();break;case Wt.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Session ".concat(this.id," transitioned to state ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===Wt.Terminated&&this.dispose()},e.prototype.copyRequestOptions=function(e){return void 0===e&&(e={}),{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}},e.prototype.getReasonHeaderValue=function(e,t){var n=e,i=je(e);return!i&&t&&(i=t),"SIP;cause="+n+';text="'+i+'"'},e.prototype.referExtraHeaders=function(e){var 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},e.prototype.referToString=function(e){var t;if(e instanceof De)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");var n=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,s=e.dialog.remoteTag,o=e.dialog.localTag,a=encodeURIComponent("".concat(r,";to-tag=").concat(s,";from-tag=").concat(o));t='"'.concat(n,'" <').concat(i,"?Replaces=").concat(a,">")}return t},e}();!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(hn||(hn={}));var gn,fn,mn={"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},vn=function(e){function t(t,n){var i=e.call(this,t)||this;i.incomingInviteRequest=n,i.disposed=!1,i.expiresTimer=void 0,i.isCanceled=!1,i.rel100="none",i.rseq=Math.floor(1e4*Math.random()),i.userNoAnswerTimer=void 0,i.waitingForPrack=!1,i.logger=t.getLogger("sip.Invitation");var r=i.incomingInviteRequest.message,s=r.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(i.rel100="required");var o=r.getHeader("supported");if(o&&o.toLowerCase().includes("100rel")&&(i.rel100="supported"),r.toTag=n.toTag,"string"!=typeof r.toTag)throw new TypeError("toTag should have been a string.");if(i.userNoAnswerTimer=setTimeout(function(){n.reject({statusCode:480}),i.stateTransition(Wt.Terminated)},i.userAgent.configuration.noAnswerTimeout?1e3*i.userAgent.configuration.noAnswerTimeout:6e4),r.hasHeader("expires")){var a=1e3*Number(r.getHeader("expires")||0);i.expiresTimer=setTimeout(function(){i.state===Wt.Initial&&(n.reject({statusCode:487}),i.stateTransition(Wt.Terminated))},a)}var c=i.request.getHeader("P-Asserted-Identity");c&&(i._assertedIdentity=He.nameAddrHeaderParse(c)),i._contact=i.userAgent.contact.toString();var u=r.parseHeader("Content-Disposition");return u&&"render"===u.type&&(i._renderbody=r.body,i._rendertype=r.getHeader("Content-Type")),i._id=r.callId+r.fromTag,i.userAgent._sessions[i._id]=i,i}return r(t,e),t.prototype.dispose=function(){var t=this;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 Wt.Initial:case Wt.Establishing:return this.reject().then(function(){return e.prototype.dispose.call(t)});case Wt.Established:case Wt.Terminating:case Wt.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"body",{get:function(){return this.incomingInviteRequest.message.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.request.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.request.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.incomingInviteRequest.message},enumerable:!1,configurable:!0}),t.prototype.accept=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.accept"),this.state!==Wt.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(Wt.Establishing),this.sendAccept(e).then(function(e){e.message;var n=e.session;n.delegate={onAck:function(e){return t.onAckRequest(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},t._dialog=n,t.stateTransition(Wt.Established),t._replacee&&t._replacee._bye()}).catch(function(e){return t.handleResponseError(e)})},t.prototype.progress=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.progress"),this.state!==Wt.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}var i=e.statusCode||180;if(i<100||i>199)throw new TypeError("Invalid statusCode: "+i);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(function(){}).catch(function(e){return t.handleResponseError(e)}):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===hn.Required?this.sendProgressReliableWaitForPrack(e).then(function(){}).catch(function(e){return t.handleResponseError(e)}):this.sendProgress(e).then(function(){}).catch(function(e){return t.handleResponseError(e)})},t.prototype.reject=function(e){if(void 0===e&&(e={}),this.logger.log("Invitation.reject"),this.state!==Wt.Initial&&this.state!==Wt.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}var n=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:je(n),r=e.extraHeaders||[];if(n<300||n>699)throw new TypeError("Invalid statusCode: "+n);var s=e.body?ze(e.body):void 0;return n<400?this.incomingInviteRequest.redirect([],{statusCode:n,reasonPhrase:i,extraHeaders:r,body:s}):this.incomingInviteRequest.reject({statusCode:n,reasonPhrase:i,extraHeaders:r,body:s}),this.stateTransition(Wt.Terminated),Promise.resolve()},t.prototype._onCancel=function(e){this.logger.log("Invitation._onCancel"),this.state===Wt.Initial||this.state===Wt.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(Wt.Terminated)):this.logger.error("CANCEL received while in state ".concat(this.state,", dropping request"))},t.prototype.handlePrackOfferAnswer=function(e){if(!this.dialog)throw new Error("Dialog undefined.");var t=Je(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case it.Initial:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case it.Stable:return this.setAnswer(t,n).then(function(){});case it.HaveLocalOffer:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case it.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,n);case it.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},t.prototype.handleResponseError=function(e){var t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof Xt?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof tn?this.logger.error("A session description handler occurred while sending response"):e instanceof nn?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof lt&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===Wt.Initial||this.state===Wt.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(Wt.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.")},t.prototype.onAckTimeout=function(){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(Wt.Terminated)},t.prototype.sendAccept=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(function(){return clearTimeout(t.userNoAnswerTimer)}).then(function(){return t.generateResponseOfferAnswer(t.incomingInviteRequest,n)}).then(function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})}):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then(function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})}))},t.prototype.sendProgress=function(e){void 0===e&&(e={});var t=e.statusCode||180,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?ze(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{var s=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:n,extraHeaders:i,body:r});return this._dialog=s.session,Promise.resolve(s)}catch(e){return Promise.reject(e)}},t.prototype.sendProgressWithSDP=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,r=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then(function(e){return t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:e})}).then(function(e){return t._dialog=e.session,e})},t.prototype.sendProgressReliable=function(e){return void 0===e&&(e={}),e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)},t.prototype.sendProgressReliableWaitForPrack=function(e){var t=this;void 0===e&&(e={});var n,i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.statusCode||183,s=e.reasonPhrase,o=(e.extraHeaders||[]).slice();return o.push("Require: 100rel"),o.push("RSeq: "+this.rseq++),new Promise(function(e,a){t.waitingForPrack=!0,t.generateResponseOfferAnswer(t.incomingInviteRequest,i).then(function(e){return n=e,t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:s,extraHeaders:o,body:n})}).then(function(i){var c,u;t._dialog=i.session,i.session.delegate={onPrack:function(n){c=n,clearTimeout(l),clearTimeout(p),t.waitingForPrack&&(t.waitingForPrack=!1,t.handlePrackOfferAnswer(c).then(function(n){try{u=c.accept({statusCode:200,body:n}),t.prackArrived(),e({prackRequest:c,prackResponse:u,progressResponse:i})}catch(e){a(e)}}).catch(function(e){return a(e)}))}};var l=setTimeout(function(){t.waitingForPrack&&(t.waitingForPrack=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(p),t.reject({statusCode:504}).then(function(){return a(new nn)}).catch(function(e){return a(e)}))},64*ct.T1),d=function(){try{t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:s,extraHeaders:o,body:n})}catch(e){return t.waitingForPrack=!1,void a(e)}p=setTimeout(d,h*=2)},h=ct.T1,p=setTimeout(d,h)}).catch(function(e){t.waitingForPrack=!1,a(e)})})},t.prototype.sendProgressTrying=function(){try{var e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(function(t,n){e.waitingForPrackResolve=t,e.waitingForPrackReject=n}),this.waitingForPrackPromise},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new nn),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t}(pn),yn=function(e){function t(t,n,i){void 0===i&&(i={});var r=e.call(this,t,i)||this;r.disposed=!1,r.earlyMedia=!1,r.earlyMediaSessionDescriptionHandlers=new Map,r.isCanceled=!1,r.inviteWithoutSdp=!1,r.logger=t.getLogger("sip.Inviter"),r.earlyMedia=void 0!==i.earlyMedia?i.earlyMedia:r.earlyMedia,r.fromTag=Ue(),r.inviteWithoutSdp=void 0!==i.inviteWithoutSdp?i.inviteWithoutSdp:r.inviteWithoutSdp;var o=s({},i);o.params=s({},i.params);var a=i.anonymous||!1,c=t.contact.toString({anonymous:a,outbound:a?!t.contact.tempGruu:!t.contact.pubGruu});a&&t.configuration.uri&&(o.params.fromDisplayName="Anonymous",o.params.fromUri="sip:anonymous@anonymous.invalid");var u=t.userAgentCore.configuration.aor;if(o.params.fromUri&&(u="string"==typeof o.params.fromUri?He.URIParse(o.params.fromUri):o.params.fromUri),!u)throw new TypeError("Invalid from URI: "+o.params.fromUri);var l=n;if(o.params.toUri&&(l="string"==typeof o.params.toUri?He.URIParse(o.params.toUri):o.params.toUri),!l)throw new TypeError("Invalid to URI: "+o.params.toUri);var d=s({},o.params);d.fromTag=r.fromTag;var h=(o.extraHeaders||[]).slice();a&&t.configuration.uri&&(h.push("P-Preferred-Identity: "+t.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+c),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.sipExtension100rel===hn.Required&&h.push("Require: 100rel"),t.configuration.sipExtensionReplaces===hn.Required&&h.push("Require: replaces"),o.extraHeaders=h;return r.outgoingRequestMessage=t.userAgentCore.makeOutgoingRequestMessage($e.INVITE,n,u,l,d,h,undefined),r._contact=c,r._referralInviterOptions=o,r._renderbody=i.renderbody,r._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(r.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(r.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(r.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(r.sessionDescriptionHandlerOptionsReInvite=i.sessionDescriptionHandlerOptionsReInvite),r._id=r.outgoingRequestMessage.callId+r.fromTag,r.userAgent._sessions[r._id]=r,r}return r(t,e),t.prototype.dispose=function(){var t=this;if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case Wt.Initial:case Wt.Establishing:return this.cancel().then(function(){return e.prototype.dispose.call(t)});case Wt.Established:case Wt.Terminating:case Wt.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"body",{get:function(){return this.outgoingRequestMessage.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.outgoingRequestMessage.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.outgoingRequestMessage.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.outgoingRequestMessage},enumerable:!1,configurable:!0}),t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.logger.log("Inviter.cancel"),this.state!==Wt.Initial&&this.state!==Wt.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}if(this.isCanceled=!0,this.stateTransition(Wt.Terminating),this.outgoingInviteRequest){var n=void 0;e.statusCode&&e.reasonPhrase&&(n=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(je(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(n,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(Wt.Terminated);return Promise.resolve()},t.prototype.invite=function(t){var n=this;if(void 0===t&&(t={}),this.logger.log("Inviter.invite"),this.state!==Wt.Initial)return e.prototype.invite.call(this,t);if(t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),t.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(Wt.Establishing),Promise.resolve(this.sendInvite(t));var i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(i).then(function(e){return n.outgoingRequestMessage.body={body:e.content,contentType:e.contentType},n.stateTransition(Wt.Establishing),n.sendInvite(t)}).catch(function(e){throw n.logger.log(e.message),n.stateTransition(Wt.Terminated),e})},t.prototype.sendInvite=function(e){var t=this;return void 0===e&&(e={}),this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:function(n){return t.dialog?(t.logger.log("Additional confirmed dialog, sending ACK and BYE"),void t.ackAndBye(n)):t.isCanceled?(t.logger.log("Canceled session accepted, sending ACK and BYE"),t.ackAndBye(n),void t.stateTransition(Wt.Terminated)):(t.notifyReferer(n),void t.onAccept(n).then(function(){t.disposeEarlyMedia()}).catch(function(){t.disposeEarlyMedia()}).then(function(){e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)}))},onProgress:function(n){t.isCanceled||(t.notifyReferer(n),t.onProgress(n).catch(function(){t.disposeEarlyMedia()}).then(function(){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(n)}))},onRedirect:function(n){t.notifyReferer(n),t.onRedirect(n),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n)},onReject:function(n){t.notifyReferer(n),t.onReject(n),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)},onTrying:function(n){t.notifyReferer(n),t.onTrying(n),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(n)}}),this.outgoingInviteRequest},t.prototype.disposeEarlyMedia=function(){this.earlyMediaSessionDescriptionHandlers.forEach(function(e){e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()},t.prototype.notifyReferer=function(e){var t=this;if(this._referred){if(!(this._referred instanceof pn))throw new Error("Referred session not instance of session");if(this._referred.dialog){if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");var n=e.message.statusCode,i=e.message.reasonPhrase,r="SIP/2.0 ".concat(n," ").concat(i).trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:r}}).delegate={onReject:function(){t._referred=void 0}}}}},t.prototype.onAccept=function(e){var t=this;if(this.logger.log("Inviter.onAccept"),this.state!==Wt.Establishing)return this.logger.error("Accept received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));var n=e.message,i=e.session;switch(n.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=He.nameAddrHeaderParse(n.getHeader("P-Asserted-Identity"))),i.delegate={onAck:function(e){return t.onAckRequest(e)},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},this._dialog=i,i.signalingState){case it.Initial:case it.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(Wt.Terminated),Promise.reject(new Error("Bad Media Description"));case it.HaveRemoteOffer:if(!this._dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this._dialog.signalingState,"."));var r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,r).then(function(n){e.ack({body:n}),t.stateTransition(Wt.Established)}).catch(function(n){throw t.ackAndBye(e,488,"Invalid session description"),t.stateTransition(Wt.Terminated),n});case it.Stable:if(this.earlyMediaSessionDescriptionHandlers.size>0){var s=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!s)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(s),this.earlyMediaSessionDescriptionHandlers.delete(i.id),e.ack(),this.stateTransition(Wt.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){if(this.earlyMedia){this.logger.error("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.")}var o=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(o.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(Wt.Terminated),Promise.reject(o)}return e.ack(),this.stateTransition(Wt.Established),Promise.resolve()}var a=i.answer;if(!a)throw new Error("Answer is undefined.");r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(a,r).then(function(){var n;t._renderbody&&t._rendertype&&(n={body:{contentDisposition:"render",contentType:t._rendertype,content:t._renderbody}}),e.ack(n),t.stateTransition(Wt.Established)}).catch(function(n){throw t.logger.error(n.message),t.ackAndBye(e,488,"Not Acceptable Here"),t.stateTransition(Wt.Terminated),n});case it.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onProgress=function(e){var t,n=this;if(this.logger.log("Inviter.onProgress"),this.state!==Wt.Establishing)return this.logger.error("Progress received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");var i=e.message,r=e.session;i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=He.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity")));var s=i.getHeader("require"),o=i.getHeader("rseq"),a=!!(s&&s.includes("100rel")&&o?Number(o):void 0),c=[];switch(a&&c.push("RAck: "+i.getHeader("rseq")+" "+i.getHeader("cseq")),r.signalingState){case it.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:c})),Promise.resolve();case it.HaveLocalOffer:return a&&e.prack({extraHeaders:c}),Promise.resolve();case it.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();var u=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(u,!0),this.earlyMediaSessionDescriptionHandlers.set(r.id,u),u.setDescription(i.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(function(){return u.getDescription(n.sessionDescriptionHandlerOptions,n.sessionDescriptionHandlerModifiers)}).then(function(t){var n={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:c,body:n})}).catch(function(e){throw n.stateTransition(Wt.Terminated),e});case it.Stable:if(a&&e.prack({extraHeaders:c}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=r;var l=r.answer;if(!l)throw new Error("Answer is undefined.");var d={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(l,d).catch(function(e){throw n.stateTransition(Wt.Terminated),e})}return Promise.resolve();case it.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onRedirect=function(e){this.logger.log("Inviter.onRedirect"),this.state===Wt.Establishing||this.state===Wt.Terminating?this.stateTransition(Wt.Terminated):this.logger.error("Redirect received while in state ".concat(this.state,", dropping response"))},t.prototype.onReject=function(e){this.logger.log("Inviter.onReject"),this.state===Wt.Establishing||this.state===Wt.Terminating?this.stateTransition(Wt.Terminated):this.logger.error("Reject received while in state ".concat(this.state,", dropping response"))},t.prototype.onTrying=function(e){this.logger.log("Inviter.onTrying"),this.state===Wt.Establishing||this.logger.error("Trying received while in state ".concat(this.state,", dropping response"))},t}(pn),bn=function(){function e(e,t,n,i,r){void 0===i&&(i="text/plain"),void 0===r&&(r={}),this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};var o=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(o="string"==typeof r.params.fromUri?He.URIParse(r.params.fromUri):r.params.fromUri),!o)throw new TypeError("Invalid from URI: "+r.params.fromUri);var a=t;if(r.params.toUri&&(a="string"==typeof r.params.toUri?He.URIParse(r.params.toUri):r.params.toUri),!a)throw new TypeError("Invalid to URI: "+r.params.toUri);var c=r.params?s({},r.params):{},u=(r.extraHeaders||[]).slice(),l={contentDisposition:"render",contentType:i,content:n};this.request=e.userAgentCore.makeOutgoingRequestMessage($e.MESSAGE,t,o,a,c,u,l),this.userAgent=e}return e.prototype.message=function(e){return void 0===e&&(e={}),this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()},e}();!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(gn||(gn={})),function(){function e(e,t,n,i){void 0===i&&(i={}),this.disposed=!1,this._state=gn.Initial,this._stateEventEmitter=new an,this.userAgent=e,i.extraHeaders=(i.extraHeaders||[]).slice(),i.contentType=i.contentType||"text/plain","number"!=typeof i.expires||i.expires%1!=0?i.expires=3600:i.expires=Number(i.expires),"boolean"!=typeof i.unpublishOnClose&&(i.unpublishOnClose=!0),this.target=t,this.event=n,this.options=i,this.pubRequestExpires=i.expires,this.logger=e.getLogger("sip.Publisher");var r,s=i.params||{},o=s.fromUri?s.fromUri:e.userAgentCore.configuration.aor,a=s.toUri?s.toUri:t;if(i.body&&i.contentType){r={contentDisposition:"render",contentType:i.contentType,content:i.body}}var c=(i.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage($e.PUBLISH,t,o,a,s,c,r),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}e.prototype.dispose=function(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Publisher ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===gn.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()))},Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.publish=function(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()},e.prototype.unpublish=function(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()},e.prototype.receiveResponse=function(e){var t=this,n=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(n.toString()):break;case/^2[0-9]{2}$/.test(n.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")){var i=Number(e.getHeader("Expires"));"number"==typeof i&&i>=0&&i<=this.pubRequestExpires?this.pubRequestExpires=i: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(function(){return t.refreshRequest()},900*this.pubRequestExpires),this._state!==gn.Published&&this.stateTransition(gn.Published)):this.stateTransition(gn.Unpublished);break;case/^412$/.test(n.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(gn.Unpublished),this.stateTransition(gn.Terminated);break;case/^423$/.test(n.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var r=Number(e.getHeader("Min-Expires"));if("number"==typeof r||r>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=r,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(gn.Unpublished),this.stateTransition(gn.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(gn.Unpublished),this.stateTransition(gn.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(gn.Unpublished),this.stateTransition(gn.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},e.prototype.send=function(){var e=this;return this.userAgent.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}})},e.prototype.refreshRequest=function(){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()},e.prototype.sendPublishRequest=function(){var e=s({},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);var t,n,i=this.target,r=this.options.params||{};if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");t={body:this.pubRequestBody,contentType:this.options.contentType}}return t&&(n=ze(t)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage($e.PUBLISH,i,r.fromUri?r.fromUri:this.userAgent.userAgentCore.configuration.aor,r.toUri?r.toUri:this.target,r,e.extraHeaders,n),this.send()},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case gn.Initial:e!==gn.Published&&e!==gn.Unpublished&&e!==gn.Terminated&&n();break;case gn.Published:e!==gn.Unpublished&&e!==gn.Terminated&&n();break;case gn.Unpublished:e!==gn.Published&&e!==gn.Terminated&&n();break;case gn.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===gn.Terminated&&this.dispose()}}(),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(fn||(fn={}));var wn,Tn=function(){function e(t,n){void 0===n&&(n={});var i=this;this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=fn.Initial,this._waiting=!1,this._stateEventEmitter=new an,this._waitingEventEmitter=new an,this.userAgent=t;var r=t.configuration.uri.clone();if(r.user=void 0,this.options=s(s(s({},e.defaultOptions()),{registrar:r}),e.stripUndefinedProperties(n)),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=e.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===He.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");var o=this.options.registrar,a=this.options.params&&this.options.params.fromUri||t.userAgentCore.configuration.aor,c=this.options.params&&this.options.params.toUri||t.configuration.uri,u=this.options.params||{},l=(n.extraHeaders||[]).slice();if(this.request=t.userAgentCore.makeOutgoingRequestMessage($e.REGISTER,o,a,c,u,l,void 0),this.expires=this.options.expires||e.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||e.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=t.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(function(e){var t=i.options[e];if("registrar"===e)i.logger.log("· "+e+": "+t);else i.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}return e.defaultOptions=function(){return{expires:e.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new De("sip","anonymous","anonymous.invalid"),refreshFrequency:e.defaultRefreshFrequency}},e.newUUID=function(){var e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce(function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t},{})},Object.defineProperty(e.prototype,"contacts",{get:function(){return this._contacts.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"retryAfter",{get:function(){return this._retryAfter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){var e=this;return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Registerer ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._registerers[this.id],new Promise(function(t){var n=function(){if(!e.waiting&&e._state===fn.Registered)return e.stateChange.addListener(function(){e.terminated(),t()},{once:!0}),void e.unregister();e.terminated(),t()};e.waiting?e.waitingChange.addListener(function(){n()},{once:!0}):n()}))},e.prototype.register=function(e){var t=this;if(void 0===e&&(e={}),this.state===fn.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();var n=new en("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}e.requestOptions&&(this.options=s(s({},this.options),e.requestOptions));var i=(this.options.extraHeaders||[]).slice();i.push("Contact: "+this.generateContactHeader(this.expires)),i.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=i,this.waitingToggle(!0);var r=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){var i;n.message.hasHeader("expires")&&(i=Number(n.message.getHeader("expires"))),t._contacts=n.message.getHeaders("contact");var r,s,o=t._contacts.length;if(!o)return t.logger.error("No Contact header in response to REGISTER, dropping response."),void t.unregistered();for(;o--;){if(!(r=n.message.parseHeader("contact",o)))throw new Error("Contact undefined");if(t.userAgent.contact.pubGruu&&qe(r.uri,t.userAgent.contact.pubGruu)){i=Number(r.getParam("expires"));break}if(""===t.userAgent.configuration.contactName){if(r.uri.user===t.userAgent.contact.uri.user){i=Number(r.getParam("expires"));break}}else if(qe(r.uri,t.userAgent.contact.uri)){i=Number(r.getParam("expires"));break}r=void 0}if(void 0===r)return t.logger.error("No Contact header pointing to us, dropping response"),t.unregistered(),void t.waitingToggle(!1);if(void 0===i)return t.logger.error("Contact pointing to us is missing expires parameter, dropping response"),t.unregistered(),void t.waitingToggle(!1);r.hasParam("temp-gruu")&&((s=r.getParam("temp-gruu"))&&(t.userAgent.contact.tempGruu=He.URIParse(s.replace(/"/g,""))));r.hasParam("pub-gruu")&&((s=r.getParam("pub-gruu"))&&(t.userAgent.contact.pubGruu=He.URIParse(s.replace(/"/g,""))));t.registered(i),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Redirect received. Not supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){if(423===n.message.statusCode)return n.message.hasHeader("min-expires")?(t.expires=Number(n.message.getHeader("min-expires")),t.waitingToggle(!1),void t.register()):(t.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),t.unregistered(),void t.waitingToggle(!1));t.logger.warn("Failed to register, status code ".concat(n.message.statusCode));var i=NaN;if(500===n.message.statusCode||503===n.message.statusCode){var r=n.message.getHeader("retry-after");r&&(i=Number.parseInt(r,void 0))}t._retryAfter=isNaN(i)?void 0:i,t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t._retryAfter=void 0,t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(r)},e.prototype.unregister=function(e){var t=this;if(void 0===e&&(e={}),this.state===fn.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==fn.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();var n=new en("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}this._state===fn.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");var i=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=i,e.all?(i.push("Contact: *"),i.push("Expires: 0")):i.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);var r=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){t._contacts=n.message.getHeaders("contact"),t.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Unregister redirected. Not currently supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){t.logger.error("Unregister rejected with status code ".concat(n.message.statusCode)),t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(r)},e.prototype.clearTimers=function(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)},e.prototype.generateContactHeader=function(e){var t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(function(e){t+=";"+e}),t+=";expires="+e},e.prototype.registered=function(e){var t=this;this.clearTimers(),this.registrationTimer=setTimeout(function(){t.registrationTimer=void 0,t.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(function(){t.logger.warn("Registration expired"),t.unregistered()},1e3*e),this._state!==fn.Registered&&this.stateTransition(fn.Registered)},e.prototype.unregistered=function(){this.clearTimers(),this._state!==fn.Unregistered&&this.stateTransition(fn.Unregistered)},e.prototype.terminated=function(){this.clearTimers(),this._state!==fn.Terminated&&this.stateTransition(fn.Terminated)},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case fn.Initial:e!==fn.Registered&&e!==fn.Unregistered&&e!==fn.Terminated&&n();break;case fn.Registered:e!==fn.Unregistered&&e!==fn.Terminated&&n();break;case fn.Unregistered:e!==fn.Registered&&e!==fn.Terminated&&n();break;case fn.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===fn.Terminated&&this.dispose()},Object.defineProperty(e.prototype,"waiting",{get:function(){return this._waiting},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"waitingChange",{get:function(){return this._waitingEventEmitter},enumerable:!1,configurable:!0}),e.prototype.waitingToggle=function(e){if(this._waiting===e)throw new Error("Invalid waiting transition from ".concat(this._waiting," to ").concat(e));this._waiting=e,this.logger.log("Waiting toggled to ".concat(this._waiting)),this._waitingEventEmitter.emit(this._waiting)},e.prototype.waitingWarning=function(){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.")},e.prototype.stateError=function(){var e=this.state===fn.Terminated?"is in 'Terminated' state":"has been disposed",t="An attempt was made to send a REGISTER request when the Registerer ".concat(e,".");t+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",t+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(t)},e.defaultExpires=600,e.defaultRefreshFrequency=99,e}();!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(wn||(wn={})),function(e){function t(t,n,i,r){void 0===r&&(r={});var s=e.call(this,t,r)||this;return s.body=void 0,s.logger=t.getLogger("sip.Subscriber"),r.body&&(s.body={body:r.body,contentType:r.contentType?r.contentType:"application/sdp"}),s.targetURI=n,s.event=i,void 0===r.expires?s.expires=3600:"number"!=typeof r.expires?(s.logger.warn('Option "expires" must be a number. Using default of 3600.'),s.expires=3600):s.expires=r.expires,s.extraHeaders=(r.extraHeaders||[]).slice(),s.subscriberRequest=s.initSubscriberRequest(),s.outgoingRequestMessage=s.subscriberRequest.message,s.id=s.outgoingRequestMessage.callId+s.outgoingRequestMessage.from.parameters.tag+s.event,s._userAgent._subscriptions[s.id]=s,s}r(t,e),t.prototype.dispose=function(){var t=this;return this.disposed?Promise.resolve():(this.logger.log("Subscription ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),e.prototype.dispose.call(this).then(function(){if(t.state===wn.Subscribed){if(!t._dialog)throw new Error("Dialog undefined.");if(t._dialog.subscriptionState===Ht.Pending||t._dialog.subscriptionState===Ht.Active){var e=t._dialog;return new Promise(function(t,n){e.delegate={onTerminated:function(){return t()}},e.unsubscribe()})}}}))},t.prototype.subscribe=function(e){var t=this;switch(this.subscriberRequest.state){case Ht.Initial:this.state===wn.Initial&&this.stateTransition(wn.NotifyWait),this.subscriberRequest.subscribe().then(function(e){e.success?(e.success.subscription&&(t._dialog=e.success.subscription,t._dialog.delegate={onNotify:function(e){return t.onNotify(e)},onRefresh:function(e){return t.onRefresh(e)},onTerminated:function(){t.state!==wn.Terminated&&t.stateTransition(wn.Terminated)}}),t.onNotify(e.success.request)):e.failure&&t.unsubscribe()});break;case Ht.NotifyWait:case Ht.Pending:break;case Ht.Active:if(this._dialog)this._dialog.refresh().delegate={onAccept:function(e){return t.onAccepted(e)},onRedirect:function(e){return t.unsubscribe()},onReject:function(e){return t.unsubscribe()}};case Ht.Terminated:}return Promise.resolve()},t.prototype.unsubscribe=function(e){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case Ht.Initial:case Ht.NotifyWait:break;case Ht.Pending:case Ht.Active:this._dialog&&this._dialog.unsubscribe();break;case Ht.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(wn.Terminated),Promise.resolve()},t.prototype._refresh=function(){return this.subscriberRequest.state===Ht.Active?this.subscribe():Promise.resolve()},t.prototype.onAccepted=function(e){},t.prototype.onNotify=function(e){var t=this;if(this.disposed)e.accept();else{if(this.state!==wn.Subscribed&&this.stateTransition(wn.Subscribed),this.delegate&&this.delegate.onNotify){var n=new ln(e);this.delegate.onNotify(n)}else e.accept();var i=e.message.parseHeader("Subscription-State");if(i&&i.state&&"terminated"===i.state){if(i.reason)switch(this.logger.log("Terminated subscription with reason ".concat(i.reason)),i.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(i.params&&i.params["retry-after"]?this.retryAfterTimer=setTimeout(function(){t.subscribe()},i.params["retry-after"]):this.subscribe())}this.unsubscribe()}}},t.prototype.onRefresh=function(e){var t=this;e.delegate={onAccept:function(e){return t.onAccepted(e)}}},t.prototype.initSubscriberRequest=function(){var e=this,t={extraHeaders:this.extraHeaders,body:this.body?ze(this.body):void 0};return this.subscriberRequest=new En(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,t),this.subscriberRequest.delegate={onAccept:function(t){return e.onAccepted(t)}},this.subscriberRequest}}(function(){function e(e,t){void 0===t&&(t={}),this._disposed=!1,this._state=wn.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new an,this._userAgent=e,this.delegate=t.delegate}return e.prototype.dispose=function(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()},Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disposed",{get:function(){return this._disposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case wn.Initial:e!==wn.NotifyWait&&e!==wn.Terminated&&n();break;case wn.NotifyWait:e!==wn.Subscribed&&e!==wn.Terminated&&n();break;case wn.Subscribed:e!==wn.Terminated&&n();break;case wn.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log("Subscription ".concat(this._dialog?this._dialog.id:void 0," transitioned to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===wn.Terminated&&this.dispose())},e}());var Sn,In,En=function(){function e(e,t,n,i,r,s){this.core=e,this.target=t,this.event=n,this.expires=i,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=s;var o="Allow: "+Mt.toString(),a=(r&&r.extraHeaders||[]).slice();a.push(o),a.push("Event: "+this.event),a.push("Expires: "+this.expires),a.push("Contact: "+this.core.configuration.contact.toString());var c=r&&r.body;this.message=e.makeOutgoingRequestMessage($e.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},a,c)}return e.prototype.dispose=function(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)},Object.defineProperty(e.prototype,"state",{get:function(){return this.subscription?this.subscription.subscriptionState:this.subscribed?Ht.NotifyWait:Ht.Initial},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(){var e=this;return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(function(t){if(!e.message)throw new Error("Message undefined.");e.request=e.core.subscribe(e.message,{onAccept:function(t){e.delegate&&e.delegate.onAccept&&e.delegate.onAccept(t)},onNotify:function(n){e.subscription=n.subscription,e.subscription&&(e.subscription.autoRefresh=!0),t({success:n})},onNotifyTimeout:function(){t({failure:{}})},onRedirect:function(e){t({failure:{response:e}})},onReject:function(e){t({failure:{response:e}})}})}))},e}();!function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(Sn||(Sn={})),function(e){e.Started="Started",e.Stopped="Stopped"}(In||(In={}));var Rn=function(){function e(e,t,n){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=n,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==n?void 0:n.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}return Object.defineProperty(e.prototype,"localMediaStream",{get:function(){return this._localMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){return this._remoteMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dataChannel},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnection",{get:function(){return this._peerConnection},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnectionDelegate",{get:function(){return this._peerConnectionDelegate},set:function(e){this._peerConnectionDelegate=e},enumerable:!1,configurable:!0}),e.dispatchAddTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))},e.dispatchRemoveTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))},e.prototype.close=function(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(function(e){e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)},e.prototype.getDescription=function(e,t){var n,i,r=this;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;var s=null===(n=null==e?void 0:e.offerOptions)||void 0===n?void 0:n.iceRestart,o=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(function(){return r.updateDirection(e)}).then(function(){return r.createDataChannel(e)}).then(function(){return r.createLocalOfferOrAnswer(e)}).then(function(e){return r.applyModifiers(e,t)}).then(function(e){return r.setLocalSessionDescription(e)}).then(function(){return r.waitForIceGatheringComplete(s,o)}).then(function(){return r.getLocalSessionDescription()}).then(function(e){return{body:e.sdp,contentType:"application/sdp"}}).catch(function(e){throw r.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})},e.prototype.hasDescription=function(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e},e.prototype.sendDtmf=function(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;var n=this._peerConnection.getSenders();if(0===n.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;var i=n[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;var r=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,s)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0},e.prototype.setDescription=function(e,t,n){var i=this;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;var r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(function(){return i.applyModifiers({sdp:e,type:r},n)}).then(function(e){return i.setRemoteSessionDescription(e)}).catch(function(e){throw i.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})},e.prototype.applyModifiers=function(e,t){var n=this;return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce(function(e,t){return e.then(t)},Promise.resolve(e)).then(function(e){if(n.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)},e.prototype.createDataChannel=function(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();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.createLocalOfferOrAnswer=function(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);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.getLocalMediaStream=function(e){var t=this;if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var n=s({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(n.audio=n.audio||this.localMediaStreamConstraints.audio,n.video=n.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(n.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(n.video))return Promise.resolve()}else void 0===n.audio&&void 0===n.video&&(n={audio:!0});return this.localMediaStreamConstraints=n,this.mediaStreamFactory(n,this).then(function(e){return t.setLocalMediaStream(e)})},e.prototype.setLocalMediaStream=function(t){var n=this;if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");var i=this._peerConnection,r=this._localMediaStream,s=[],o=function(t){var o=t.kind;if("audio"!==o&&"video"!==o)throw new Error("Unknown new track kind ".concat(o,"."));var a=i.getSenders().find(function(e){return e.track&&e.track.kind===o});a?s.push(new Promise(function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - replacing sender ".concat(o," track")),e()}).then(function(){return a.replaceTrack(t).then(function(){var n=r.getTracks().find(function(e){return e.kind===o});n&&(n.stop(),r.removeTrack(n),e.dispatchRemoveTrackEvent(r,n)),r.addTrack(t),e.dispatchAddTrackEvent(r,t)}).catch(function(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ".concat(o," track")),e})})):s.push(new Promise(function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - adding sender ".concat(o," track")),e()}).then(function(){try{i.addTrack(t,r)}catch(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to add sender ".concat(o," track")),e}r.addTrack(t),e.dispatchAddTrackEvent(r,t)}))},a=t.getAudioTracks();a.length&&o(a[0]);var c=t.getVideoTracks();return c.length&&o(c[0]),s.reduce(function(e,t){return e.then(function(){return t})},Promise.resolve())},e.prototype.getLocalSessionDescription=function(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))},e.prototype.setLocalSessionDescription=function(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)},e.prototype.setRemoteSessionDescription=function(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var t,n=e.sdp;switch(this._peerConnection.signalingState){case"stable":t="offer";break;case"have-local-offer":t="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return n?this._peerConnection.setRemoteDescription({sdp:n,type:t}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))},e.prototype.setRemoteTrack=function(t){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");var n=this._remoteMediaStream;n.getTrackById(t.id)?this.logger.debug("SessionDescriptionHandler.setRemoteTrack - have remote ".concat(t.kind," track")):"audio"===t.kind?(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getAudioTracks().forEach(function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)}),n.addTrack(t),e.dispatchAddTrackEvent(n,t)):"video"===t.kind&&(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getVideoTracks().forEach(function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)}),n.addTrack(t),e.dispatchAddTrackEvent(n,t))},e.prototype.updateDirection=function(e){var t=this;if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");this._peerConnection.getTransceivers().forEach(function(t){if(t.direction){var n=function(t){switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}}(t.direction);t.direction!==n&&(t.direction=n)}});break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");var n=function(){var e=t._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");var n=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(n)switch(n[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"}(),i=function(){switch(n){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}}();this._peerConnection.getTransceivers().forEach(function(e){e.direction&&"stopped"!==e.direction&&e.direction!==i&&(e.direction=i)});break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()},e.prototype.iceGatheringComplete=function(){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)},e.prototype.waitForIceGatheringComplete=function(e,t){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=0),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(function(e,i){n.iceGatheringCompleteResolve=e,n.iceGatheringCompleteReject=i,t>0&&(n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),n.iceGatheringCompleteTimeoutId=setTimeout(function(){n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),n.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())},e.prototype.initPeerConnectionEventHandlers=function(){var e=this;if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");var t=this._peerConnection;t.onconnectionstatechange=function(n){var i,r=t.connectionState;e.logger.debug("SessionDescriptionHandler.onconnectionstatechange ".concat(r)),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.onconnectionstatechange)&&e._peerConnectionDelegate.onconnectionstatechange(n)},t.ondatachannel=function(t){var n;e.logger.debug("SessionDescriptionHandler.ondatachannel"),e._dataChannel=t.channel,e.onDataChannel&&e.onDataChannel(e._dataChannel),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ondatachannel)&&e._peerConnectionDelegate.ondatachannel(t)},t.onicecandidate=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidate)&&e._peerConnectionDelegate.onicecandidate(t)},t.onicecandidateerror=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidateerror)&&e._peerConnectionDelegate.onicecandidateerror(t)},t.oniceconnectionstatechange=function(n){var i,r=t.iceConnectionState;e.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange ".concat(r)),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.oniceconnectionstatechange)&&e._peerConnectionDelegate.oniceconnectionstatechange(n)},t.onicegatheringstatechange=function(n){var i,r=t.iceGatheringState;e.logger.debug("SessionDescriptionHandler.onicegatheringstatechange ".concat(r)),"complete"===r&&e.iceGatheringComplete(),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.onicegatheringstatechange)&&e._peerConnectionDelegate.onicegatheringstatechange(n)},t.onnegotiationneeded=function(t){var n;e.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onnegotiationneeded)&&e._peerConnectionDelegate.onnegotiationneeded(t)},t.onsignalingstatechange=function(n){var i,r=t.signalingState;e.logger.debug("SessionDescriptionHandler.onsignalingstatechange ".concat(r)),(null===(i=e._peerConnectionDelegate)||void 0===i?void 0:i.onsignalingstatechange)&&e._peerConnectionDelegate.onsignalingstatechange(n)},t.onstatsended=function(t){var n;e.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onstatsended)&&e._peerConnectionDelegate.onstatsended(t)},t.ontrack=function(t){var n,i=t.track.kind,r=t.track.enabled?"enabled":"disabled";e.logger.debug("SessionDescriptionHandler.ontrack ".concat(i," ").concat(r)),e.setRemoteTrack(t.track),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ontrack)&&e._peerConnectionDelegate.ontrack(t)}},e}();function kn(e){return function(t,n){void 0===e&&(e=function(e){return 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)});var i={iceGatheringTimeout:void 0!==(null==n?void 0:n.iceGatheringTimeout)?null==n?void 0:n.iceGatheringTimeout:5e3,peerConnectionConfiguration:s(s({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}),null==n?void 0:n.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new Rn(r,e,i)}}var Cn=function(){function e(t,n){if(this._state=Sn.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new an,this.logger=t,n){var i=n,r=null==i?void 0:i.wsServers,o=null==i?void 0:i.maxReconnectionAttempts;if(void 0!==r){var a='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(a)}if(void 0!==o){a='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(a)}r&&!n.server&&("string"==typeof r&&(n.server=r),r instanceof Array&&(n.server=r[0]))}this.configuration=s(s({},e.defaultOptions),n);var c=this.configuration.server,u=He.parse(c,"absoluteURI");if(-1===u)throw this.logger.error('Invalid WebSocket Server URL "'.concat(c,'"')),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(u.scheme))throw this.logger.error('Invalid scheme in WebSocket Server URL "'.concat(c,'"')),new Error("Invalid scheme in WebSocket Server URL");this._protocol=u.scheme.toUpperCase()}return e.prototype.dispose=function(){return this.disconnect()},Object.defineProperty(e.prototype,"protocol",{get:function(){return this._protocol},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"server",{get:function(){return this.configuration.server},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ws",{get:function(){return this._ws},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this._connect()},e.prototype.disconnect=function(){return this._disconnect()},e.prototype.isConnected=function(){return this.state===Sn.Connected},e.prototype.send=function(e){return this._send(e)},e.prototype._connect=function(){var e,t=this;switch(this.logger.log("Connecting ".concat(this.server)),this.state){case Sn.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case Sn.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case Sn.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Sn.Connecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;case Sn.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Sn.Connecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}try{(e=new WebSocket(this.server,"sip")).binaryType="arraybuffer",e.addEventListener("close",function(n){return t.onWebSocketClose(n,e)}),e.addEventListener("error",function(n){return t.onWebSocketError(n,e)}),e.addEventListener("open",function(n){return t.onWebSocketOpen(n,e)}),e.addEventListener("message",function(n){return t.onWebSocketMessage(n,e)}),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise(function(n,i){t.connectResolve=n,t.connectReject=i,t.transitionState(Sn.Disconnected,e)})}return this.connectPromise=new Promise(function(n,i){t.connectResolve=n,t.connectReject=i,t.connectTimeout=setTimeout(function(){t.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*t.configuration.connectionTimeout)}),this.connectPromise},e.prototype._disconnect=function(){var e=this;switch(this.logger.log("Disconnecting ".concat(this.server)),this.state){case Sn.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Sn.Disconnecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;case Sn.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Sn.Disconnecting)}catch(e){if(e instanceof rn)return Promise.reject(e);throw e}break;case Sn.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case Sn.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Sn.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.");var t=this._ws;return this.disconnectPromise=new Promise(function(n,i){e.disconnectResolve=n,e.disconnectReject=i;try{t.close(1e3)}catch(t){throw e.logger.error("WebSocket close failed."),e.logger.error(t),t}}),this.disconnectPromise},e.prototype._send=function(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==Sn.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()},e.prototype.onWebSocketClose=function(e,t){if(t===this._ws){var n="WebSocket closed ".concat(this.server," (code: ").concat(e.code,")"),i=this.disconnectPromise?void 0:new Error(n);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(n),this._ws=void 0,this.transitionState(Sn.Disconnected,i)}},e.prototype.onWebSocketError=function(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")},e.prototype.onWebSocketMessage=function(e,t){if(t===this._ws){var n,i=e.data;if(/^(\r\n)+$/.test(i))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(i){if("string"!=typeof i){try{n=(new TextDecoder).decode(new Uint8Array(i))}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"+n+"\n")}else n=i,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===Sn.Connected){if(this.onMessage)try{this.onMessage(n)}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...")}},e.prototype.onWebSocketOpen=function(e,t){t===this._ws&&this._state===Sn.Connecting&&(this.logger.log("WebSocket opened ".concat(this.server)),this.transitionState(Sn.Connected))},e.prototype.transitionLoopDetectedError=function(e){var t="A state transition loop has been detected.";return t+=" An attempt to transition from ".concat(this._state," to ").concat(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 rn("Loop detected.")},e.prototype.transitionState=function(e,t){var n=this,i=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case Sn.Connecting:e!==Sn.Connected&&e!==Sn.Disconnecting&&e!==Sn.Disconnected&&i();break;case Sn.Connected:e!==Sn.Disconnecting&&e!==Sn.Disconnected&&i();break;case Sn.Disconnecting:e!==Sn.Connecting&&e!==Sn.Disconnected&&i();break;case Sn.Disconnected:e!==Sn.Connecting&&i();break;default:throw new Error("Unknown state.")}var r=this._state;this._state=e;var s=this.connectResolve,o=this.connectReject;r===Sn.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);var a=this.disconnectResolve,c=this.disconnectReject;if(r===Sn.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 ".concat(r," to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===Sn.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===Sn.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===Sn.Connecting){if(!s)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===Sn.Connected?s():o(t||new Error("Connect aborted."))}if(r===Sn.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!c)throw new Error("Disconnect reject undefined.");e===Sn.Disconnected?a():c(t||new Error("Disconnect aborted."))}this.transitioningState=!1},e.prototype.clearKeepAliveTimeout=function(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0},e.prototype.sendKeepAlive=function(){var e=this;return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(function(){e.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))},e.prototype.startSendingKeepAlives=function(){var e,t,n=this;this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(function(){n.sendKeepAlive(),n.startSendingKeepAlives()},(e=this.configuration.keepAliveInterval,t=.8*e,1e3*(Math.random()*(e-t)+t))))},e.prototype.stopSendingKeepAlives=function(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0},e.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0},e}(),An=function(){function e(t){void 0===t&&(t={});var n=this;if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=In.Stopped,this.unloadListener=function(){n.stop()},this._stateEventEmitter=new an,this.delegate=t.delegate,this.options=s(s(s(s(s({},e.defaultOptions()),{sipjsId:Me(5)}),{uri:new De("sip","anonymous."+Me(6),"anonymous.invalid")}),{viaHost:Me(12)+".invalid"}),e.stripUndefinedProperties(t)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){var i=Math.floor(254*Math.random()+1);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Lt,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=Nt.error;break;case"warn":this.loggerFactory.level=Nt.warn;break;case"log":this.loggerFactory.level=Nt.log;break;case"debug":this.loggerFactory.level=Nt.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(function(e){var t=n.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":n.logger.log("· "+e+": "+t);break;case"authorizationPassword":n.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":n.logger.log("· "+e+": "+t.name);break;default:n.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){var r=this.options.transportOptions,o=r.maxReconnectionAttempts,a=r.reconnectionTimeout;if(void 0!==o){var c='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(c)}if(void 0!==a){c='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(c)}void 0===t.reconnectionDelay&&void 0!==a&&(this.options.reconnectionDelay=a),void 0===t.reconnectionAttempts&&void 0!==o&&(this.options.reconnectionAttempts=o)}if(void 0!==t.reconnectionDelay){c='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(c)}if(void 0!==t.reconnectionAttempts){c='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(c)}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()}return e.makeURI=function(e){return He.URIParse(e)},e.defaultOptions=function(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:function(){},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:kn(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:hn.Unsupported,sipExtensionReplaces:hn.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Cn,transportOptions:{},uri:new De("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.20.0",viaHost:""}},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce(function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t},{})},Object.defineProperty(e.prototype,"configuration",{get:function(){return this.options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contact",{get:function(){return this._contact},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this._userAgentCore},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){return this.loggerFactory.getLogger(e,t)},e.prototype.getLoggerFactory=function(){return this.loggerFactory},e.prototype.isConnected=function(){return this.transport.isConnected()},e.prototype.reconnect=function(){var e=this;return this.state===In.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(function(){return e.transport.connect()})},e.prototype.start=function(){if(this.state===In.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting ".concat(this.configuration.uri)),this.transitionState(In.Started),this.options.autoStop){var 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()},e.prototype.stop=function(){return o(this,void 0,void 0,function(){var e,t,n,i,r,o,c,u,l,d,h,p,g,f,m,v,y,b,w,T,S,I,E,R,k,C,A,P=this;return a(this,function(_){switch(_.label){case 0:if(this.state===In.Stopped)return this.logger.warn("User agent already stopped"),[2,Promise.resolve()];for(h in this.logger.log("Stopping ".concat(this.configuration.uri)),this.transitionState(In.Stopped),this.options.autoStop&&(e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime),"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)),t=s({},this._publishers),n=s({},this._registerers),i=s({},this._sessions),r=s({},this._subscriptions),o=this.transport,c=this.userAgentCore,this.logger.log("Dispose of registerers"),u=function(e){return a(this,function(t){switch(t.label){case 0:return n[e]?[4,n[e].dispose().catch(function(t){throw P.logger.error(t.message),delete P._registerers[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},d=[],l=n)d.push(h);p=0,_.label=1;case 1:return p<d.length?(h=d[p])in l?[5,u(h)]:[3,3]:[3,4];case 2:_.sent(),_.label=3;case 3:return p++,[3,1];case 4:for(v in this.logger.log("Dispose of sessions"),g=function(e){return a(this,function(t){switch(t.label){case 0:return i[e]?[4,i[e].dispose().catch(function(t){throw P.logger.error(t.message),delete P._sessions[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},m=[],f=i)m.push(v);y=0,_.label=5;case 5:return y<m.length?(v=m[y])in f?[5,g(v)]:[3,7]:[3,8];case 6:_.sent(),_.label=7;case 7:return y++,[3,5];case 8:for(S in this.logger.log("Dispose of subscriptions"),b=function(e){return a(this,function(t){switch(t.label){case 0:return r[e]?[4,r[e].dispose().catch(function(t){throw P.logger.error(t.message),delete P._subscriptions[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},T=[],w=r)T.push(S);I=0,_.label=9;case 9:return I<T.length?(S=T[I])in w?[5,b(S)]:[3,11]:[3,12];case 10:_.sent(),_.label=11;case 11:return I++,[3,9];case 12:for(C in this.logger.log("Dispose of publishers"),E=function(e){return a(this,function(n){switch(n.label){case 0:return t[e]?[4,t[e].dispose().catch(function(t){throw P.logger.error(t.message),delete P._publishers[e],t})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})},k=[],R=t)k.push(C);A=0,_.label=13;case 13:return A<k.length?(C=k[A])in R?[5,E(C)]:[3,15]:[3,16];case 14:_.sent(),_.label=15;case 15:return A++,[3,13];case 16:return this.logger.log("Dispose of transport"),[4,o.dispose().catch(function(e){throw P.logger.error(e.message),e})];case 17:return _.sent(),this.logger.log("Dispose of core"),c.dispose(),[2]}})})},e.prototype._makeInviter=function(e,t){return new yn(this,e,t)},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;e>n?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - trying")),setTimeout(function(){t.reconnect().then(function(){t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - succeeded"))}).catch(function(i){t.logger.error(i.message),t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - failed")),t.attemptReconnection(++e)})},1===e?0:1e3*i))},e.prototype.initContact=function(){var e=this,t=""!==this.options.contactName?this.options.contactName:Me(8),n=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new De("sip",t,this.options.viaHost,void 0,n),toString:function(t){void 0===t&&(t={});var i=t.anonymous||!1,r=t.outbound||!1,s="<";return s+=i?e.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport=".concat(n.transport?n.transport:"ws"):e.contact.pubGruu||e.contact.uri,r&&(s+=";ob"),s+=">"}}},e.prototype.initCore=function(){var e=this,t=[];t.push("outbound"),this.options.sipExtension100rel===hn.Supported&&t.push("100rel"),this.options.sipExtensionReplaces===hn.Supported&&t.push("replaces"),this.options.sipExtensionExtraSupported&&t.push.apply(t,this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(t=t.filter(function(e){return mn[e]}));var n=(t=Array.from(new Set(t))).slice();(this.contact.pubGruu||this.contact.tempGruu)&&n.push("gruu");var i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:t,supportedOptionTagsResponse:n,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:function(){var t=e.options.authorizationUsername?e.options.authorizationUsername:e.options.uri.user,n=e.options.authorizationPassword?e.options.authorizationPassword:void 0,i=e.options.authorizationHa1?e.options.authorizationHa1:void 0;return new et(e.getLoggerFactory(),i,t,n)},transportAccessor:function(){return e.transport}};return new Qt(i,{onInvite:function(t){var n,i=new vn(e,t);if(t.delegate={onCancel:function(e){i._onCancel(e)},onTransportError:function(t){e.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},t.trying(),e.options.sipExtensionReplaces!==hn.Unsupported){var r=t.message.parseHeader("replaces");if(r){var s=r.call_id;if("string"!=typeof s)throw new Error("Type of call id is not string");var o=r.replaces_to_tag;if("string"!=typeof o)throw new Error("Type of to tag is not string");var a=r.replaces_from_tag;if("string"!=typeof a)throw new Error("type of from tag is not string");var c=s+o+a,u=e.userAgentCore.dialogs.get(c);if(!u)return void i.reject({statusCode:481});if(!u.early&&!0===r.early_only)return void i.reject({statusCode:486});var l=e._sessions[s+a]||e._sessions[s+o]||void 0;if(!l)throw new Error("Session does not exist.");i._replacee=l}}if(null===(n=e.delegate)||void 0===n?void 0:n.onInvite)return i.autoSendAnInitialProvisionalResponse?void i.progress().then(function(){var t;if(void 0===(null===(t=e.delegate)||void 0===t?void 0:t.onInvite))throw new Error("onInvite undefined.");e.delegate.onInvite(i)}):void e.delegate.onInvite(i);i.reject({statusCode:486})},onMessage:function(t){if(e.delegate&&e.delegate.onMessage){var n=new un(t);e.delegate.onMessage(n)}else t.accept()},onNotify:function(t){if(e.delegate&&e.delegate.onNotify){var n=new ln(t);e.delegate.onNotify(n)}else e.options.allowLegacyNotifications?t.accept():t.reject({statusCode:481})},onRefer:function(t){e.logger.warn("Received an out of dialog REFER request"),e.delegate&&e.delegate.onReferRequest?e.delegate.onReferRequest(t):t.reject({statusCode:405})},onRegister:function(t){e.logger.warn("Received an out of dialog REGISTER request"),e.delegate&&e.delegate.onRegisterRequest?e.delegate.onRegisterRequest(t):t.reject({statusCode:405})},onSubscribe:function(t){e.logger.warn("Received an out of dialog SUBSCRIBE request"),e.delegate&&e.delegate.onSubscribeRequest?e.delegate.onSubscribeRequest(t):t.reject({statusCode:405})}})},e.prototype.initTransportCallbacks=function(){var e=this;this.transport.onConnect=function(){return e.onTransportConnect()},this.transport.onDisconnect=function(t){return e.onTransportDisconnect(t)},this.transport.onMessage=function(t){return e.onTransportMessage(t)}},e.prototype.onTransportConnect=function(){this.state!==In.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()},e.prototype.onTransportDisconnect=function(e){this.state!==In.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())},e.prototype.onTransportMessage=function(e){var t=this,n=Xe.parseMessage(e,this.getLogger("sip.Parser"));if(n)if(this.state===In.Stopped&&n instanceof Ve)this.logger.warn("Received ".concat(n.method," request while stopped. Dropping."));else{var i=function(){for(var e=0,i=["from","to","call_id","cseq","via"];e<i.length;e++){var r=i[e];if(!n.hasHeader(r))return t.logger.warn("Missing mandatory header field : ".concat(r,".")),!1}return!0};if(n instanceof Ve){if(!i())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!n.toTag&&n.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(n,{statusCode:482});var r=Le(n.body);if((s=n.getHeader("content-length"))&&r<Number(s))return void this.userAgentCore.replyStateless(n,{statusCode:400})}if(n instanceof Ge){if(!i())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(n.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(n.via.host!==this.options.viaHost||void 0!==n.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var s;r=Le(n.body);if((s=n.getHeader("content-length"))&&r<Number(s))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(n instanceof Ve)this.userAgentCore.receiveIncomingRequestFromTransport(n);else{if(!(n instanceof Ge))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(n)}}else this.logger.warn("Failed to parse incoming message. Dropping.")},e.prototype.transitionState=function(e,t){var n=this,i=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};switch(this._state){case In.Started:e!==In.Stopped&&i();break;case In.Stopped:e!==In.Started&&i();break;default:throw new Error("Unknown state.")}this.logger.log("Transitioned from ".concat(this._state," to ").concat(e)),this._state=e,this._stateEventEmitter.emit(this._state)},e}();!function(){function e(e,t){void 0===t&&(t={});var n=this;this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.muted=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=s({},t);var i=s({},t.userAgentOptions);if(i.transportConstructor||(i.transportConstructor=Cn),i.transportOptions||(i.transportOptions={server:e}),!i.uri&&t.aor){var r=An.makeURI(t.aor);if(!r)throw new Error("Failed to create valid URI from ".concat(t.aor));i.uri=r}this.userAgent=new An(i),this.userAgent.delegate={onConnect:function(){n.logger.log("[".concat(n.id,"] Connected")),n.delegate&&n.delegate.onServerConnect&&n.delegate.onServerConnect(),n.registerer&&n.registerRequested&&(n.logger.log("[".concat(n.id,"] Registering...")),n.registerer.register().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred registering after connection with server was obtained.")),n.logger.error(e.toString())}))},onDisconnect:function(e){n.logger.log("[".concat(n.id,"] Disconnected")),n.delegate&&n.delegate.onServerDisconnect&&n.delegate.onServerDisconnect(e),n.session&&(n.logger.log("[".concat(n.id,"] Hanging up...")),n.hangup().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred hanging up call after connection with server was lost.")),n.logger.error(e.toString())})),n.registerer&&(n.logger.log("[".concat(n.id,"] Unregistering...")),n.registerer.unregister().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred unregistering after connection with server was lost.")),n.logger.error(e.toString())})),e&&n.attemptReconnection()},onInvite:function(e){if(n.logger.log("[".concat(n.id,"] Received INVITE")),n.session)return n.logger.warn("[".concat(n.id,"] Session already in progress, rejecting INVITE...")),void e.reject().then(function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))}).catch(function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())});var t={sessionDescriptionHandlerOptions:{constraints:n.constraints}};n.initSession(e,t),n.delegate&&n.delegate.onCallReceived?n.delegate.onCallReceived():(n.logger.warn("[".concat(n.id,"] No handler available, rejecting INVITE...")),e.reject().then(function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))}).catch(function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())}))},onMessage:function(e){e.accept().then(function(){n.delegate&&n.delegate.onMessageReceived&&n.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",function(){n.logger.log("[".concat(n.id,"] Online")),n.attemptReconnection()})}Object.defineProperty(e.prototype,"id",{get:function(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof Rn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof Rn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localAudioTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"audio"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localVideoTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"video"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteAudioTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"audio"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteVideoTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"video"===e.kind})},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this.logger.log("[".concat(this.id,"] Connecting UserAgent...")),this.connectRequested=!0,this.userAgent.state!==In.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.disconnect=function(){return this.logger.log("[".concat(this.id,"] Disconnecting UserAgent...")),this.connectRequested=!1,this.userAgent.stop()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e.prototype.register=function(e,t){var n=this;return this.logger.log("[".concat(this.id,"] Registering UserAgent...")),this.registerRequested=!0,this.registerer||(this.registerer=new Tn(this.userAgent,e),this.registerer.stateChange.addListener(function(e){switch(e){case fn.Initial:break;case fn.Registered:n.delegate&&n.delegate.onRegistered&&n.delegate.onRegistered();break;case fn.Unregistered:n.delegate&&n.delegate.onUnregistered&&n.delegate.onUnregistered();break;case fn.Terminated:n.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(function(){})},e.prototype.unregister=function(e){return this.logger.log("[".concat(this.id,"] Unregistering UserAgent...")),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(function(){}):Promise.resolve()},e.prototype.call=function(e,t,n){if(this.logger.log("[".concat(this.id,"] Beginning Session...")),this.session)return Promise.reject(new Error("Session already exists."));var i=An.makeURI(e);if(!i)return Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);var r=new yn(this.userAgent,i,t);return this.sendInvite(r,t,n).then(function(){})},e.prototype.hangup=function(){return this.logger.log("[".concat(this.id,"] Hangup...")),this.terminate()},e.prototype.answer=function(e){return this.logger.log("[".concat(this.id,"] Accepting Invitation...")),this.session?this.session instanceof vn?(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."))},e.prototype.decline=function(){return this.logger.log("[".concat(this.id,"] rejecting Invitation...")),this.session?this.session instanceof vn?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))},e.prototype.hold=function(){return this.logger.log("[".concat(this.id,"] holding session...")),this.setHold(!0)},e.prototype.unhold=function(){return this.logger.log("[".concat(this.id,"] unholding session...")),this.setHold(!1)},e.prototype.isHeld=function(){return this.held},e.prototype.mute=function(){this.logger.log("[".concat(this.id,"] disabling media tracks...")),this.setMute(!0)},e.prototype.unmute=function(){this.logger.log("[".concat(this.id,"] enabling media tracks...")),this.setMute(!1)},e.prototype.isMuted=function(){return this.muted},e.prototype.sendDTMF=function(e){if(this.logger.log("[".concat(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("[".concat(this.id,"] Sending DTMF tone: ").concat(e));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(function(){})},e.prototype.message=function(e,t){this.logger.log("[".concat(this.id,"] sending message..."));var n=An.makeURI(e);return n?new bn(this.userAgent,n,t).message():Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')))},Object.defineProperty(e.prototype,"constraints",{get:function(){var e,t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=s({},this.options.media.constraints)),t},enumerable:!1,configurable:!0}),e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts||3,i=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log("[".concat(this.id,"] Reconnection attempt already in progress")),e>n?this.logger.log("[".concat(this.id,"] Reconnection maximum attempts reached")):(1===e?this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying")):this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying in ").concat(i," seconds")),this.attemptingReconnection=!0,setTimeout(function(){if(!t.connectRequested)return t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - aborted")),void(t.attemptingReconnection=!1);t.userAgent.reconnect().then(function(){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - succeeded")),t.attemptingReconnection=!1}).catch(function(i){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - failed")),t.logger.error(i.message),t.attemptingReconnection=!1,t.attemptReconnection(++e)})},1===e?0:1e3*i))):this.logger.log("[".concat(this.id,"] Reconnection not currently desired"))},e.prototype.cleanupMedia=function(){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())))},e.prototype.enableReceiverTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof Rn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getReceivers().forEach(function(t){t.track&&(t.track.enabled=e)})},e.prototype.enableSenderTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof Rn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getSenders().forEach(function(t){t.track&&(t.track.enabled=e)})},e.prototype.initSession=function(e,t){var n=this;this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(function(t){if(n.session===e)switch(n.logger.log("[".concat(n.id,"] session state changed to ").concat(t)),t){case Wt.Initial:case Wt.Establishing:break;case Wt.Established:n.setupLocalMedia(),n.setupRemoteMedia(),n.delegate&&n.delegate.onCallAnswered&&n.delegate.onCallAnswered();break;case Wt.Terminating:case Wt.Terminated:n.session=void 0,n.cleanupMedia(),n.delegate&&n.delegate.onCallHangup&&n.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:function(e){var t;if(void 0!==(null===(t=n.delegate)||void 0===t?void 0:t.onCallDTMFReceived)){var i=e.request.getHeader("content-type");if(i&&/^application\/dtmf-relay/i.exec(i)){var r=e.request.body.split("\r\n",2);if(2===r.length){var s,o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(o.test(r[0])&&(s=r[0].replace(o,"$2")),s){var a,c=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;c.test(r[1])&&(a=parseInt(r[1].replace(c,"$2"),10)),a?e.accept().then(function(){if(n.delegate&&n.delegate.onCallDTMFReceived){if(!s||!a)throw new Error("Tone or duration undefined.");n.delegate.onCallDTMFReceived(s,a)}}).catch(function(e){n.logger.error(e.message)}):e.reject()}else e.reject()}else e.reject()}else e.reject()}else e.reject()},onRefer:function(e){e.accept().then(function(){return n.sendInvite(e.makeInviter(t),t)}).catch(function(e){n.logger.error(e.message)})}}},e.prototype.sendInvite=function(e,t,n){var i=this;return this.initSession(e,t),e.invite(n).then(function(){i.logger.log("[".concat(i.id,"] sent INVITE"))})},e.prototype.setHold=function(e){var t=this;if(!this.session)return Promise.reject(new Error("Session does not exist."));var n=this.session;if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof Rn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var i={requestDelegate:{onAccept:function(){t.held=e,t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)},onReject:function(){t.logger.warn("[".concat(t.id,"] re-invite request was rejected")),t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)}}},r=n.sessionDescriptionHandlerOptionsReInvite;return r.hold=e,n.sessionDescriptionHandlerOptionsReInvite=r,this.session.invite(i).then(function(){t.enableReceiverTracks(!e),t.enableSenderTracks(!e&&!t.muted)}).catch(function(e){throw e instanceof en&&t.logger.error("[".concat(t.id,"] A hold request is already in progress.")),e})},e.prototype.setMute=function(e){this.session?this.session.state===Wt.Established?(this.muted=e,this.enableSenderTracks(!this.held&&!this.muted)):this.logger.warn("[".concat(this.id,"] An established session is required to enable/disable media tracks")):this.logger.warn("[".concat(this.id,"] A session is required to enabled/disable media tracks"))},e.prototype.setupLocalMedia=function(){var e,t,n=this;if(!this.session)throw new Error("Session does not exist.");var i=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(i){var r=this.localMediaStream;if(!r)throw new Error("Local media stream undefiend.");i.srcObject=r,i.volume=0,i.play().catch(function(e){n.logger.error("[".concat(n.id,"] Failed to play local media")),n.logger.error(e.message)})}},e.prototype.setupRemoteMedia=function(){var e,t,n,i,r=this;if(!this.session)throw new Error("Session does not exist.");var s=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(i=null===(n=this.options.media)||void 0===n?void 0:n.remote)||void 0===i?void 0:i.audio);if(s){var o=this.remoteMediaStream;if(!o)throw new Error("Remote media stream undefiend.");s.autoplay=!0,s.srcObject=o,s.play().catch(function(e){r.logger.error("[".concat(r.id,"] Failed to play remote media")),r.logger.error(e.message)}),o.onaddtrack=function(){r.logger.log("[".concat(r.id,"] Remote media onaddtrack")),s.load(),s.play().catch(function(e){r.logger.error("[".concat(r.id,"] Failed to play remote media")),r.logger.error(e.message)})}}},e.prototype.terminate=function(){var e=this;if(this.logger.log("[".concat(this.id,"] Terminating...")),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case Wt.Initial:if(this.session instanceof yn)return this.session.cancel().then(function(){e.logger.log("[".concat(e.id,"] Inviter never sent INVITE (canceled)"))});if(this.session instanceof vn)return this.session.reject().then(function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))});throw new Error("Unknown session type.");case Wt.Establishing:if(this.session instanceof yn)return this.session.cancel().then(function(){e.logger.log("[".concat(e.id,"] Inviter canceled (sent CANCEL)"))});if(this.session instanceof vn)return this.session.reject().then(function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))});throw new Error("Unknown session type.");case Wt.Established:return this.session.bye().then(function(){e.logger.log("[".concat(e.id,"] Session ended (sent BYE)"))});case Wt.Terminating:case Wt.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log("[".concat(this.id,"] Terminating in state ").concat(this.session.state,", no action taken")),Promise.resolve()}}();var Pn=function(e){var t=document.getElementById(e);if(t instanceof HTMLAudioElement)return t;var n=new Audio;return n.controls=!0,n.autoplay=!0,n.id="ueRemoteAudio",n.style.display="none",document.body.appendChild(n),document.getElementById(e)}("ueRemoteAudio"),_n=function(){function e(e){var t=this;this.registerRequested=!1,this.attemptingReconnection=!1,this.connectRequested=!1,this.requestDelegate={onAccept:function(e){},onProgress:function(e){},onRedirect:function(e){},onReject:function(e){return o(t,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return[4,this.disconnect()];case 1:return e.sent(),[4,this.connect()];case 2:return e.sent(),this.register(),[2]}})})},onTrying:function(e){}},this.accept=function(){return o(t,void 0,void 0,function(){var e;return a(this,function(t){return e={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},[2,this.Ginvitation.accept(e)]})})},this.ueUnregisterWebrtc=function(){return o(t,void 0,void 0,function(){return a(this,function(e){return this.registerer?[2,this.registerer.unregister({all:!0}).then(function(e){}).catch(function(e){})]:[2,!1]})})};var n=An.makeURI("sip:"+e.sip+"@"+e.server);if(!n)throw new Error("Failed to create URI");var i={onConnect:function(e){return o(t,void 0,void 0,function(){return a(this,function(e){return this.registerer&&this.registerRequested&&this.registerer.register().catch(function(e){}),[2]})})},onDisconnect:function(e){t.registerer&&t.registerer.unregister().catch(function(e){}),e&&t.attemptReconnection()},onInvite:function(e){t.Ginvitation=e;var n=e;n.delegate={onRefer:function(e){}},n.stateChange.addListener(function(e){switch(e){case Wt.Initial:case Wt.Establishing:break;case Wt.Established:var t=n.sessionDescriptionHandler;if(!(t&&t instanceof Rn))throw new Error("Invalid session description handler.");Pn&&(i=t.remoteMediaStream,(r=Pn).autoplay=!0,r.srcObject=i,r.play().catch(function(e){}),i.onaddtrack=function(){r.load(),r.play().catch(function(e){})},i.onremovetrack=function(){r.load(),r.play().catch(function(e){})});break;case Wt.Terminating:case Wt.Terminated:break;default:throw new Error("Unknown session state.")}var i,r});var i={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},r=t.Ginvitation.incomingInviteRequest.message.headers["X-Calltype"][0].raw;"callout"!==r&&"callTask"!==r||e.accept(i).then(function(){}).catch(function(e){})}},r={logBuiltinEnabled:!1,delegate:i,displayName:"WEBRTC",uri:n,transportOptions:{server:"wss://"+e.server},authorizationUsername:e.sip,authorizationHa1:e.secret,reconnectionDelay:0};this.userAgent=new An(r),window.addEventListener("online",function(){return o(t,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return window.sessionStorage.getItem("kickoff")?[2]:[4,this.attemptReconnection()];case 1:return e.sent(),this.register(),[2]}})})})}return e.prototype.register=function(){var e=this;return this.registerRequested=!0,this.registerer||(this.registerer=new Tn(this.userAgent,{expires:10}),this.registerer.stateChange.addListener(function(t){switch(t){case fn.Initial:case fn.Registered:case fn.Unregistered:break;case fn.Terminated:e.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register({requestDelegate:this.requestDelegate}).then(function(){})},e.prototype.unregister=function(e){return this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(function(){}):Promise.resolve()},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);this.connectRequested&&(e>1||(this.attemptingReconnection=!0,setTimeout(function(){t.connectRequested?t.userAgent.reconnect().then(function(){t.attemptingReconnection=!1}).catch(function(n){t.attemptingReconnection=!1,t.attemptReconnection(++e)}):t.attemptingReconnection=!1},0)))},e.prototype.sendDTMF=function(e){if(!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.Ginvitation)return Promise.reject(new Error("Session does not exist."));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.Ginvitation.info({requestOptions:t}).then(function(){})},e.prototype.disconnect=function(){return this.connectRequested=!1,this.userAgent.stop()},e.prototype.connect=function(){return this.connectRequested=!0,this.userAgent.state!==In.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e}(),Dn={requestState:!1,delay:0},qn=function(){function i(e){void 0===e&&(e={});var t=this;this.getWebrtcInfo=function(e,t,n){r.request(e+"/call/api/sip/webrtc/config/query",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(e){e.success&&e.data?(r.agentextras=e.data,"WEBRTC"===n&&r.initWebrtcEvent(e.data)):t.error(s({},e))},error:function(e){t.error({error:e})}})},this.initAttachEvent=function(e,n,i,s){r.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach(function(e){"KF"===e.id&&(o=e.url)});var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:n,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:1,pushHangupStatistics:r.initOptions.pushHangupStatistics||!1,pushCallinRingStatistics:r.initOptions.pushCallinRingStatistics||!1},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};t.attachEventCallbacks?(t.attachEventCallbacks.serve=o,t.attachEventCallbacks.SocketOptions=a,r.createEventHandle(t.attachEventCallbacks)):r.createEventHandle({serve:o,SocketOptions:a})}},error:function(e){i.error({error:e})}})},this.attachNetworkCallbacks={message:r.noop,error:r.noop,success:r.noop},this.initnNetworkMonitoring=function(e,n){var i="";e.forEach(function(e){"MONITOR"===e.id&&(i="https://"+e.url)}),t.attachNetworkCallbacks.success(),t.attachNetworkCallbacks.message({delay:100}),setInterval(function(){var e=(new Date).getTime();Dn.requestState=!0,r.request(i+"/ready",{method:"GET",success:function(n){if(n.success){var i=(new Date).getTime();Dn.delay=(i-e)/2,t.attachNetworkCallbacks.message({delay:Dn.delay})}else t.attachNetworkCallbacks.error(),Dn.delay=500,Dn.requestState=!1},error:function(e){t.attachNetworkCallbacks.error(),Dn.delay=500,Dn.requestState=!1}})},1e4)},this.listenCallNetork=function(e){e&&(t.attachNetworkCallbacks.message=e.message&&"function"==typeof e.message?e.message:r.noop,t.attachNetworkCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.attachNetworkCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop)},this.volumeCallbacks={message:r.noop,error:r.noop,success:r.noop},this.stopVolumeCallbacks={error:r.noop,success:r.noop},this.audioContext=null,this.analyser=null,this.dataArray=null,this.stream=null,this.volumeIntervalId=null,this.getMicrophoneVolume=function(){if(!t.analyser||!t.dataArray)return 0;t.analyser.getByteFrequencyData(t.dataArray);for(var e=0,n=0;n<t.dataArray.length;n++)e+=t.dataArray[n];return e/t.dataArray.length},this.initAudioDetection=function(){return o(t,void 0,void 0,function(){var e,t,n;return a(this,function(i){switch(i.label){case 0:if(this.audioContext)return[2];i.label=1;case 1:return i.trys.push([1,3,,4]),e=this,[4,navigator.mediaDevices.getUserMedia({audio:!0})];case 2:return e.stream=i.sent(),this.audioContext=new AudioContext,t=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),t.connect(this.analyser),[3,4];case 3:return n=i.sent(),this.volumeCallbacks.error(n),[3,4];case 4:return[2]}})})},this.startVolumeDetection=function(e,n){return o(t,void 0,void 0,function(){var t,n=this;return a(this,function(i){switch(i.label){case 0:return"WEBRTC"!==e.loginType?(this.volumeCallbacks.error("只有webrtc支持音量检测"),[2]):(this.clearVolumeDetection(),[4,this.initAudioDetection()]);case 1:return i.sent(),this.volumeCallbacks.success({code:"200",msg:"音频检测已初始化"}),e.interval||(e.interval=500),e.interval<100&&(e.interval=100),e.interval>5e3&&(e.interval=5e3),t=this.getMicrophoneVolume(),this.volumeCallbacks.message({volume:Math.round(t/255*100)}),this.volumeIntervalId=setInterval(function(){var e=n.getMicrophoneVolume();n.volumeCallbacks.message({volume:Math.round(e/255*100)})},e.interval),[2]}})})},this.clearVolumeDetection=function(){t.volumeIntervalId&&(clearInterval(t.volumeIntervalId),t.volumeIntervalId=null),t.stream&&(t.stream.getTracks().forEach(function(e){return e.stop()}),t.stream=null),t.audioContext&&(t.audioContext.close(),t.audioContext=null),t.analyser=null,t.dataArray=null},this.stopVolumeDetection=function(){try{t.clearVolumeDetection(),t.stopVolumeCallbacks.success({code:"200",msg:"音频检测关闭成功"})}catch(e){t.stopVolumeCallbacks.error(e)}},this.listenCallVolume=function(e){e&&(t.volumeCallbacks.message=e.message&&"function"==typeof e.message?e.message:r.noop,t.volumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.volumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop),r.initOptions.volume||(r.initOptions.volume={open:!0,interval:500}),t.startVolumeDetection(s(s({},r.initOptions.volume),{loginType:r.initOptions.loginType}),"")},this.stopListenVolume=function(e){e&&(t.stopVolumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.stopVolumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop),t.stopVolumeDetection()},this.turnOffRingCallbacks={error:r.noop,success:r.noop},this.muteRing=function(e){e&&(t.turnOffRingCallbacks.success=e.success&&"function"==typeof e.success?e.success:r.noop,t.turnOffRingCallbacks.error=e.error&&"function"==typeof e.error?e.error:r.noop);try{r.isCanRing=!1,Hn.ringAudioPause(),t.turnOffRingCallbacks.success({code:"200",msg:"关闭铃声成功"})}catch(e){t.turnOffRingCallbacks.error(e)}},this.sdkMonitorMsg=function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.error=e&&"function"==typeof e.error?e.error:r.noop,null!==e.type&&void 0!==e.type&&""!==e.type)if(null!==e.requestMsg&&void 0!==e.requestMsg&&""!==e.requestMsg&&"{}"!==JSON.stringify(e.requestMsg))if(r.initOptions.monitor)try{r.changeMonitorEventHandle(t.allMonitorEventCallbacks,e),e.success({code:"200",msg:"成功"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter requestMsg is required!"});else e.error({success:!1,message:"Parameter type is required!"})},this.closeSdkMonitor=function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.error=e&&"function"==typeof e.error?e.error:r.noop,null!==e.type&&void 0!==e.type&&""!==e.type&&0!==e.type.length)if(r.initOptions.monitor)try{e.type.forEach(function(e){switch(e){case"summary":clearInterval(r.summaryUeTimer);break;case"agent":clearInterval(r.agentUeTimer);break;case"queue":clearInterval(r.queueUeTimer)}}),e.success({code:"200",msg:"success"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter type is required!"})},this.initAgentQueue=function(e,n,i,s){(t.attachMonitorEventCallbacks||t.attachNlsTranslationEventCallbacks||t.allMonitorEventCallbacks)&&r.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach(function(e){"MONITOR"===e.id&&(o=e.url)});var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:n,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:3},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};t.attachMonitorEventCallbacks&&r.UserConfig.isOpenCallQueue&&(t.attachMonitorEventCallbacks.serve=o,t.attachMonitorEventCallbacks.SocketOptions=a,r.createQueueMonitorEventHandle(t.attachMonitorEventCallbacks)),t.attachNlsTranslationEventCallbacks&&r.UserConfig.openNlsTranslation&&(t.attachNlsTranslationEventCallbacks.serve=o,t.attachNlsTranslationEventCallbacks.SocketOptions=a,r.createopenNlsTransEventHandle(t.attachNlsTranslationEventCallbacks)),t.allMonitorEventCallbacks&&r.UserConfig.monitor&&(t.allMonitorEventCallbacks.serve=o,t.allMonitorEventCallbacks.SocketOptions=a,r.createopenAllMonitorEventHandle(t.allMonitorEventCallbacks))}},error:function(e){r.log("失败"),i.error({error:e})}})},this.initQueue=function(e){r.request(e+"/call/monitor/agent/queue/query",{verb:"POST",body:{accountId:r.agentInfo.accountId,agentId:r.agentInfo._id},success:function(e){e&&e.data?t.attachMonitorEventCallbacks.message(e):t.attachMonitorEventCallbacks.error(e)},error:function(e){t.attachMonitorEventCallbacks.error(e)}})},this.listenCallQueueEvent=function(e){t.attachMonitorEventCallbacks=e},this.listenTranslationEvent=function(e){t.attachNlsTranslationEventCallbacks=e},this.listenMonitor=function(e){t.allMonitorEventCallbacks=e},this.openMediaAudio=function(e,n){var i,r=navigator,s=r.mediaDevices,c=r.getUserMedia,u=r.webkitGetUserMedia,l=r.mozGetUserMedia,d=r.msGetUserMedia,h=null===(i=s&&s.getUserMedia||c||u||l||d)||void 0===i?void 0:i.bind(navigator);return s&&s.getUserMedia?s.getUserMedia({audio:!0}).then(function(e){return o(t,void 0,void 0,function(){return a(this,function(t){return p(e),[2,!0]})})}).catch(function(t){var i=t.message.includes("Permission denied")||"NotAllowedError"===t.name;return n?(i?alert(Ae.forbiddenAudioMsg):e&&alert(e),i?Ae:Ce):i?Ae:Ce}):new Promise(function(t,i){h?h({audio:!0},function(e){p(e),t(!0)},function(t){n&&e&&alert(e),i(Ce)}):i(Ce)});function p(e){e&&"function"==typeof e.getTracks&&e.getTracks().forEach(function(e){e.stop()})}},this.listenCallEvent=function(e){t.attachEventCallbacks=e,e&&null!=r.Socketinstance&&r.createEventHandle(t.attachEventCallbacks)},this.switchOutDevices=function(e){return o(t,void 0,void 0,function(){var t,n,i,s;return a(this,function(o){switch(o.label){case 0:if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,!e.deviceId||"string"!=typeof e.deviceId)return e.fail({success:!1,message:"Passing in an illegal deviceId!"}),[2];t=document.getElementById("ueRemoteAudio"),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,navigator.mediaDevices.enumerateDevices()];case 2:return n=o.sent(),i=n.filter(function(e){return"audiooutput"===e.kind}),i.some(function(t){return t.deviceId===e.deviceId})?[4,t.setSinkId(e.deviceId)]:(e.fail({success:!1,message:"The deviceId is not in the output device list!"}),[2]);case 3:return o.sent(),[3,5];case 4:return s=o.sent(),e.fail(s),[3,5];case 5:return e.success({code:"200",msg:"切换音频输出设备成功"}),[2]}})})},this._callApi=function(){var e,n,i=t;return{callout:function(t){return o(this,void 0,void 0,function(){var o,c,u,l,d,h;return a(this,function(a){switch(a.label){case 0:if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null===r.loginToken||void 0===r.loginToken)return t.fail({success:!1,message:"initialization not complete!"}),[2];if("KICK_OFF"===r.loginToken)return t.fail({success:!1,message:"您的座席账号正在别处登录,当前页面电话条已退出。"}),[2];if(null===r.agentInfo||void 0===r.agentInfo)return t.fail({success:!1,message:"initialization not complete!"}),[2];if(null===t.customerNumber||void 0===t.customerNumber)return t.fail({success:!1,message:"Parameter customerNumber is required!"}),[2];if(o=r.initOptions.server||r.callApiUrl,c={customerNumber:t.customerNumber,agentNumber:r.agentInfo.agentNumber,accountId:r.agentInfo.accountId,agentId:r.agentInfo._id,loginType:t.loginType||r.agentInfo.loginType||r.initOptions.loginType},t.agentTimeout&&(c.agentTimeout=t.agentTimeout),t.customerTimeout&&(c.customerTimeout=t.customerTimeout),t.agentDisNumber&&(c.agentDisNumber=t.agentDisNumber),t.customerDisNumber&&(c.customerDisNumber=t.customerDisNumber),t.extras&&(c.extras=t.extras),t.numberGroupId&&(c.numberGroupId=t.numberGroupId),t.numberGroupName&&(c.numberGroupName=t.numberGroupName),u=r.initOptions,l=!0,"WEBRTC"!==u.loginType)return[3,4];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,i.openMediaAudio("请打开麦克风权限!",l)];case 2:return d=a.sent()||{},r.log(d),!0!==d?(t.fail({success:!1,message:"无麦克风权限!"}),[2]):[3,4];case 3:return h=a.sent(),r.log(h),t.fail({success:!1,message:"无麦克风权限!"}),[2];case 4:return r.request(o+"/call/api/call/call/out",{verb:"POST",body:c,loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success(s(s({success:!0,message:"callout success"},d),e.data)):t.fail(s({success:!1,message:e.message,code:e.code},d))}}),[2]}})})},hangup:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/hangup",{verb:"POST",body:{},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?(t.success({success:!0,message:"hangup success",data:e}),Hn.InvalidateHangup()):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},holdOrUnHold:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type){var i=r.initOptions.server||r.callApiUrl,s={type:t.type};r.request(i+"/call/api/call/hold",{verb:"POST",body:s,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"holdOrUnHold success"}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},muteOrUnMute:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type){var i=r.initOptions.server||r.callApiUrl,s="1"===t.type?"in":"all",o={type:t.type,direction:s};r.request(i+"/call/api/call/mute",{verb:"POST",body:o,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"muteOrUnMute success"}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},transfer:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type)if(null!==t.number&&void 0!==t.number){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/transfer",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"transfer success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter number is required!"});else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},consult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.mode&&void 0!==t.mode)if(null!==t.number&&void 0!==t.number){t.agentNumber=r.agentInfo.agentNumber;var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"consult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter number is required!"});else t.fail({success:!1,message:"Parameter mode is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},cancelconsult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/cancel",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"cancelconsult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},endConsult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/stop",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"endConsult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},callbackConsult:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/resume",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"resumeConsult success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},consultTransfer:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/consult/transfer",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"consultTransfer success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},threeWayCall:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/threeway",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"threeWayCall success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},evaluate:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.type&&void 0!==t.type){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/evaluate",{verb:"POST",body:t,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"evaluate success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter type is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},meeting:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.number&&void 0!==t.number){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/call/meeting",{verb:"POST",body:{meetingType:"phone",number:t.number},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"meeting success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"Parameter number is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},listen:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/listen",{verb:"POST",body:{agentNumber:t.agentNumber,listenAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"listen success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},loot:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/lootCall",{verb:"POST",body:{agentNumber:t.agentNumber,lootAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"loot success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},forcedHangup:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/hangupChannel",{verb:"POST",body:{agentNumber:t.agentNumber,hangupAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"forcedHangup success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},breakIn:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/breakIn",{verb:"POST",body:{agentNumber:t.agentNumber,breakInAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"breakIn success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})},whisper:function(t){if(t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null!==r.loginToken&&void 0!==r.loginToken)if(null!==r.agentInfo&&void 0!==r.agentInfo)if(null!==t.agentNumber&&void 0!==t.agentNumber)if(t.agentNumber!==r.agentInfo.agentNumber&&"0000"!==r.agentInfo.agentNumber){var i=r.initOptions.server||r.callApiUrl;r.request(i+"/call/api/monitor/whisper",{verb:"POST",body:{agentNumber:t.agentNumber,whisperAgent:r.agentInfo.agentNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,encryptionAlgorithm:e,encryptionFields:n,success:function(e){e.success?t.success({success:!0,message:"whisper success",data:e.data}):t.fail({success:!1,message:e.message,code:e.code})}})}else t.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else t.fail({success:!1,message:"Parameter agentNumber is required!"});else t.fail({success:!1,message:"initialization not complete!"});else t.fail({success:!1,message:"initialization not complete!"})}}},this._agentApi=function(){var e=t;return{switchLoginType:function(t){return o(this,void 0,void 0,function(){var n,i,c,u,l=this;return a(this,function(d){return n=null,t.success=t&&"function"==typeof t.success?t.success:r.noop,t.fail=t&&"function"==typeof t.fail?t.fail:r.noop,null===t.loginType||void 0===t.loginType?(t.fail({success:!1,message:"Parameter loginType is required!"}),[2]):null===r.agentInfo||void 0===r.agentInfo?(t.fail({success:!1,message:"initialization not complete!"}),[2]):(null!==t.loginNumber&&void 0!==t.loginNumber&&(n=t.loginNumber),"PSTN"!==t.loginType||(n=n||r.agentInfo.mobile)?("SIP"===t.loginType&&(n=n||r.agentInfo.sipNumber),"WEBRTC"===t.loginType&&(n=r.agentInfo.webrtcSipNumber),i=r.initOptions.server||r.callApiUrl,c={loginType:t.loginType,loginNumber:n},r.request(i+"/call/api/agent/v1/login-type/change",{verb:"POST",body:c,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(n){return o(l,void 0,void 0,function(){return a(this,function(o){switch(o.label){case 0:return n.success?(t.success(s({success:!0,message:"updateLoginType success"},u)),r.agentInfo.loginType=t.loginType,r.initOptions.loginType=t.loginType,"WEBRTC"!==t.loginType?[3,1]:(e._webPhoneApi().connect(),[3,4])):[3,5];case 1:return"PSTN"!==t.loginType?[3,3]:[4,r.request(i+"/platform/action/updateCallConfig",{verb:"POST",body:{agentCallConfig:{},mobile:t.loginNumber},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId})];case 2:return o.sent(),e._webPhoneApi().disconnect(),[3,4];case 3:e._webPhoneApi().disconnect(),o.label=4;case 4:return[3,6];case 5:t.fail(s({success:!1,message:n.message,code:n.code},u)),o.label=6;case 6:return[2]}})})}}),[2]):(alert("请给座席绑定手机号,或者传入号码参数!"),t.fail({success:!1,message:"Please bind your mobile number"}),[2]))})})},findPhoneBarList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl;r.request(t+"/call/api/phone/bar/all",{verb:"GET",loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(t){if(t.success){var n=[];t.data.forEach(function(e){var t={name:e.name,number:e.number};n.push(t)}),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},switchPhoneBar:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==e.stateNumber&&void 0!==e.stateNumber)if(null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl,n={stateNumber:e.stateNumber,accountId:r.agentInfo.accountId,agentNumber:r.agentInfo.agentNumber};r.request(t+"/call/api/agent/status/switch",{verb:"POST",body:n,loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(t){t.success?e.success({success:!0}):e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"});else e.fail({success:!1,message:"Parameter stateNumber is required!"})},logout:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){null!==e.toAnswerOffline&&void 0!==e.toAnswerOffline||(e.toAnswerOffline="0");var t=r.initOptions.server||r.callApiUrl,n={toAnswerOffline:e.toAnswerOffline};r.request(t+"/call/api/sdk/agent/logout",{verb:"POST",body:n,loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(t){t.success?e&&(r.Socketinstance&&(r.Socketinstance.disconnect(),r.Socketinstance=null),r.MonitorSocketinstance&&(r.MonitorSocketinstance.disconnect(),r.MonitorSocketinstance=null),"WEBRTC"===r.UserConfig.loginType&&r.webPhone&&(window.sessionStorage.setItem("kickoff","true"),r.webPhone.disconnect(),r.webPhone=null),e.success({success:!0})):e&&e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},findIdleAgentsForQueue:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl;r.request(t+"/call/api/queue/acountFreeAgent/find",{verb:"POST",body:{},loginToken:r.loginToken,sessionId:r.agentInfo._id,accountId:r.agentInfo.accountId,success:function(t){t.success?e&&e.success({success:!0,dataList:t.data||[]}):e&&e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},getAvailableSipNumberList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:r.noop,e.fail=e&&"function"==typeof e.fail?e.fail:r.noop,null!==r.agentInfo&&void 0!==r.agentInfo){var t=r.initOptions.server||r.callApiUrl;r.request(t+"/call/api/sip/avaliable/query",{verb:"POST",body:{},loginToken:r.loginToken,sessionId:r.agentInfo._id,success:function(t){if(t.success&&t.data){var n=[];t.data.forEach(function(e){var t={number:e.id,numberName:e.number};n.push(t)}),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})}}},this._webPhoneApi=function(){return{accept:function(){r.webPhone.accept()},connect:function(){r.webPhone&&this.isConnected()||r.initWebrtcEvent(r.agentextras)},disconnect:function(){r.webPhone&&this.isConnected()&&r.webPhone.disconnect()},isConnected:function(){return r.webPhone.isConnected()},sendDTMF:function(e){r.webPhone.sendDTMF(e)}}},e.error="function"==typeof e.error?e.error:r.noop,e.success="function"==typeof e.success?e.success:r.noop,null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.accountId&&void 0!==e.accountId&&""!==e.accountId?null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.agentNumber&&void 0!==e.agentNumber&&""!==e.accountId?null!==e.password&&void 0!==e.password?(null!==e.loginType&&void 0!==e.loginType||(e.loginType="PSTN"),null!==e.pushHangupStatistics&&void 0!==e.pushHangupStatistics||(e.pushHangupStatistics=!1),null!==e.pushCallinRingStatistics&&void 0!==e.pushCallinRingStatistics||(e.pushCallinRingStatistics=!1),this.init(e)):e.error({message:"Invalid password"}):e.error({message:"Invalid agentNumber or Invalid accountName"}):e.error({message:"Invalid accountId or Invalid accountName"})}var r;return i.noop=function(){},i.prototype.init=function(e){if(void 0===e&&(e={}),r.trace=r.noop,r.debug=r.noop,r.log=r.noop,r.warn=r.noop,r.error=r.noop,!0===e.debug||"all"===e.debug)r.trace=console.trace.bind(console),r.debug=console.debug.bind(console),r.log=console.log.bind(console),r.warn=console.warn.bind(console),r.error=console.error.bind(console);else if(Array.isArray(e.debug))for(var t in e.debug){var n=e.debug[t];switch(n){case"trace":r.trace=console.trace.bind(console);break;case"debug":r.debug=console.debug.bind(console);break;case"log":r.log=console.log.bind(console);break;case"warn":r.warn=console.warn.bind(console);break;case"error":r.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+n+"' (supported: 'trace', 'debug', 'log', warn', 'error')")}}r.log("Initializing library");var i=r.useDefaultDependencies({WebSocket:On});r.newWebSocket=i.newWebSocket,r.request=i.request,this.getDomain(e)},i.prototype.getDomain=function(e){return o(this,void 0,void 0,function(){var t,n,i,s=this;return a(this,function(o){return t=(null===(i=e.accountName)||void 0===i?void 0:i.split("@")[1])||e.accountId,n=e.server||r.callApiUrl,r.request(n+"/platform/public/cloudConfig?accountName="+t,{verb:"GET",success:function(t){t.success?(e.server="https://"+t.data.baseURL+"/api",r.callApiUrl="https://"+t.data.baseURL+"/api",s.login(e)):e.error({res:t})},error:function(t){e.error({error:t})}}),[2]})})},i.prototype.login=function(i){return o(this,void 0,void 0,function(){var o,c,u,l,d,h,p,g,f,m=this;return a(this,function(a){return r.log(i),r.UserConfig=i,o=i.server||r.callApiUrl,c=i.accountName?i.accountName:i.agentNumber+"@"+i.accountId,u=i.loginType,l=i.isOpenNetwork||!1,d=i.isOpenCallQueue||!1,h=i.openNlsTranslation||!1,p=i.monitor||!1,g={loginName:c,loginType:u,loginChannel:"SDK",password:"",clientType:1},i.password&&(g.password=i.password),r.request(o+"/platform/public/loginPre",{verb:"GET",success:function(a){if(a&&a.success&&a.data){var c=decodeURIComponent(e.decode(a.data.pk)),v=new n;v.setPublicKey(c);var y=t(g.password),b=v.encrypt(y);g.password=b,r.request(o+"/platform/public/login",{verb:"POST",body:g,success:function(e){e.success?r.request(o+"/platform/action/loginInfo",{verb:"GET",loginToken:e.data.loginToken,sessionId:e.data.sessionId,success:function(e){e.success?(e.data.agent&&(r.agentInfo=e.data.agent,r.loginToken=e.data.loginToken,r.initOptions=s(s({},i),{audioInfo:f}),i.success(s(s({},e),{msg:"登录成功"}))),m.initAttachEvent(o,u,e.data.pushServer,e.data.agent),l&&m.initnNetworkMonitoring(e.data.pushServer,""),(d||h||p)&&m.initAgentQueue(o,u,e.data.pushServer,e.data.agent),d&&m.initQueue(o),m.getWebrtcInfo(o,i,u),window.sessionStorage.removeItem("kickoff")):i.error(s(s({},e),f))},error:function(e){i.error(s({error:e},f))}}):i.error(s(s({},e),f))},error:function(e){i.error(s({error:e},f))}})}else i.error(s(s({},a),f))},error:function(e){i.error(s({error:e},f))}}),[2]})})},i.createEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.event="function"==typeof e.event?e.event:r.noop,e.server=null===e.serve||void 0===e.serve?"ws://152.136.72.209:3201/phoneBarGateway":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),this.Socketinstance||(this.Socketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.Socketinstance.on("connect",function(){e.success("connect event serve success!")}),this.Socketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.Socketinstance.on("message",function(t,n){e.message({subtype:t.subType,data:t.data}),"WEBRTC"===r.initOptions.loginType&&$n("WEBRTC",t.data),n&&"function"==typeof n&&n("success")}),this.Socketinstance.on("event",function(t){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.event({message:"坐席账户在其他地方登录",data:t})}})},i.createQueueMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("connect event serve success!"),r.log("监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(t,n){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:t})}e.message(t)}),this.MonitorSocketinstance.on("call",function(t,n){"queue"==t.subType&&r.UserConfig.isOpenCallQueue&&e.message({subtype:t.subType,data:t.data})})},i.createopenNlsTransEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("转译connect event serve success!"),r.log("转译监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(t,n){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:t})}e.message(t)}),this.MonitorSocketinstance.on("call",function(t,n){"translation"==t.subType&&r.UserConfig.openNlsTranslation&&e.message({subtype:t.subType,data:t.data})})},i.createopenAllMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("转译connect event serve success!"),r.log("转译监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(t,n){if("KICK_OFF"===t.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===t.data.kickoff)){try{r.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:t})}e.message(t)}),r.UserConfig.monitor&&this.MonitorSocketinstance.on("monitor",function(t){r.UserConfig.monitor&&e.message({type:"agent",data:t})})},i.changeMonitorEventHandle=function(e,t){var n=this;void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:r.noop,e.error="function"==typeof e.error?e.error:r.noop,e.message="function"==typeof e.message?e.message:r.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},r.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=r.newWebSocket(e.server,e.SocketOptions)),r.UserConfig.monitor&&t&&(r.agentUeTimer&&clearInterval(r.agentUeTimer),r.queueUeTimer&&clearInterval(r.queueUeTimer),r.summaryUeTimer&&clearInterval(r.summaryUeTimer),t.type.forEach(function(i){var o;switch(i){case"agent":null!==n.MonitorSocketinstance&&(null===(o=n.MonitorSocketinstance)||void 0===o||o.emit("monitor","agent",JSON.stringify(s(s({},t.requestMsg),{monitorQueryAgent:r.agentInfo._id,accountId:r.agentInfo.accountId})))),r.agentUeTimer=window.setInterval(function(){var e;null===(e=n.MonitorSocketinstance)||void 0===e||e.emit("monitor","agent",JSON.stringify(s(s({},t.requestMsg),{monitorQueryAgent:r.agentInfo._id,accountId:r.agentInfo.accountId})))},3e3);break;case"queue":null!==n.MonitorSocketinstance&&n.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:r.agentInfo.accountId,date:new Date}},e),r.queueUeTimer=window.setInterval(function(){n.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:r.agentInfo.accountId,date:new Date}},e)},3e3);break;case"summary":null!==n.MonitorSocketinstance&&n.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:r.agentInfo.accountId,date:new Date}},e),r.summaryUeTimer=window.setInterval(function(){n.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:r.agentInfo.accountId,date:new Date}},e)},3e3)}}))},i.handleHttpMonitor=function(e,t){r.request(r.callApiUrl+e.url,{verb:"POST",body:e.data,success:function(n){n.success&&r.UserConfig.monitor?t.message({type:e.type,data:n.data}):t.error({type:e.type,data:n})}})},i.useDefaultDependencies=function(e){var t=e&&e.fetch||fetch,n=e&&e.Promise||Promise,i=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new i(e,t)},request:function(e,i){var s={method:i.verb,cache:"no-cache",headers:{"Content-Type":"application/json",loginToken:i.loginToken||"",sessionId:i.sessionId||"",clienttype:0}};i.encryptionFields&&(s.headers["ue-encryption-algorithm"]=i.encryptionAlgorithm||"aes",s.headers["ue-encryption-fields"]=i.encryptionFields),void 0!==i.withCredentials&&(s.credentials=!0===i.withCredentials?"include":i.withCredentials?i.withCredentials:"omit"),void 0!==i.body&&(s.body=JSON.stringify(i.body));var o=t(e,s).catch(function(e){return n.reject({message:"Probably a network error, is the gateway down?",error:e})});if(void 0!==i.timeout){var a=new n(function(e,t){var n=window.setTimeout(function(){return clearTimeout(n),i.error({message:"Request timed out",timeout:i.timeout}),t({message:"Request timed out",timeout:i.timeout})},i.timeout)});o=n.race([o,a])}return o.then(function(e){return e.ok?typeof i.success==typeof r.noop?e.json().then(function(e){i.success(e)}).catch(function(t){return i.error({message:"Failed to parse response body",error:t,response:e}),n.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:(i.error({message:"API call failed",response:e}),n.reject({message:"API call failed",response:e}))}).catch(function(e){typeof i.error==typeof r.noop&&i.error(e.message||"<< internal error >>",e)}),o}}},Object.defineProperty(i.prototype,"agent",{get:function(){return this._agentApi()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"webrtc",{get:function(){return this._webPhoneApi()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"call",{get:function(){return this._callApi()},enumerable:!1,configurable:!0}),r=i,i.callApiUrl="https://app.useasy.cn/api",i.Socketinstance=null,i.AudioTask=null,i.MonitorSocketinstance=null,i.UserConfig=null,i.isCanRing=!0,i.kickOffEvent=function(){r.Socketinstance&&(r.Socketinstance.disconnect(),r.Socketinstance=null),r.MonitorSocketinstance&&(r.MonitorSocketinstance.disconnect(),r.MonitorSocketinstance=null),"WEBRTC"===r.UserConfig.loginType&&r.webPhone&&(window.sessionStorage.setItem("kickoff","true"),r.webPhone.disconnect(),r.webPhone=null)},i.initWebrtcEvent=function(e){return o(void 0,void 0,void 0,function(){return a(r,function(t){switch(t.label){case 0:return r.webPhone=new _n({server:e.wssUrl,sip:e.sip,secret:e.password}),[4,this.webPhone.connect()];case 1:return t.sent(),this.webPhone.register(),[2]}})})},i}(),On=function(){function e(e,t){delete t.path,delete t.hostname,delete t.port,this.ws=ke.connect("wss://".concat(e),t)}return e.prototype.on=function(e,t){"connect"===e&&this.ws.on(e,t),"error"===e&&(this.ws.on("connect_error",t),this.ws.on("error",t),this.ws.on("disconnect",t),this.ws.on("reconnect_failed",t)),"message"===e&&this.ws.on("call",t),"event"===e&&this.ws.on("event",t),"call"===e&&this.ws.on("call",t),"monitor"===e&&this.ws.on("monitor",t)},e.prototype.emit=function(e,t,n){this.ws.emit(e,t,n)},e.prototype.disconnect=function(){this.ws.disconnect()},e}(),Hn=new(function(){function e(){var e=this;fetch("https://softphone.useasy.cn/ring.wav").then(function(e){return e.blob()}).then(function(t){var n=URL.createObjectURL(t);e.ringAudio=new Audio(n),e.ringAudio.loop=!0,e.ringAudioRunning=!1}),fetch("https://softphone.useasy.cn/hangup.wav").then(function(e){return e.blob()}).then(function(t){var n=URL.createObjectURL(t);e.handupAudio=new Audio(n),e.hangupAllow=!0})}return e.prototype.ringAudioPlay=function(){return o(this,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return[4,this.ringAudio.play()];case 1:return e.sent(),this.ringAudioRunning=!0,[2]}})})},e.prototype.ringAudioPause=function(){return o(this,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return this.ringAudio.paused?[3,2]:[4,this.ringAudio.pause()];case 1:e.sent(),this.ringAudioRunning=!1,e.label=2;case 2:return[2]}})})},e.prototype.activeHangup=function(){this.hangupAllow=!0},e.prototype.InvalidateHangup=function(){this.hangupAllow=!1},e.prototype.triggerTask=function(){return o(this,void 0,void 0,function(){return a(this,function(e){return this.hangupAllow?this.handupAudio.play():this.activeHangup(),[2]})})},e}()),$n=function(e,t){"WEBRTC"===e&&("ring"!==t.eventType||"callin"!==t.callType&&"inner"!==t.callType&&"twoWayCall"!==t.callType&&"transfer"!==t.callType&&"autoCallout"!==t.callType||!qn.isCanRing?Hn.ringAudioRunning&&Hn.ringAudioPause():Hn.ringAudioPlay(),"hangup"===t.eventType&&(Hn.triggerTask(),qn.isCanRing=!0))};export{qn as default};